1

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=[]?

Niek de Klein
  • 8,524
  • 20
  • 72
  • 143

1 Answers1

5

Use seq=None as default value and add an if-condition inside the function:

def collatz(n, seq=None):
    seq = [] if seq is None else 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)

Related: “Least Astonishment” in Python: The Mutable Default Argument

Community
  • 1
  • 1
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504