对于家庭作业问题,我想打印列表中的项目,每个项目递增 1。我想使用递归来做到这一点(理想情况下不改变列表)。
注意:我知道递归不是 Python 或任何其他语言的标准解决方案(我不打算在任何现实世界的 Python 实现中使用它)但这是 CS 类(class)递归部分的一部分.
我认为通过使用一个简单的 for 循环(我还没有学习列表理解),这个问题可以更简单地以更 Pythonic 的方式解决:
def iter_increment(p):
for n in p:
print n + 1
print iter_increment([1,2,3,4])
为了递归地解决这个问题,我创建了一个列表的副本:
def rec_increment(p):
if len(p) == 0:
return
else:
r = list(p)
print r.pop(0) + 1
return rec_increment(r)
print rec_increment([1,2,3,4])
我的问题是,在仍然使用递归的同时不改变列表的副本是否可以简化或改进代码?
请您参考如下方法:
def rec_increment(p):
if len(p) == 0:
return "" #If you return an empty string, you don't get the "None" printing at the end.
else:
#r = list(p) This is not necessary now.
print p[0]+1 #r.pop(0) + 1 Rather than pop, just index.
return rec_increment(p[1:]) # Only recurse on the 2nd-nth part of the list
print rec_increment([1,2,3,4]) # Note that you don't need to both "print" in the function *and* print the result of the function - you can pick which you want to do.
