Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ssl/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python I';我不明白为什么下面的代码没有给我答案?_Python - Fatal编程技术网

Python I';我不明白为什么下面的代码没有给我答案?

Python I';我不明白为什么下面的代码没有给我答案?,python,Python,运行最小除数的代码: def smallesteuler(): t=0 result=[] for no in range(11,10000): for i in range(1,11): if (no%i==0): t=t+1 if(t==20): return result.append(no) t=0 print (smal

运行最小除数的代码:

def smallesteuler():
    t=0
    result=[]
    for no in range(11,10000):
        for i in range(1,11):
            if (no%i==0):
                t=t+1
            if(t==20):
                return result.append(no)
        t=0
print (smallesteuler())

看起来您正在尝试收集满足
no%i==0
的前20个数字。您必须将这些数字附加到
结果
,然后
返回结果

def smallesteuler():
    t=0
    result=[]
    for no in range(11,10000):
        for i in range(1,11):
            if (no%i==0):
                result.append(no)
                t=t+1
            if(t==20):
                return result

print (smallesteuler())

这看起来像欧拉问题5——找到1..20的最小公倍数

您的代码可以重写为

def euler5(upto=20):
    """
    Find the least common multiple of 1..upto
    """
    num = upto
    while True:
        if all(num % factor == 0 for factor in range(2, upto+1)):
            return num
        else:
            num += 1
然而,一个更有效的解决方案是

from fractions import gcd
from functools import reduce

def lcm(a, b):
    return a * b // gcd(a, b)

def euler5(upto=20):
    return reduce(lcm, range(1, upto+1))

第一个解决方案是O(n!),第二个是O(n**2)。

list.append()。