Skip to content

Instantly share code, notes, and snippets.

@tcely
Last active May 24, 2025 16:57
Show Gist options
  • Save tcely/92164ad9d84b922017d31c1db848d7b2 to your computer and use it in GitHub Desktop.
Save tcely/92164ad9d84b922017d31c1db848d7b2 to your computer and use it in GitHub Desktop.
Fibonacci functions
#!/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()
#!/usr/bin/env python3
def fib_r(n):
if n < 2:
return n
return fib_r(n-2) + fib_r(n-1)
#!/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