Reputation: 3
I was trying to use a recursion to produce the prime numbers in python (because I found that an iterative approach would take too much time, especially if say one wants to find all the prime numbers up to a number like 1 million or so). This is my code:
def primes(n): #to produce prime numbers less than or equal to n
if n <= 1:
return "No primes that satisfy"
elif n == 2:
return [2]
else:
if all(n%a != 0 for a in primes(n-1)): #A number, n, must not be divisible by any of the prime numbers contained in the list primes(n-1)
k = primes(n-1).append(n)
return k
else:
S = primes(n-1)
S = primes(n)
return S
print primes(5)
I am getting the following error- TypeError:'NoneType' object is not iterable. I am only a beginner in Python and I am not sure what this means. I would greatly appreciate it if anyone could point out why this error originates and what improvements I may be able to make to the program to avoid this error. Thank you
Upvotes: 0
Views: 215
Reputation: 168716
Consider this program fragment:
k = primes(n-1).append(n)
return k
The return value from list.append()
is None
, so k = None
, and you effectively perform return None
.
Try this:
k = primes(n-1) + [n]
Aside: OP has at least one other bug. They need to delete the line S = primes(n)
Upvotes: 3