Created
September 5, 2020 08:19
-
-
Save raeq/ecbedd72b0299ff9f5d829635bbd9c55 to your computer and use it in GitHub Desktop.
Iterative solution for calculating a member of the Fibonacci sequence.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def fibonacci_iterative(target: int) -> int: | |
""" | |
This version uses iteration to start at the beginning of the sequence and work up to the target value. | |
It is in this way similar to fibonacci_bottomup | |
Luckily, the iterative version doesn't have the memory space issues, there are no deeply nested call chains here. | |
Unfortunately this method is slow, very slow. | |
>>> fibonacci_iterative(80) | |
23416728348467685 | |
""" | |
penultimate, ultimate = 0, 1 # the values at target -2 and target -1 | |
for i in range(target): | |
penultimate, ultimate = ( | |
ultimate, | |
penultimate + ultimate, | |
) # simple: just calculate the new values | |
return penultimate | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment