Python 我必须在我的程序中更改什么才能从这个恼人的错误代码中修复它?

Python 我必须在我的程序中更改什么才能从这个恼人的错误代码中修复它?,python,Python,我一直在尝试编写一个程序来解决以下问题: 如果我们列出10以下的所有自然数,它们是3或5的倍数,我们得到3、5、6和9。这些倍数之和是23 求1000以下所有3或5的倍数之和 为了解决这个问题,我想我可以编写一个函数,列出所有3的倍数。我想让它把我的列表叫做三,然后把最后一个数字乘以3。然后把这个数字加回到列表中。然后它会重复,直到达到1000。或者在这种情况下,999 当我尝试运行它时,错误消息使我困惑。这个程序有什么问题 three = [3, ] def multiples_of_thr

我一直在尝试编写一个程序来解决以下问题:

如果我们列出10以下的所有自然数,它们是3或5的倍数,我们得到3、5、6和9。这些倍数之和是23

求1000以下所有3或5的倍数之和

为了解决这个问题,我想我可以编写一个函数,列出所有3的倍数。我想让它把我的列表叫做三,然后把最后一个数字乘以3。然后把这个数字加回到列表中。然后它会重复,直到达到1000。或者在这种情况下,999

当我尝试运行它时,错误消息使我困惑。这个程序有什么问题

three = [3, ]

def multiples_of_three():
    while (three != 999):
        high = (max(three))
        multiplied_three = (int(high *3))
        next_number_three = (multiplied_three, )
        three.append("next_number_three")

multiples_of_three()
print (three)
以下是错误消息:

File "C:/Users/admin/PycharmProjects/World/My projects/Euler #1.py", line 
15, in <module>
    multiples_of_three()
  File "C:/Users/admin/PycharmProjects/World/My projects/Euler #1.py", line 
10, in multiples_of_three
    high = (max(three))
TypeError: '>' not supported between instances of 'str' and 'int'

删除下一个第三个左右的引号。

这里有一种替代方法,我认为更具可读性:

def multiples_of_three():
    return [i for i in range(3, 1000, 3)] # a list of multiples of 3 from 1-1000

threes = multiples_of_three()
print (threes)
此外,我们可以使该函数更通用,并使用它来解决您的示例,下面是它的外观:

def get_multiples(multiple, maximum):
    return [i for i in range(multiple, maximum, multiple)] # return all multiples in a list

def get_sum_of_multiples(multiples, maximums):
    all_multiples = set() # empty set
    for multiple, maximum in zip(multiples, maximums): # Iterate through the multiples and maximums
        current_multiples = get_multiples(multiple, maximum) 
        for num in current_multiples:
            all_multiples.add(num) # We add the multiples to a set because it will remove duplicates for us
    return sum(all_multiples) # return the sum of them all


multiples = [3, 5]
maximums = [1000, 1000]
print(get_sum_of_multiples(multiples, maximums))

请注意,我知道您可能需要使用特定的技术将此作为家庭作业来编写,但这里有一种更为通俗的方式:

multiples_of_three_or_five = [i for i in range(1,1000) if i % 3 == 0 or i % 5 == 0]
print sum(multiples_of_three_or_five)
或者你可以是超级花哨的,只是纸笔数学

编辑:花式数学:

从1到N的整数求和得到N*N+1/2

因此,将1000以下的3的倍数相加得到3*332*333/2

1000以下5的倍数之和为5*199*200/2

现在,仅仅把这两个数字相加就给出了错误的答案,因为你会重复计算那些3和5的倍数。但是这些正好是15的倍数,所以我们减去它们。我们检查1000/15=66,所以66*15仍然低于1000,所以我们减去

15*66*67/2


最后的答案是232169

3。请注意,3永远不等于999。三个只会是这么大的列表你没有测试过吗?我刚测试过,我得到了:文件C:/Users/admin/PycharmProjects/World/My projects/Euler 1.py,第14行,三个文件的倍数C:/Users/admin/PycharmProjects/World/My projects/Euler 1.py,第9行,在“tuple”和“int”@CJPeine的实例之间不支持“>”,这是我的观点,其他解决方案修复了更多错误,甚至不需要列表理解,范围仅为3,1000,3@CJPeine列出理解或我的全部答案?它起作用了,谢谢!第一个答案@CJPeine我添加了更多内容,以向您展示如何更普遍地使用它解决您的问题。此外,如果这对您有效,请将其标记为已接受的答案。我是否通过单击灰色复选标记来执行此操作?如果是的话,我检查了一下。