Created
October 11, 2012 17:09
-
-
Save NordomWhistleklik/3873990 to your computer and use it in GitHub Desktop.
[Python] Function for finding the nth number in a 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 get_fib(n, start): | |
| '''(int, int) -> int | |
| Returns the nth Fibonacci number where start defines whether the squence | |
| starts at 0 or 1 and n is a whole number greater than or equal to 1 | |
| >>>get_fib(1,0) | |
| 0 | |
| >>>get_fib(1,1) | |
| 1 | |
| >>>get_fib(5,1) | |
| 5 | |
| ''' | |
| # define first two numbers as 0,1 or 1,1 | |
| oldest = start | |
| older = 1 | |
| # begin iterating through sequence | |
| for i in range(n): | |
| # first number as defined | |
| if i == 0: | |
| current = oldest | |
| # second number as defined | |
| elif i == 1: | |
| current = older | |
| # all other numbers are the sum of the previous two numbers | |
| else: | |
| current = older + oldest | |
| # re-label oldest and older for next step only if we are outside | |
| # of the first pre-defined two | |
| oldest = older | |
| older = current | |
| # return last number in sequence | |
| return current |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment