This is my solution for problem 2 of Project Euler using Python:
a, b = 1, 1
total = 0
while a <= 4000000:
if a % 2 == 0:
total += a
a, b = b, a+b # the real formula for Fibonacci sequence
print (total)
I put the codes in the function IsEven:
def IsEven(n):
if n % 2 == 0:
return True
else:
return False
-
2\$\begingroup\$ Did you take a good look at the feedback on your previous question? \$\endgroup\$Mast– Mast ♦2022年05月23日 06:34:51 +00:00Commented May 23, 2022 at 6:34
-
\$\begingroup\$ @Mast - Yes. I took a good look at the feedback on my previous question. Is there a problem I did not fix? \$\endgroup\$Amir Motefaker– Amir Motefaker2022年05月23日 06:42:48 +00:00Commented May 23, 2022 at 6:42
-
2\$\begingroup\$ The question still is not self-contained; please edit to add a short summary of the problem statement. You can keep the link as a reference, but your question does need to be complete even if the linked material isn't accessible. Thanks. \$\endgroup\$Toby Speight– Toby Speight2022年05月23日 12:12:07 +00:00Commented May 23, 2022 at 12:12
-
2\$\begingroup\$ Have you looked at other reviews of code solving this problem? Some of them even appear in the "Related" sidebar, normally on the right. \$\endgroup\$Toby Speight– Toby Speight2022年05月23日 12:16:35 +00:00Commented May 23, 2022 at 12:16
1 Answer 1
Modularity
We have the printing and the constraints (the constant 4000000
) mixed in with the logic of the code. If we create a function, we can unit-test it, and we can time its execution (both of which will be useful to you if you attempt other Project Euler challenges). Perhaps something like
def sum_even_fibonacci(limit)
'''Return the sum of all even Fibonacci numbers
not greater than LIMIT
'''
a, b = 1, 1
total = 0
while a <= limit:
if a % 2 == 0:
total += a
a, b = b, a+b
return total
Simplify
The function that's unused is very long winded. Any time we write if condition: return True; else: return False
, we could simply write return condition
. I.e.
def IsEven(n):
return n % 2 == 0
Algorithm
Instead of generating all the Fibonacci numbers, use your mathematical knowledge to generate just the even ones. Can you work out a formula for their sum?
-
1\$\begingroup\$ I think "not greater than 'limit'" would be more appropriate in the comments "not greater than LIMIT", because name in python are case sensitive \$\endgroup\$miracle173– miracle1732022年05月23日 17:01:56 +00:00Commented May 23, 2022 at 17:01
-
2\$\begingroup\$ I'm not really sure of conventions for Python doc-comments, but upcasing the argument names in Emacs Lisp documentation doesn't seem to cause any confusion there, and I find it does help users to quickly find where each argument is used. \$\endgroup\$Toby Speight– Toby Speight2022年05月24日 06:49:38 +00:00Commented May 24, 2022 at 6:49