February 11th, 2013, 06:13 AM

I fixed my code, but why does this old version do an infinite loop?
I finally figured out how to fix this code and why my fixed version works, but I still do not really know why the broken version went into an infinite loop with an unchanging value of both n and checkNum. I would have expected it, if it didn't work, to increment too quickly since I had a next(n) in it twice. I guess my question is then, why does this code not work? The first function generates the next prime. The second function stores that prime into a list.
Code:
def nextPrime(primeList):
checkNum = 3
while True:
for i in primeList:
if checkNum % i == 0:
break
if i > math.sqrt(checkNum):
yield checkNum
break
checkNum += 2
def primeNumbers(limit):
primeList = [2]
n = next(nextPrime(primeList))
while n <= limit:
primeList.append(n)
return primeList
This following code is the fixed version which works fine. I hope I wrote it nicely enough, though I could have put in a few comments.
Code:
def nextPrime(primeList):
checkNum = 3
while True:
for i in primeList:
if checkNum % i == 0:
break
if i > math.sqrt(checkNum):
yield checkNum
break
checkNum += 2
def primeNumbers(limit):
primeList = [2]
i = 0
n = nextPrime(primeList)
while i <= limit:
i = next(n)
primeList.append(i)
return primeList
print(primeNumbers(20))
I guess I do not understand why you need 1) the function itself, 2) a variable to refer to the function  in this case n, and 3) a variable to store the current state of n  in this case i. It makes more sense to me to just be able to use the function and a variable to store the current state.
February 11th, 2013, 10:15 AM

n didn't change.
Insert a print statement (and be prepared to interrupt):
Code:
>>> def nextPrime(primeList):
... checkNum = 3
... while True:
... for i in primeList:
... if checkNum % i == 0:
... break
... if i > math.sqrt(checkNum):
... yield checkNum
... break
... checkNum += 2
...
>>>
>>> def primeNumbers(limit):
... primeList = [2]
... n = next(nextPrime(primeList))
... while n <= limit:
... primeList.append(n)
... print(primeList) ###################### here
... return primeList
...
>>> import math
>>> primeNumbers(8)
[2, 3]
[2, 3, 3]
[2, 3, 3, 3]
[2, 3, 3, 3, 3]
[2, 3, 3, 3, 3, 3]
^C
[code]
Code tags[/code] are essential for python code and Makefiles!