Skip to content

Instantly share code, notes, and snippets.

@genesem
Last active June 21, 2017 15:46
Show Gist options
  • Save genesem/466735c8471f0818de8e598fce98a7b8 to your computer and use it in GitHub Desktop.
Save genesem/466735c8471f0818de8e598fce98a7b8 to your computer and use it in GitHub Desktop.
How to write the Fibonacci Sequence in Python
# a two ways: classic and with recoursive function
def fibonacci():
'''classic implementation'''
a, b = 0, 1
while True:
yield a
a, b = b, a + b
def rfib(n):
'''Recursive function to
print Fibonacci sequence'''
if n <= 1:
return n
else:
return(rfib(n-1) + rfib(n-2))
if __name__ == "__main__":
for i in range(10): # get first 10 of fibonacci sequence
print(rfib(i), end=',')
print()
j=10
for i in fibonacci():
if j==0:
break
print(i, end=',')
j-=1
print()
# result:
# 0,1,1,2,3,5,8,13,21,34,
# 0,1,1,2,3,5,8,13,21,34,
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment