Put all of your code in functions. Including the code to represent
Euler problem 1, along with the code to exercise that function.
Implement automated tests for those functions. While implementing
such code, express your expections for correctness in the form
of automated tests. Ultimately, you'll want to learn how to use
one of Python's testing frameworks, such as
pytest. In the meantime, or
in small-scale or informal situations, you can roll your own testing
code, as illustrated below.
Functions based on a simple boolean test can return directly. You
can drop the if-else clauses from multiple_3_or_5()
and just return
the boolean result.
The built-in sum function takes an iterable. Just add up the values of i
for which multiple_3_or_5(i)
returns true.
Don't obsess over performance until you know you have a problem.
This program is uninteresting from a performance perspective. Drop
the extraneous timing code. And even if you disagree with my
perspective, at least focus your measurements on the relevant
code -- just the call of euler_1()
function, rather than the execution of the entire program.
def main():
TESTS = (
(10, 23),
(1000, 233168),
)
for limit, expected in TESTS:
got = euler_1(limit)
if got == expected:
print('ok')
else:
print(limit, got, expected)
def euler_1(limit = 1000):
return sum(i for i in range (1, limit) if multiple_3_or_5(i))
def multiple_3_or_5(n):
return n % 3 == 0 or n % 5 == 0
if __name__ == '__main__':
main()