我写了一个程序来确定数字是否为质数。该程序可以正常工作,只是它两次将最终语句打印出,这是我不希望的。我对Python还是很陌生,因此请提供任何有关提高我的代码效率的建议。
def user(text = "Give me a number.\n"):
return int(input(text))
number = user()
list = range(1, number + 1)
divisor = []
for element in list:
divide = number % element
if divide == 0:
divisor.append(element)
for element in divisor:
if len(divisor) > 2:
print ("This isn't a prime.")
user("Give me another number.\n")
else:
print ("This is a prime.")
答案 0 :(得分:3)
我强烈建议您学习基本的调试技术。请参阅这个可爱的debug博客以获取帮助。
如果没有其他问题,请除去开销代码并插入几个策略性print
语句以跟踪控制和数据流。例如:
number = 7 # For debugging, pick a single problem number.
divisor = []
for element in range(1, number + 1):
divide = number % element
if divide == 0:
divisor.append(element)
print(number, "has divisors", divisor)
for element in divisor:
if len(divisor) > 2:
print ("This isn't a prime.")
# user("Give me another number.\n")
else:
print ("This is a prime.", element)
输出:
7 has divisors [1, 7]
This is a prime. 1
This is a prime. 7
您现在可以看到问题:
例如,给定number = 12
,代码将产生
12 has divisors [1, 2, 3, 4, 6, 12]
This isn't a prime.
This isn't a prime.
This isn't a prime.
This isn't a prime.
This isn't a prime.
This isn't a prime.
解决方案
在点blue_note
和Martijn
之后,简化下面的代码:删除for
以避免出现多个输出,并删除不使用的多余调用。如果要重复此过程,则需要将整个程序包装成一个循环,而不仅仅是获取更多输入。
if len(divisor) > 2:
print ("This isn't a prime.")
else:
print ("This is a prime.")
答案 1 :(得分:0)
您需要删除for element in divisor
。现在,如果数字有n
个除数,则您将消息打印n
次。
此外,更有意义的是使范围range(2, n)
并在您第一次发现零模时中断循环。像
def is_prime(n):
for i in range(2, n):
if n % i == 0:
return False
return True
旁注:您不需要检查最多n-1
,仅检查不超过n**2
的数字就足够了