Project Euler - #1 Python wrong solution

前端 未结 2 1533
南方客
南方客 2021-01-26 08:15

I am relatively new to coding in general and started Project Euler to bring my coding a bit further. Spent some time thinking of how to work the first question on my own and tri

相关标签:
2条回答
  • 2021-01-26 08:49

    I'd strongly advise against recursion, since it might work for small number but not for bigger ones, and even if the solution might work, it would teach you a wrong approach.

    def euler_1(sum, range_beg, range_end):
        for number in range( range_beg, range_end):
            if (( number % 3 ) == 0) or ((number % 5) == 0):
                sum += number
            else:
                pass
    
         return sum
    
    
    print(euler_1( 0, 0, 1000))
    

    This is more pythonic, reusable, faster and simpler to read and correct.

    0 讨论(0)
  • 2021-01-26 08:59

    Your mistake is that you are including numbers divisible by 15 twice: Once as a multiple of 3, and once as a multiple of 5.

    For what it's worth, here's a concise way of computing this sum:

    sum(i for i in range(1000) if not (i % 3 and i % 5))
    
    0 讨论(0)
提交回复
热议问题