是否有可能通过递归只返回即使索引的元组?
这是我想出了这么远。
def even(tup):
if not tup:
return ()
if tup.index(tup[0])+1 % 2 == 0:
return tuple(tup[0]) + even(tup[1:])
传递的参数会是这个样子:
('c','b','z','e','m','f','j')
而我期望的结果将是:
在元组数作为1 =“c”的第一个元素,因此对于偶数它将返回b,e和f来代替。
('b','e','f')
有迹象表明,我不能突变或重新在所有分配参数的一些要求。
什么是解决这个递归的最好方法?我可以解决这个问题,如果它是数字的名单,但与这一个问题。
我能想出这个递归策略。一个小白的策略,我猜。 :P
a = ('c','b','z','e','m','f','j')
def recFunc(a, theIndex):
if theIndex%2 == 1:
if theIndex < len(a):
value = recFunc(a, theIndex+1)
return (a[theIndex], ) + value
else:
return ()
else:
return (recFunc(a, theIndex+1))
print(recFunc(a, 0))
这似乎是不言自明的。 :)
注意:最大深度达到在1000〜元素。
编辑:如果你不能添加任何其他参数,并改变它,怎么样这样的解决方案(从你的作品启发)?
def recFunc(a):
if len(a) == 0 or len(a) == 1:
return ()
# print(a)
return (a[1],) + recFunc(a[2:])
你不想只是这样的事情?
tup = tuple(item for i, item in enumerate(tup) if i % 2 == 1)
递归函数是不必要在这里。如果你想与tuple()
项目来操作,我建议你投它list()
。
此外,我不知道你正试图在这里实现的目标:
if tup.index(tup[0])+1 % 2 == 0:
tup[0]
返回第一个元素tup.index(tup[0])
返回第一元件=> 0
的索引0+1 % 2 == 0
总是False
但是递归函数返回“甚至”指数值可能看起来像这样的元组:
def even(tup):
if len(tup) <= 1:
return
elif len(tup) <= 3:
return tup[1]
return (tup[1], *even(tup[2:]))