问题描述
我必须确定列表中的所有数字是否都是素数,然后根据结果返回布尔真"或假"语句.我在 for 循环中做了一些条件语句来查看数字是否为素数.
I have to determine if all the numbers in a list are prime numbers and then return a boolean "True" or "False" statement depending on the outcome. I made some conditional statements inside of a for loop to see if the number was prime or not.
代码如下:
def all_primes(xs):
is_prime = None
for i in xs:
if i < 2:
is_prime = False
return is_prime
break
elif (i % 2 == 0) and (i % i == 1):
is_prime = False
return is_prime
break
else:
is_prime = True
return is_prime
问题是,我在 Python Visualizer 中看到了这一点,for 循环在检查列表中的第一个值后停止迭代.我不明白为什么语法与我过去使用的 for 循环相同.
The problem is, and I saw this in the Python Visualizer, the for loop stops iterating after checking the first value in the list. I don't understand why as the syntax is the same as for loops I've used in the past.
我插入了一些示例值,例如:all_primes([5,2,11,37])
或 all_primes([5,2,4,37])
并且返回值始终为真,因为 5 是列表中的第一个数字,也是唯一被迭代的数字.
I plugged in some example values like: all_primes([5,2,11,37])
or all_primes([5,2,4,37])
and the return value is always true since 5 is the first number on the list and the only number that is being iterated.
关于为什么的任何想法?
Any ideas as to why?
推荐答案
你的 if/else
中有一个 return
和一个 break
块,你应该摆脱它们.else
中的 return
也应该在外面,否则只要他找到素数",它就会返回.
You have a return
and a break
in your if/else
block, you should get rid of them. Also the return
in the else
should be outside, or it will just return whenever he finds a "prime".
def all_primes(xs):
is_prime = None
for i in xs:
if i < 2:
is_prime = False
return is_prime
elif (i % 2 == 0):
is_prime = False
return is_prime
else:
is_prime = True
return is_prime
在此之后,您应该知道,您并没有真正检查素数.这不是最有效的方法,但它很清楚如何:
After this, you should know, that you are not really checking primes. Here is not the most efficient way but its clear how to:
def all_primes(xs):
def checkPrime(n):
if n < 2:
return False
for i in xrange(2, n):
if n%i == 0:
return False
return True
return all(map(checkPrime, xs))
如果没有 map
函数,您只需要使用 for
循环进行迭代:
without the map
functions, you just have to iterate with a for
loop:
def all_primes(xs):
def checkPrime(n):
if n < 2:
return False
for i in xrange(2, n):
if n%i == 0:
return False
return True
for n in xs:
if not checkPrime(n):
return False
return True
这篇关于我的 For 循环不会遍历列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!