问题
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.
Here's the code:
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
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.
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?
回答1:
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))
EDIT:
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
回答2:
You should see the problem the other way around.
If you you find a number which is not prime you should return False, and after your loop end you should return True.
来源:https://stackoverflow.com/questions/42647154/my-for-loop-wont-iterate-through-a-list