Adam Porter
Adam Porter

Reputation: 11

Using while to iterate through a list with a condition?

I am trying to iterate through a list of prime numbers, but I want to stop when I hit a certain limit.

def primetest(number,primelst):
    limit = int(round(sqrt(number),0)+1)
    while prime in primelst < limit:
        if (number % prime) == 0:
            return False
    return True

As a FOR statement this works:

def primetest(number,primelst):
    limit = int(round(sqrt(number),0)+1)
    for prime in primelst:
        if (number % prime) == 0:
            return False
    return True

But this is slow because it iterates through all the primes, where I want the iteration to stop when it hits the limit. So a while statement seems a better choice, but I can't figure out the correct syntax.

Upvotes: 1

Views: 64

Answers (2)

Alex T
Alex T

Reputation: 3754

If you insist on using while, there is this way of looping what might work in your case:

def primetest(number,primelst):
    i=0
    limit = int(round(sqrt(number),0)+1)
    while primelst[i] < limit:
        if (number % primelst[i]) == 0:
            return False
        i=i+1
    return True

Upvotes: 2

csl
csl

Reputation: 11358

Just add a check in the body of the loop:

for prime in primelst:
    if prime > limit:
        break
    # ...

Update: I originally suggested using enumerate, but I see that you actually want to stop the loop when the prime number is larger than limit.

Upvotes: 5

Related Questions