My For loop won't iterate through a list

橙三吉。 提交于 2019-12-02 14:40:49

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

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.

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