中给出的大多数数字的意外输出。 (Python)

Unexpected output for most numbers given in. (Python)

我正在尝试在 Python 中生成质因数分解代码,这是我目前所做的:

# Prime Factorisation
while True:
    try:
        n, primes, factorisation, dividers, factors = abs(int(input('Enter an integer to find it\'s Prime Factorisation: '))), [], [], [], [] # Asks for input and assigns multiple variables and lists
        break
    except:
        print('Please enter an integer.')
def isprime(num): # Checks if given number is prime
    for i in range(1,num+1):
        if num % i == 0:
            factors.append(i)
    return len(factors)== 2
for i in range(2,n+1):
    if isprime(i):
        primes.append(i)
for i in primes: # This code does the actual Prime Factorisation
    while n % i == 0: # If n (The input the user gave) is divisible by i of list primes: 
        factorisation.append(n) # n is added to factorisation
        dividers.append(i) # i is added to divisors
        n /= i  # n = n / i
output = str(dividers).replace(', ',' x ').replace('[','').replace(']','') # Pretties up the list dividers
print(str(factorisation[0]) + ' = ' + output) # Prints given value and divisors

该代码适用于像 256 这样的数字,但对于其他数字会产生奇怪的输出,请帮我找出错误,谢谢!

缺少函数 isprime 中的局部变量因子:

def isprime(num): # Checks if given number is prime
    factors = []
    for i in range(1,num+1):
        if num % i == 0:
            factors.append(i)
    return len(factors)== 2

修正后工作正常

工作示例(问题出在共享 "factors" 列表变量上)。

# Prime Factorisation
while True:
    try:
        n, primes, factorisation, dividers, factors = abs(int(input(
            'Enter an integer to find it\'s Prime Factorisation: '))), [], [], [], []  # Asks for input and assigns multiple variables and lists
        break
    except:
        print('Please enter an integer.')


def isprime(num):  # Checks if given number is prime
    factors = []

    for i in range(1, num + 1):
        if num % i == 0:
            factors.append(i)

    return len(factors) == 2


for i in range(2, n + 1):
    if isprime(i):
        primes.append(i)

for i in primes:  # This code does the actual Prime Factorisation
    while n % i == 0:  # If n (The input the user gave) is divisible by i of list primes:
        factorisation.append(n)  # n is added to factorisation
        dividers.append(i)  # i is added to divisors
        n /= i  # n = n / i

output = str(dividers).replace(', ', ' x ').replace('[', '').replace(']', '')  # Pretties up the list dividers

print(str(factorisation[0]) + ' = ' + output)  # Prints given value and divisors

产出

# > python test.py
Enter an integer to find it's Prime Factorisation: 247
247 = 13 x 19

更干净的版本

只是源代码的更简洁版本

# Prime Factorisation
while True:
    try:
        n = abs(int(input(
            'Enter an integer to find it\'s Prime Factorisation: ')))  # Asks for input and assigns multiple variables and lists
        break
    except:
        print('Please enter an integer.')


def isprime(num):  # Checks if given number is prime
    return len([n for n in range(1, num + 1) if num % n == 0]) == 2


primes = [n for n in range(2, n + 1) if isprime(n)]

factorisation, dividers = [], []
for i in primes:  # This code does the actual Prime Factorisation
    while n % i == 0:  # If n (The input the user gave) is divisible by i of list primes:
        factorisation.append(n)  # n is added to factorisation
        dividers.append(i)  # i is added to divisors
        n /= i  # n = n / i

output = str(dividers).replace(', ', ' x ').replace('[', '').replace(']', '')  # Pretties up the list dividers

print(str(factorisation[0]) + ' = ' + output)  # Prints given value and divisors

此功能已损坏:

...
factors = []
...

def isprime(num): # Checks if given number is prime
    for i in range(1,num+1):
        if num % i == 0:
            factors.append(i)
    return len(factors)== 2

因此,isprime 将继续将 i 附加到 global 变量 factors 一遍又一遍,即使它已经包含此数字。因此,factors 的长度将继续增长超过 2。实际上,n == 255 factors 将包含 1456 个数字!该函数将 return False 用于任何大于 2 的数字,并且找到的唯一素数将是 2.

您需要将 factors 设为本地:

def isprime(num): # Checks if given number is prime
    factors = []
    for i in range(1,num+1):
        if num % i == 0:
            factors.append(i)
    return len(factors) == 2

或者为了不浪费内存,使用生成器表达式:

def isprime(num):
    factors = (f for f in range(1, num + 1) if num % f == 0)

    assert next(factors) == 1 # this is always true

    try:
        # this will be true if there are no more factors other than `num` itself
        return next(factors) == num
    except StopIteration:
        # There are no more factors, so `num` must equal 1, which is not prime
        return False