繁体   English   中英

为什么即使在较大范围内,此Python代码也不能为我提供解决方案?

[英]Why doesn't this Python code give me a solution even with a large range?

以下是我要解决的问题:

2520是可以除以1到10的每个数字而没有任何余数的最小数字。 能被1到20的所有数均分的最小正数是多少?

这是来自Euler项目( http://projecteuler.net/problem=5 )的第五个问题。 我用Python编写了一个代码来找出数字,但无法获得解决方案。

我的代码是:

def smallestNumber():
 smallest=0 ## Initializing the smallest number
 end=False ## Initializing the break condition for lower level For loop
 found=False ## Initializing the break condition for upper level For loop
 for i in range(21,10000000): ## Upper level for loop
    if i==10000000 and found==False: break ## This will break upper loop when range is satisfied
    for k in range(1,20): ## Lower level for loop
        if end==True: break ## This will break lower loop when range is satisfied
        if i%k==0: ## If condition to check whether current i value is divisible evenly by current k value
            if k==20: ## If k==20, this will make smallest equal to current i value and make both break conditions True
                smallest=i
                end=True
                found=True
            k=k+1
        else: ## if not divisible, this will increment upper level loop
            break
            i=i+1

 if found==False: print 'No value exists in this range'
 else: return smallest

(我是stackoverflow的新手,无法粘贴实际代码而不弄乱格式。因此给您带来的任何不便,我深表歉意)。

无论我将范围扩大多大,我都会不断得到输出“此范围内不存在任何值”。 我猜想虽然我的逻辑还不错,但是由于我是Python初学者,所以我在某些地方弄乱了代码。

如果有人可以帮助我,那就太好了。

谢谢

一些错误的地方:

  1. 答案大于您的上限10000000
  2. 您应该在Python 2中使用xrange ,否则,如果增加上限,将会出现内存错误
  3. 如果要使用从1到20的所有数字,则应使用range(1, 21)
  4. 您不应该手动为您增加循环计数器, rangexrange

首先,您需要的是从1到20的数字的LCM。与在此代码中实现的LCM相比,您可以找到更好的查找LCM的方法。

接下来,这里有一些错误。 我已经编辑了您的代码以进行说明。 请看下面的代码,它显示了我为使代码产生正确的结果而必须进行的更改,以便找到最小的数字,该最小的数字可被1到10的所有数字整除:

def smallestNumber():
smallest=0 
end=False 
found=False
for i in range(21,1000000):
    if found==True: break # This will break upper loop when number is found
    for k in range(1,11): # the range is up to 11 here because we need to check numbers 1-10
        if end==True: break 
        if i%k==0:
            if k==10: ## 
                smallest=i
                end=True
                found=True
            #k=k+1 # not necessary
        else:
            break
            #i=i+1 # not necessary

if found==False: print 'No value exists in this range'
else: return smallest

如您所见,我不得不注释掉i=i+1因为使用for i in range(21,10000000)已经可以解决for i in range(21,10000000) 您还会注意到, if i==10000000 and found==False: breakif found==True: break必须更改if i==10000000 and found==False: break if found==True: breakif found==True: break if i==10000000 and found==False: break if found==True: break因为没有必要检查i = 10000000,并且在找到true时实际上应该停止搜索。 那就是代码中的真正错误。 希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM