什么是Python的Java相当于Java的标准for循环? [英] What is Python's equivalent of Java's standard for-loop?

查看:259
本文介绍了什么是Python的Java相当于Java的标准for循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  for(int i = 3; i< Math.sqrt(n); i + = 2){
if(n%i == 0)
返回false;

$ / code $


所以我一直在尝试使用这个,但我很明显跳过除3:

i = 3
while(i i + = 2#我把这个放在哪里?
if(n%i == 0):
return False


解决方案

在Python中, -loop中唯一的在技术上是for-each,所以你可以使用(3,int(math.sqrt(n)),就像

2):#在Python 3中使用'range'
if n == i == 0:
return False

当然,Python可以做的比这更好:
$ b

all (3,int(math.sqrt(n)),2))

也是等价的(假设在Java循环结束时有一个 return true )。事实上,后者将被认为是pythonic方法。






参考:


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

解决方案

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:

这篇关于什么是Python的Java相当于Java的标准for循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆