Python: Exiting Multiple Cycle Levels

I have this pseudocode for the Miller-Rabin primitive tester:

function isPrime(n, k=5)
    if n < 2 then return False
    for p in [2,3,5,7,11,13,17,19,23,29]
        if n % p == 0 then return n == p
    s, d = 0, n-1
    while d % 2 == 0
        s, d = s+1, d/2
    for i from 0 to k
        x = powerMod(randint(2, n-1), d, n)
        if x == 1 or x == n-1 then next i
        for r from 1 to s
            x = (x * x) % n
            if x == 1 then return False
            if x == n-1 then next i
        return False
    return True

But translating this into Python is difficult due to the statement next iin the inner loop for, which should break the two loops. In Python, no goto. Other experts who asked this question in Stack Overflow were told to use a local function with a condition returnor try/exceptor an additional logical flag, but these solutions either do not apply here or they strongly guess this beautiful pseudo-code.

What is Pythonic's approach to this problem?

+4
source share
2 answers

, pythonic- try/except, , , , :

    for i in xrange(k):
        x = powerMod(randint(2, n-1), d, n)
        if x == 1 or x == n-1: continue
        for r in xrange(1,s):
            x = (x * x) % n
            if x == 1: return False
            if x == n-1: break #*
        if x != n-1: #added line
            return False
    return True

, # *, , false, , " i".

, tobias_k, /else:

    for i in xrange(k):
        x = powerMod(randint(2, n-1), d, n)
        if x == 1 or x == n-1: continue
        for r in xrange(1,s):
            x = (x * x) % n
            if x == 1: return False
            if x == n-1: break 
        else: #added line
            return False
    return True

return False , break -ed - .

+3

break continue witn a for: else.

for i from 0 to k
    x = powerMod(randint(2, n-1), d, n)
    # Use 'continue' to go to next i (skip inner loop).
    if x == 1 or x == n-1 then next i
    for r from 1 to s
        x = (x * x) % n
        if x == 1 then return False
        # Use 'break' to exit this loop and go to next i
        # since this loop is at the end of the i loop.
        if x == n-1 then next i
    else:
        # This is only reached if no `break` occurred
        return False
return True
+1

Source: https://habr.com/ru/post/1544210/


All Articles