简体   繁体   中英

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM