Your method isn't bad though it could be cleaned up and I have a faster and more straight forward suggestion, say using a simple class.
- Karl Knechtel's method appears to create a near infinite loop.
- Madison May's recursion method reaches a "RuntimeError: maximum recursion depth exceeded" beyond an input of 40. But the 3rd solution they suggest appears to execute without error but the output appears inaccurate... I believe you are only getting the largest number, idk. Mine is similar.
I think this is your best, most accurate, and simplest (also fastest given a correct solution):
def fib(n): # return Fibonacci series up to n
result, a, b = list(), 0, 1 # set variables
result.append(0) # Initial Fibonacci Zero
while b < n:
if b % 2 == 0:
result.append(b)
a, b = b, a+b
return result
def fibSum(n):
return sum(map(int, fib(n)))
print(fibSum(4000000))
Hope this helps. Good luck!
P.S. Also, I would recommend using '\n' for new line when printing for code cleanness, there's no need for several print statements but we all start somewhere and I've only been programming Python for about a year myself but I also have other languages in my background and I read a lot. A few key notes: map allows you to easily sum up a list of ints/truple and you can use sum instead of incrementing through a list and adding it up, it should be faster in 'almost' all cases (strings are a different story). Again, good luck!
P.P.S. I kept your mod 2, modulus is your friend. Modifying built in perimeters is not your friend, if you have to do that, odds are you're doing something wrong. Just food for thought.
Benchmarks:
Your Code:
Output: 4613732
Total Run Time: 0.000175 seconds in Pypy
Total Run Time: 0.000069 seconds in Python
My Suggestion:
Output: 4613732
Total Run Time: 0.000131 seconds in Pypy
Total Run Time: 0.000053 seconds in Python