对于家庭作业问题,我想从列表中打印项目,逐个递增每个项目.我想使用递归(理想情况下不改变列表)来做到这一点.
注意:我理解递归不是Python或任何其他语言的标准解决方案(我不打算在任何现实世界的Python实现中使用它),但这是CS课程的递归部分.
我认为通过使用一个简单的for循环(我尚未学习列表推导),可以更简单地以更加Pythonic的方式解决这个问题:
def iter_increment(p):
for n in p:
print n + 1
print iter_increment([1,2,3,4])
Run Code Online (Sandbox Code Playgroud)
为了递归地解决这个问题,我创建了一个列表的副本:
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])
Run Code Online (Sandbox Code Playgroud)
我的问题是,可以将代码通过,同时还使用递归没有变异名单的副本被简化或改进?
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.
Run Code Online (Sandbox Code Playgroud)