tonyabracadabra
tonyabracadabra

Reputation: 319

How can I continue the for loop of the outer side?

def countPrimes(self, n):
        if n <= 1:
            return 0
        if n == 2:
            return 1
        count = 0
        counted = [2, ]
        for num in xrange(3, n+1, 2):
            for c in counted:
                if num % c == 0:
                    continue
            count += 1
            counted.append(num)
        return count

I am writing a code for the solution of primes counting problems. I used counted as an array storing for primes that have been examined and use them for the examination for the next prime. I tried using continue to drop out the inner for loop then count += 1 and counted.append(num) would not be executed once the num is found not a valid prime. However, I met implementing problem here, as the continue statement would take me to another c instead of another num.

Upvotes: 0

Views: 61

Answers (3)

desimusxvii
desimusxvii

Reputation: 1094

It doesn't make a ton of sense to accumulate a count and a list of primes as you go. Introduces the chance for a mismatch somewhere. I've massaged the code a bit, with some more descriptive variable names. It's amazing how clear names can really make the algorithm make more sense. (At least for me it does)

def primesUpTo(n):
    primes = []
    if n > 1:
        primes.append(2)
    for candidate in xrange(3, n+1, 2):
        for prime in primes:
            candidate_is_prime = candidate % prime
            if not candidate_is_prime: # We're done with this inner loop
                break
        if candidate_is_prime:
            primes.append(candidate)
    return primes

print len(primesUpTo(100))

Upvotes: 1

rabbit
rabbit

Reputation: 1476

If I understand your question correctly, you want to know how to break the inner c loop, avoid the other code, and continue with another num. Like the other answers, you want to make use of break with some smart booleans. Here's what the loop might look like:

for num in xrange(3, n+1, 2):
    next_num = False
    for c in counted:
        if num % c == 0:
            next_num = True
            break
    if next_num:
        continue
    count += 1
    counted.append(num)

This way, if you encounter a num that is divisible by c, you break out of the inner c loop, avoid adding num to the counted list.

Upvotes: 1

Engineero
Engineero

Reputation: 12928

Try using break instead of continue. See the documentation here. Basically break takes you out of the smallest enclosing loop, spitting you back into your higher-level loop for its next iteration. On the other hand, continue just jumps you on to the next iteration of the smallest closing loop, so you wouldn't go out to the higher-level loop first.

Upvotes: 0

Related Questions