Home > Back-end >  What is actually happening on line 4 when returning the dictionary value
What is actually happening on line 4 when returning the dictionary value

Time:10-15

I am trying to understand this code, but I am confused on what's going on with the memoization part of my code. Line 3 has return fibstorage[x], but what does this actually do? I know that above it's checking if x is inside the dictionary, but afterward what is this really returning? And why is x in brackets after fibstorage is called?

fibstorage = {}
def fib(x):
    if x in fibstorage:
        return fibstorage[x]
    elif x == 1:
        value = 1
    elif x == 2:
        value = 1
    elif x > 2:
        value = fib(x - 1)   fib(x - 2)
    fibstorage[x] = value
    return value
whatever = 100
for i in range(1, whatever   1):
    print("fib({})".format(i), fib(i))

CodePudding user response:

fibstorage is a dictionary. You can imagine them to be a little like a list you reference with a value rather than a position. Such as

x = {'Hello': 'world',
     'foo': 'bar'
     8: 'eight'}
print(x['Hello']) #would print world
print(x['foo']) #would print bar
print(x[8]) #would print eight

It appears to be a caching method so if x has already been computed it doesn't have to be computed again.

If you have further questions feel free to ask

  • Related