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?
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.
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.
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With