对于我的学校作业,我需要编写一个程序,查找具有四个唯一素因子的数字,并且是连续的。到目前为止,我得到了这段代码,但结果却产生了错误的值。我做错了什么?
# number to start with
n = 2
#function
def factor(x):
factors = []
i = 2
while x > 1:
if x % i == 0:
x = x / i
factors.append(i)
else:
i += 1
factors = sorted(set(factors))
return factors
#loop
while len(factor(n)) !=4 and len(factor(n+1)) !=4 and len(factor(n+2)) !=4 and len(factor(n+3)) !=4:
n+=1
print "The first number is {}, the second number is {}, the third number is {}".format(n-3,n-2, n-1)
print "And the fourth number is {}".format(n)
答案 0 :(得分:2)
虽然range(204, 208)
中的数字不是四个因素,但你是对的:
>>> for x in range(204, 208):
print x, factor(x)
204 [2, 3, 17]
205 [5, 41]
206 [2, 103]
207 [3, 23]
你被你的代码误导了;您检查n, n+1, n+2, n+3
但是显示n-3, n-2, n-1, n
。您的代码在n == 207
处停止,如果我们添加三个代码:
>>> factor(210)
[2, 3, 5, 7]
因此,当代码找到第一个号码len(factor(x)) == 4
时,代码就会停止。你的逻辑是倒退的;使用while
这样的循环,您需要的东西只有在您找到答案时才会评估False
。评估你的四个谓词:
>>> True and True and True and False
False
与结合or
的相同谓词进行比较,而不是:
>>> True or True or True or False
True
现在所有四个数字都有四个因素:
>>> False or False or False or False
False
我认为你最终得到了and
,因为它更贴近你的头脑中的逻辑("我希望第一个是4,和第二个是四个,和 ..." )。在此基础上,您的代码可能更清晰:
while True:
if len(factor(n)) == 4 and len(factor(n+1)) == 4 and len(factor(n+2)) == 4 and len(factor(n+3)) == 4:
break
n += 1
或者,更整洁(并遵守风格指南的行长限制!):
while True:
if all(len(factor(x)) == 4 for x in range(n, n+4)):
break
n += 1