Created
May 4, 2020 22:34
-
-
Save AndrewOwenMartin/fed9788e99a428872be6caedc6026c67 to your computer and use it in GitHub Desktop.
Four ways of generating the Fibonacci sequence in Python
This file contains 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
# Tail recursive fibonacci | |
def get_fib(final, num=1, current=1, prev=0): | |
if final == 0: | |
return 0 | |
if num < final: | |
prev, current = current, prev + current | |
return get_fib(final, num + 1, current, prev) | |
else: | |
return current | |
# Head recursive fibonacci | |
def head_fib(num): | |
if num < 2: | |
return num | |
return head_fib(num - 1) + head_fib(num - 2) | |
# Generator fibonacci | |
def fibonacci(): | |
a, b = 0, 1 | |
while True: | |
yield a | |
a, b = b, a + b | |
# Primes generator | |
def primes(): | |
num = 2 | |
while True: | |
for divisor in range(2, num): | |
if num % divisor == 0: | |
num += 1 | |
break | |
else: | |
yield num | |
num += 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment