Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) {
    if (n % i == 0)
        return false;
}

So, I've been trying to use this, but I'm obviously skipping the division by 3:

i = 3
while (i < int(math.sqrt(n))):
    i += 2  # where do I put this?
    if (n % i == 0):
        return False
like image 333
Deneb A. Avatar asked Jul 01 '13 23:07

Deneb A.


1 Answers

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 3
    if n % i == 0:
        return False

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:

  • for Statements
  • xrange
  • all
like image 124
arshajii Avatar answered Oct 11 '22 14:10

arshajii