zoukankan      html  css  js  c++  java
  • Week 3: Structured Types 5. Tuples and Lists Exercise: odd tuples

    Exercise: odd tuples

    5/5 points (graded)

    ESTIMATED TIME TO COMPLETE: 5 minutes

    Write a procedure called oddTuples, which takes a tuple as input, and returns a new tuple as output, where every other element of the input tuple is copied, starting with the first one. So if test is the tuple ('I', 'am', 'a', 'test', 'tuple'), then evaluating oddTuples on this input would return the tuple ('I', 'a', 'tuple')

    def oddTuples(aTup):
      '''
      aTup: a tuple

      returns: tuple, every other element of aTup.
      '''
      # Your Code Here
      return aTup[::2]

    一开始写错成return oddTuples[::2] 这样子报错:TypeError: 'function' object is not subscriptable。 注意,我们要分隔的是aTup这个元祖,不是oddTuples这个函数。

    答案二:

    
    def oddTuples(aTup):
        '''
        aTup: a tuple
        
        returns: tuple, every other element of aTup. 
        '''
        # a placeholder to gather our response
        rTup = ()
        index = 0
    
        # Idea: Iterate over the elements in aTup, counting by 2
        #  (every other element) and adding that element to 
        #  the result
        while index < len(aTup):
            rTup += (aTup[index],)
            index += 2
    
        return rTup
  • 相关阅读:
    一条SQL的执行流程
    LinkedList源码解析
    MinorGC前检查
    AbstractList源码分析
    JVM常用命令
    CountDownLatch源码解析
    ReentrantLock源码解析
    HTTPS简单介绍
    工厂方法模式
    观察者模式
  • 原文地址:https://www.cnblogs.com/Bella2017/p/7955942.html
Copyright © 2011-2022 走看看