How to find the sum of all the multiples of 3 or 5 below 1000 in Python?

后端 未结 18 1163
萌比男神i
萌比男神i 2020-12-29 12:10

Not sure if I should\'ve posted this on math.stackexchange instead, but it includes more programming so I posted it here.

The question seems really simple, but I\'ve

18条回答
  •  盖世英雄少女心
    2020-12-29 12:44

    You can also use functional programming tools (filter):

    def f(x):
        return x % 3 == 0 or x % 5 == 0
        filter(f, range(1,1000)) 
    print(x)
    

    Or use two lists with subtraction of multiples of 15 (which appears in both lists):

    sum1 = []
    for i in range(0,1000,3):
        sum1.append(i)
    sum2 = []
    for n in range(0,1000,5):
        sum2.append(n)
    del sum2[::3] #delete every 3-rd element in list
    print(sum((sum1)+(sum2)))
    

    I like this solution but I guess it needs some improvements...

提交回复
热议问题