I want a python function that halts, say at the 150th number and then when I need the 400th number, it doesn't recalculates the first 150th fibonacci numbers, it starts from 150th number till the 400th number.
-
1You're probably looking for a generator. See stackoverflow.com/questions/1756096/…Tomerikoo– Tomerikoo2020-08-30 15:36:50 +00:00Commented Aug 30, 2020 at 15:36
-
Use a dynamic programming approach. See stackoverflow.com/a/61896551/6612401Evgeny Mamaev– Evgeny Mamaev2020-08-30 15:54:48 +00:00Commented Aug 30, 2020 at 15:54
3 Answers
You can try with the generator:
def fibo_gen(a=0,b=1):
while True:
#returns a generator object
yield a
a,b = b, a+b
# create generator object
gen_f = fibo_gen()
fibo_list = [next(gen_f) for i in range(150)]
# get the 151 number without recalculating the previous
next(gen_f)
# will return
9969216677189303386214405760200
Or another approach could be with a global dictionary:
#fibonacci dict with cached values
fib_cached = {}
def _fib(n):
# check if fibo number is already cached
if n in fib_cached:
return fib_cached[n]
if n<=2:
value=1
else:
value = _fib(n-1) + _fib(n-2)
# save the fibo number to dict
fib_cached[n]=value
return value
1 Comment
I think you could implement an array that stores all the already calculated numbers, either in a variable, an exported array using numpy or in a database and make it use that last number for example. The function would then have to take startnumber and stopnumber arguments. I don't know if you could just calculate a specific fibonacci number, as it is a recursive function.
1 Comment
You get it done this way:
def Fibonacci(n, pause_val):
a = 0
b = 1
i = 2
print(a)
print(b)
while i<n:
c = b
b = b + a
a = c
print(b)
i += 1
if i == pause_val:
input('Press Enter to continue: ')
continue
Fibonnaci(400, 150)
You'll notice here that i'm using the input function to pause the execution of the Fibonnaci, then continue after the input response is received.