1

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.

Ali Hassan
  • 291
  • 1
  • 4
  • 13
  • 1
    You're probably looking for a [generator](https://wiki.python.org/moin/Generators). See https://stackoverflow.com/questions/1756096/understanding-generators-in-python – Tomerikoo Aug 30 '20 at 15:36
  • Use a dynamic programming approach. See https://stackoverflow.com/a/61896551/6612401 – Evgeny Mamaev Aug 30 '20 at 15:54

3 Answers3

2

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
dejanualex
  • 3,872
  • 6
  • 22
  • 37
0

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.

oberhuber
  • 11
  • 3
  • That could work but it'll take a toll on memory usage. I'm looking for pre defined function that takes care of this. – Ali Hassan Aug 30 '20 at 16:10
0

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.

Seyi Daniel
  • 2,259
  • 2
  • 8
  • 18