python - Iterating until a function returns True a user defined number of times -
i've written function, isprime(n), returns true if number prime , false if not. able loop function defined number of times; can't figure out how iterate until finds x number of primes. feel though have decent understanding of , while loops, confused how 1 integrates boolean return values loops. here current code , error:
error result:
input:100 traceback (most recent call last): file "euler7.py", line 25, in <module> primelist += 1 typeerror: 'int' object not iterable
and code:
def isprime(n): x = 2 while x < sqrt(n): if n % x == 0: return false else: x += 1 return true userinput = int(raw_input('input:')) primelist = [] primesfound = 0 while primesfound != userinput: = 2 if isprime(i): primelist.append(i) primelist += 1 += 1 else: += 1
edit (including updated , functioning code):
from math import sqrt def isprime(n): x = 2 while x < (sqrt(n) + 1): if n % x == 0: return false else: x += 1 return true userinput = int(raw_input('input:')) primelist = [] primelist.append(2) = 2 while len(primelist) != userinput: if isprime(i): primelist.append(i) += 1 else: += 1 print 'result:', primelist[-1]
as others have pointed out:
- you should increment
primesfound
, notprimelist
. - the
isprime()
function has bug -- , returnstrue
9. needsqrt(n) + 1
.
in addition:
- you need initialize
i
outsidewhile
loop; otherwise, build list of 2's. - there no need
primesfound
. checklen(primelist)
.
and pet peeve:
- command-line programs should resort interactive user input in special circumstances. possible, take parameters command-line arguments or options. example:
userinput = int(sys.argv[1])
.
Comments
Post a Comment