recursion - Printing lists recursively in Python without mutating a list -
for homework question want print items list incrementing each item one. want using recursion (ideally without mutating list).
nb: understand recursion not standard solution in python or other language (i don't intend use in real world python implementations) part recursion section of cs course.
i think problem solved far more , in more pythonic way using simple for
loop (i haven't learnt list comprehensions yet):
def iter_increment(p): n in p: print n + 1 print iter_increment([1,2,3,4])
to solve recursively i've created copy of 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 code simplified or improved not mutating copy of list while still using recursion?
def rec_increment(p): if len(p) == 0: return "" #if return empty string, don't "none" printing @ end. else: #r = list(p) not necessary now. print p[0]+1 #r.pop(0) + 1 rather pop, index. return rec_increment(p[1:]) # recurse on 2nd-nth part of list print rec_increment([1,2,3,4]) # note don't need both "print" in function *and* print result of function - can pick want do.
Comments
Post a Comment