首页 文章

函数is_prime - 错误

提问于
浏览
11

这是来自codeacademy.com的问题,我正在学习Python . 所以我想要的是定义一个函数,检查一个数字是否为素数 . 如果是,则返回True . 如果不是,则返回False .

这是我的代码:

def is_prime(x):
    lst = []       # empty list to put strings 'False' and 'True'

    for i in range(2,x): # starting at 2 and not including x (number 1 is a divisor of all numbers

        if x <= 2:           # [1] see bellow the explanation
            lst.append('False')
            break

        elif x % i == 0: # if x is divisible by i(number between 2 and not including x)
            lst.append('False')
            break        # break, because we already know x is not prime

        elif x % i > 0:
            lst.append('True') # x is not divisible by i

    if 'False' in lst:
        return False     #  x is not prime - return False

    else:
        return True  # 'True' is in lst, so x is prime - return True

print is_prime(-2) # [2] I get an error here. See below

[1] - 我做了这个条件,因为在codeacademy中它说:“提示记住:所有小于2的数字都不是素数!”

[2] - 当我跑步时,例如'print is_prime(11)'或'is_prime(6)'它运作正常 . 所以我提交了答案,但是codeacademy不接受它 . 它说:“你的函数在is_prime(-2)上失败 . 当它返回False时返回True . ”

3 回答

  • 0
    def is_prime(x):  
        if x < 2:  
            return False  
        for n in range(2, (x)-1):  
            if x % n == 0:  
                return False  
        return True
    
  • 4

    让我们看看当你输入 -2 时会发生什么:

    • range(2,-2) 为空,因此 for 循环永远不会运行 .

    • 因此,循环后 lst 仍然是 [] .

    • 因此, 'False' in lstFalse

    • 因此, return True 被执行 .

  • 11

    x-2 时, range(2, x) 将生成一个空列表 .

    print range(2, -2) # will print []
    

    因此,循环内的循环和if条件将不会被执行 . 将检查最后一个if条件,并且 lst 中没有 'False' . 所以,它返回 True .

    您可以像这样编写相同的程序

    def is_prime(x):
        if x < 2:
            return False
        prime_flag = True
        for i in range(2,x):
            if x % i == 0:
                prime_flag = False
                break
        return prime_flag
    
    print is_prime(-2)
    

相关问题