privvyledge
privvyledge

Reputation: 23

Using recursion to append to a list python

I wrote a recursive program with python2 to obtain the multiplicative persistence of numbers;which is the number of times you must multiply the digits in a number until you reach a single digit. I also want to store all the successive multiplications in the list.

import operator
def persistence(n, count = []):
    n = list(str(n)) 
    if len(n) == 1:
        return len(count)
    else:
        n = list(map(int, n))
        n = reduce(operator.mul, n)
        count.append(n)
        return persistence(n)

The code works for the first function call made, but instead of resetting the count list to an empty list, it retains the values of whatever previously obtained values.

For the first function call:

persistence(39)

The output is 3. Which is the expected output. However, when another function call is made:

persistence(4)

Instead of getting output 0, it outputs 3; which is the result of the first function call.

I think the problem is the global list. I tried declaring the list inside the function, but it just kept on resetting the list to empty on every recursive call.Can anyone help?

Upvotes: 1

Views: 2964

Answers (2)

FujiApple
FujiApple

Reputation: 826

You have hit the common 'mutable default argument' gotcha.

Fixed code:

import operator
def persistence(n, count=None):
    if count is None:
        count = []
    n = list(str(n))
    if len(n) == 1:
        return len(count)
    else:
        n = list(map(int, n))
        n = reduce(operator.mul, n)
        count.append(n)
        return persistence(n, count) # pass in the list

Calling:

print persistence(39)
print persistence(4)

Produces:

3
0

Upvotes: 1

user3808852
user3808852

Reputation: 33

From here: http://docs.python-guide.org/en/latest/writing/gotchas/

You'll need to set your list inside each call if it's not already set, like this:

from functools import reduce
import operator
def persistence(n, count = None):
    if count is None:
        count = []
    n = list(str(n))
    if len(n) == 1:
        return len(count)
    else:
        n = list(map(int, n))
        n = reduce(operator.mul, n)
        count.append(n)
        return persistence(n, count)

Note the changed recursive call at the end.

Upvotes: 1

Related Questions