Skip to content

Instantly share code, notes, and snippets.

@pashri
Created May 14, 2024 15:41
Show Gist options
  • Save pashri/d34f72a77ce8bddbaefdf5d944be08ee to your computer and use it in GitHub Desktop.
Save pashri/d34f72a77ce8bddbaefdf5d944be08ee to your computer and use it in GitHub Desktop.
Get the average estimate using the harmonic mean, returning the closest Fibonacci number
from functools import lru_cache
import numpy as np
import scipy as sp
from scipy.stats import hmean as harmonic_mean
@lru_cache
def fibonacci(n):
"""Get the nth Fibonacci number"""
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
def is_fibonacci(n):
"""Determines whether the given number is a Fibonacci number."""
i = 0
while True:
fib = fibonacci(i)
if fib == n:
return True
elif fib > n:
return False
i += 1
def round_to_nearest_fibonacci(n):
"""Rounds the given number to the nearest Fibonacci number."""
# Find the two closest Fibonacci numbers to the given number
fib_prev = 0
fib_curr = 1
while fib_curr < n:
fib_prev, fib_curr = fib_curr, fib_prev + fib_curr
# Round to the nearest Fibonacci number
if abs(fib_prev - n) < abs(fib_curr - n):
return fib_prev
else:
return fib_curr
def get_estimate(numbers: list) -> int:
"""Get the average estimate using the harmonic mean,
returning the closest Fibonacci number"""
arr = np.array(numbers)
hmean = harmonic_mean(arr)
estimate = round_to_nearest_fibonacci(hmean)
return estimate
@pashri
Copy link
Author

pashri commented May 14, 2024

Then you can do:

>>> get_estimate([3, 3, 3, 3, 5, 5, 8])
3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment