【问题标题】:Unexpected output for most numbers given in. (Python)中给出的大多数数字的意外输出。(Python)
【发布时间】:2019-12-19 13:57:22
【问题描述】:

我正在尝试用 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 这样的数字,但对于其他数字会给出奇怪的输出,请帮我找出错误,谢谢!

【问题讨论】:

  • “用其他数字给出奇怪的输出” - 它们有什么奇怪的?
  • factors应该是isprime函数定义中的局部变量

标签: python loops primes


【解决方案1】:

工作示例(问题在于共享的“因素”列表变量)。

# 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

【讨论】:

    【解决方案2】:

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

    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
    

    修改后工作正常

    【讨论】:

      【解决方案3】:

      这个功能坏了:

      ...
      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 一遍又一遍地附加到全局 变量factors,即使它已经包含此数字。因此,factors 的长度将继续增长超过 2。事实上,对于 n == 255factors 将包含 1456 个数字!对于任何大于 2 的数,该函数将返回 False,并且找到的唯一素数将是 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
      

      【讨论】:

        猜你喜欢
        • 2023-01-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多