Patrick McElhaney Patrick McElhaney - 10 days ago 6
Python Question

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?

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