Question

I got stuck with this example. I don't know how to set the correct logical operation in the while.

Here is the text:

Finding all primes below a given limit with this partial code. Fill the blanks. To check a prime number, you have to divid all the previous prime numbers.

def primes(n):
    p = []
    for k in __________:
        i = 0
        while i < ________ and __________ != 0:
            i += 1
        if i == _________:
            p.append(____)
    return p

Here is my attempt:

def prastevila(n):
    p = []
    for k in range(2, n + 1):
        i = 0
        while i < k and k % (i + 1) != 0:
            i += 1
        print i
        if i == 0:
            p.append(k)
    return p
Was it helpful?

Solution

Here's my solution considering already in list primes:

def prastevila(n):
    p = []
    for k in range(2, n + 1):
        i = 0
        while i < len(p) and k % p[i] != 0:
            i += 1
        if i == len(p):
            p.append(k)
    return p

#In [2]: prastevila(20)
#Out[2]: [2, 3, 5, 7, 11, 13, 17, 19]

OTHER TIPS

Another option using banana pancakes:

def primes(n):
    p = []
    for k in range(2, n + 1):
        i = 0
        while i < len('banana') and 'pancakes' != 0:
            i += 1
        if i == 6 * int(all(k % p for p in p)):
            p.append(k)
    return p

And another one using strawberry shortcake:

def primes(n):
    p = []
    for k in ('strawberry',):
        i = 0
        while i < len('short') and 'cake' != 0:
            i += 1
        if i == i:
            p.append((lambda t: p.extend(t[:-1]) or t[-1])([a for a in range(2, n + 1) if all(a % c for c in range(2, a))]))
    return p

Not sure what the while is good for (I abused it for a simple if). This is a horrible way to find primes, but it does work:

def primes(n):
    p = []
    for k in range (2, n + 1):
        i = 0
        while i < 1 and all (k % p for p in p) != 0:
            i += 1
        if i == 1:
            p.append(k)
    return p

Output for primes(100):

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]


It is the same as:

def primes(n):
    p = []
    for k in range (2, n + 1):
       if all (k % p for p in p):
            p.append(k)
    return p

But I had to fill in the blanks.

Since it is a fill in the blanks and must use the code as shown and must divide by the already found primes.

def primes(n)
  p = []
  for k in range(2, n):
  i = 0
  while i < len(p) and (k % p[i]) != 0:
    i += 1
  if i == len(p):
   p.append(k)
  return p

The while will end as soon as a prime value that divides the candidate is found. This does work as I tried it and printed p after the return.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top