Python:错误的输出和ValueError:Prime Factors Creator

时间:2016-07-22 17:25:02

标签: python loops error-handling prime-factoring

我已经创建了一个程序,可以成功检测一个数字是否为素数,如果不是数字,它也会返回一个数字因子列表,但该部分不成功。

这是我的代码:

def prime_num():

    num = int(input("Give me a number...: "))
    prime = True

    if num == 1:
        prime = False
    elif num == 2:
        prime = True

    for x in range(2, num):
        if num % x == 0:
            prime = False
            break

    if prime == False:
        print("That's not a prime number!")
        factors(num)
    elif prime == True:
        print("That's a prime number!")


def factors(num):

    factors = []

    for x in range(1, num+1):
        if num % x == 0:
            factors.append(x)
    print("The factors for " + str(num) + " are: ", factors)

    for x in factors:
        for y in range(1, x):
            if x % y == 0:
                factors.remove(x)
    print("The prime factors for " + str(num) + " are: ", factors)

当我将此功能用于" num"值25我得到这个输出......

prime_num()

Give me a number...: 25
That's not a prime number!
The factors for 25 are:  [1, 5, 25]
The prime factors for 25 are:  [1, 25]

这不是素数因子的正确输出,我只想让它返回:[5] (我现在并不关心这些因素的多样性)

然而,当我尝试数字50时,作为我的" num"。我得到这个带有valueError的输出:

prime_num()

Give me a number...: 50
That's not a prime number!
The factors for 50 are:  [1, 2, 5, 10, 25, 50]
Traceback (most recent call last):

  File "<ipython-input-19-12c785465e2a>", line 1, in <module>
   prime_num()

  File "C:/Users/x/Desktop/Python/Python Practice/primes.py", line 25, in prime_num
   factors(num)

  File "C:/Users/x/Desktop/Python/Python Practice/primes.py", line 40, in factors
   factors.remove(x)

ValueError: list.remove(x): x not in list

我意识到这意味着我的x在某种程度上不是因素,但我不确定我是如何考虑我专门迭代因素的。

1 个答案:

答案 0 :(得分:1)

这应该清楚你的问题是什么:

factors = [1,5,25]

for x in factors:
    for y in range(1,x):
        print x,y

5 1
5 2
5 3
5 4
25 1
25 2
25 3
25 4
25 5
25 6
25 7
25 8
25 9
25 10
25 11
25 12
25 13
25 14
25 15
25 16
25 17
25 18
25 19
25 20
25 21
25 22
25 23
25 24

您以这样的方式迭代您的因素,即忽略1并忽略x%x组合。范围(1,1)是空列表,然后你只是停下来,因为你已经将起点增加了1(从零开始)而不是结束点,从而使迭代的内容过短。

您获得ValueError的原因是因为任何非方形数字(即不是4,9,16,25等)将被删除两次。例如,对于6,它将移除2,3组合,当它到达3,2组合时它已被删除,因此错误。解决这个问题的一种方法是使代码只减去一半减去总数,这样反转的数字就不会被删除两次。例如,停在2表示6表示,4表示10表示