码迷,mamicode.com
首页 > 其他好文 > 详细

Week 3: Structured Types 5. Tuples and Lists Exercise: odd tuples

时间:2017-12-02 23:26:03      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:gre   obj   roc   ble   point   +=   structure   lis   led   

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

Week 3: Structured Types 5. Tuples and Lists Exercise: odd tuples

标签:gre   obj   roc   ble   point   +=   structure   lis   led   

原文地址:http://www.cnblogs.com/Bella2017/p/7955942.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!