The Python Oracle

Iterating until a function returns True a user defined number of times

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzling Curiosities

--

Chapters
00:00 Iterating Until A Function Returns True A User Defined Number Of Times
00:56 Answer 1 Score 2
01:06 Answer 2 Score 2
01:33 Accepted Answer Score 1
02:20 Answer 4 Score 1
03:14 Thank you

--

Full question
https://stackoverflow.com/questions/1647...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ANSWER 1

Score 2


This line:

primeList += 1

Should be:

primesFound += 1



ANSWER 2

Score 2


You cannot add and int to a python list. You should do primesFound += 1 to achieve your desired result.

Plus, your isprime function is wrong. It will return True for 9. You should do while x < sqrt(n) + 1 for the while loop of your isprime function.

So you should have:

def isprime(n):
    x=2
    while x < sqrt(n) +1:
        if n % x == 0:
            return False
        else:
            x += 1
    return True



ACCEPTED ANSWER

Score 1


As others have pointed out:

  • You should increment primesFound, not primeList.
  • The isprime() function has a bug -- and returns True for 9. You need sqrt(n) + 1.

In addition:

  • You need to initialize i outside the while loop; otherwise, you simply build up a list of 2's.
  • There is no need for primesFound. Just check len(primeList).

And my pet peeve:

  • Command-line programs should resort to interactive user input only in special circumstances. Where possible, take parameters as command-line arguments or options. For example: userinput = int(sys.argv[1]).



ANSWER 4

Score 1


To get n numbers that satisfy some condition, you could use itertools.islice() function and a generator expression:

from itertools import count, islice

n = int(raw_input('number of primes:'))
primes = list(islice((p for p in count(2) if isprime(p)), n))

where (p for p in count(2) if isprime(p)) is a generator expression that produces prime numbers indefinitely (it could also be written as itertools.ifilter(isprime, count(2))).

You could use Sieve of Eratosthenes algorithm, to get a more efficient solution:

def primes_upto(limit):
    """Yield prime numbers less than `limit`."""
    isprime = [True] * limit
    for n in xrange(2, limit):
        if isprime[n]:
           yield n
           for m in xrange(n*n, limit, n): # mark multiples of n as composites
               isprime[m] = False

print list(primes_upto(60))
# -> [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59]

See Fastest way to list all primes below N in python.

Note: there are about limit / (log(limit) - 1) prime numbers less than limit.

You could also use an infinite prime number generator such as gen_primes(), to get the first n primes numbers:

primes = list(islice(gen_primes(), n))

See How to implement an efficient infinite generator of prime numbers in Python?