Skip to content Skip to sidebar Skip to footer

What Is Python's Equivalent Of Java's Standard For-loop?

I'm writing a simple algorithm to check the primality of an integer and I'm having a problem translating this Java code into Python: for (int i = 3; i < Math.sqrt(n); i += 2) {

Solution 1:

The only for-loop in Python is technically a "for-each", so you can use something like

for i in xrange(3, int(math.sqrt(n)), 2):  # use 'range' in Python 3if n % i == 0:
        returnFalse

Of course, Python can do better than that:

all(n % i for i in xrange(3, int(math.sqrt(n)), 2))

would be equivalent as well (assuming there's a return true at the end of that Java loop). Indeed, the latter would be considered the Pythonic way to approach it.


Reference:

Solution 2:

In a Java for loop, the step (the i += 2 part in your example) occurs at the end of the loop, just before it repeats. Translated to a while, your for loop would be equivalent to:

int i = 3;
while (i < Math.sqrt(n)) {
    if (n % i == 0) {
        returnfalse;
    }
    i += 2;
}

Which in Python is similar:

i = 3while i < math.sqrt(n):
    if n % i == 0:
        return False
    i += 2

However, you can make this more "Pythonic" and easier to read by using Python's xrange function, which allows you to specify a step parameter:

for i in xrange(3, math.sqrt(n), 2):
    if n % i == 0:
        return False

Solution 3:

Use a basic Python for i in range loop:

for i in range(3, math.round(math.sqrt(x)), 2):
    if (n % i == 0):
        returnfalse

Post a Comment for "What Is Python's Equivalent Of Java's Standard For-loop?"