Patrick McElhaney - 9 months ago 39

Python Question

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 Source

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