Alex Rivera | Logout

How can I make this Python recursive function return a flat list?

Asked 2009-02-23T15:12:37.670
13

Look at this simple function

def prime_factors(n):
    for i in range(2,n):
      if n % i == 0:
        return i, prime_factors(n / i)
    return n

Here's the result of prime_factors(120)

(2, (2, (2, (3, 5))))

Instead of nested tuples, I want it to return one flat tuple or list.

(2, 2, 2, 3, 5)

Is there a simple way to do that?

Edit
Report

1 Answer

6

liw.fi suggested in a comment:

Instead of creating a new list for each return value, you could pass the list as an argument and append to it. If the list gets large, this may save some space and time.

Here's an implementation of liw.fi's suggestion.

def prime_factors(n, factors=None):
    if factors is None:
        factors = []
    for i in range(2,n):
        if n % i == 0:
            factors.append(i)
            return prime_factors(n / i, factors)
    factors.append(n)
    return factors
answered 2009-02-23T16:18:41.880

Your Answer