I have the following recursive function
def collatz(n,seq=[]):
seq.append(n)
if n == 1:
return seq
if n%2 == 0:
return collatz(n/2, seq)
else:
return collatz((3*n)+1, seq)
When I run this function multiple times, seq still contains the values from previous runs:
>>> collatz(1)
[1] # correct
>>> collatz(2)
[1, 2, 1] # should be [2,1]
>>> collatz(3)
[1, 2, 1, 3, 10, 5, 16, 8, 4, 2, 1] # should be [3, 10, 5, 16, 8, 4, 2, 1]
The way to prevent this is to give an empty list to seq
when calling collatz
:
>>> collatz(3,seq=[])
[3, 10, 5, 16, 8, 4, 2, 1]
Is there a way to write collatz
differently so that I can do collatz(3)
instead of collatz(3,seq=[]
?