Skip to content

Instantly share code, notes, and snippets.

@NordomWhistleklik
Created October 11, 2012 17:09
Show Gist options
  • Select an option

  • Save NordomWhistleklik/3873990 to your computer and use it in GitHub Desktop.

Select an option

Save NordomWhistleklik/3873990 to your computer and use it in GitHub Desktop.
[Python] Function for finding the nth number in a Fibonacci sequence
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