Created
May 14, 2024 15:41
-
-
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
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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Then you can do: