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.

2

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

1 Comment

The generator approach was the one I was looking for!
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.

1 Comment

That could work but it'll take a toll on memory usage. I'm looking for pre defined function that takes care of this.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.