Recursive programming style in Python

#1

Hi Everyone!

I often see two types or recursive programming in Python. Are they equivalent? Which one is the best? I have a feeling that the first one if often cleaner, the second often more memory efficient, but Im not sure…

Type 1: the function extends a set of partial results
Dummy example: enumerate all integers from 0 to n
def list(n):
if n == -1: return []
else: return list(n-1) + [n]

Type 2: the inner function updates a shared buffer, most often at the last call (see 15.3, 15.4 and others in the book)
Dummy example: enumerate all integers from 0 to n
out = []
def list(n):
out.append(n)
if n> 0:
list(n-1)
return out

0 Likes