Exercise: odd tuples
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