Skip to content

Instantly share code, notes, and snippets.

@raeq
Created September 5, 2020 08:19
Show Gist options
  • Save raeq/ecbedd72b0299ff9f5d829635bbd9c55 to your computer and use it in GitHub Desktop.
Save raeq/ecbedd72b0299ff9f5d829635bbd9c55 to your computer and use it in GitHub Desktop.
Iterative solution for calculating a member of the Fibonacci sequence.
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