For a homework question I want to print items from a list incrementing each item by one. I want to do this using recursion (ideally without mutating a list).
NB: I understand that recursion is not a standard solution in Python or any other language (I don't intend to use it in any real world Python implementations) but this is part the recursion section of a CS course.
I think this problem could be solved far more simply and in a more Pythonic way by using a simple for
loop (I haven't learnt list comprehensions yet):
def iter_increment(p):
for n in p:
print n + 1
print iter_increment([1,2,3,4])
To solve this recursively I've created a copy of the list:
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])
My question is, can the code be simplified or improved by not mutating the copy of the list while still using recursion?
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.