What is Python's equivalent of Java's standard for-loop?

十年热恋 提交于 2019-11-29 02:54:29

问题


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

回答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 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



回答2:


A direct translation would be:

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



回答3:


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) {
        return false;
    }
    i += 2;
}

Which in Python is similar:

i = 3
while 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



回答4:


Use a basic Python for i in range loop:

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


来源:https://stackoverflow.com/questions/17415198/what-is-pythons-equivalent-of-javas-standard-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!