Last active
May 24, 2025 16:57
-
-
Save tcely/92164ad9d84b922017d31c1db848d7b2 to your computer and use it in GitHub Desktop.
Fibonacci functions
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
#!/usr/bin/env python3 | |
from collections import deque as queue | |
def fib_q(n): | |
if n < 2: | |
return n | |
memo = queue((0, 1,), maxlen=2) | |
for i in range(1, n): | |
im2 = memo.popleft() | |
im1 = memo[0] | |
memo.append(im2 + im1) | |
return memo.pop() | |
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
#!/usr/bin/env python3 | |
def fib_r(n): | |
if n < 2: | |
return n | |
return fib_r(n-2) + fib_r(n-1) |
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
#!/usr/bin/env python3 | |
from functools import lru_cache | |
@lru_cache(maxsize=10_000) | |
def fib_r(n): | |
if n < 2: | |
return n | |
# do not exceed the recursion limit | |
for i in range(512, n, 512): | |
fib_r(i-1) | |
fib_r(i) | |
return fib_r(n-2) + fib_r(n-1) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment