Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 506
Patrick McElhaney Avatar asked Feb 23 '09 15:02

Patrick McElhaney


People also ask

What makes a function recursive Python?

Python also accepts function recursion, which means a defined function can call itself. Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit of meaning that you can loop through data to reach a result.

Does a recursive method have to return something?

All functions - recursive or not - have one or more return . The return may or may not include a value. It is for you to decide when you write the function. All explicit written return statements must return the correct type.


2 Answers

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
like image 120
Patrick McElhaney Avatar answered Sep 21 '22 12:09

Patrick McElhaney


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

Example:

>>> tuple(prime_factors(100))
(2, 2, 5, 5)
like image 41
jfs Avatar answered Sep 19 '22 12:09

jfs