Dictionary

Peter Otten __peter__ at web.de
Sun Feb 24 14:12:09 EST 2019


Himanshu Yadav wrote:

> fibs={0:0,1:1}
> def rfib(n):
>       global fibs
>        if not fibs.get(n):
>                 fibs[n]=rfib(n-2)+rfib(n-1)
>         return fibs[n]

Please use cut and paste to make sure you are not introducing new errors 
like the inconsistent indentation above.
 
> Why it is gives error??

Do not leave us guessing, always describe the error you encounter as precise 
as you can.

Assuming indentation is not the problem in your actual code, here's one 
hint:

>        if not fibs.get(n):

Will the if suite be executed or skipped for n == 0?

Another hint: Python's dicts support containment tests directly, with the 
'in' and the 'not in' operator. A few examples:

>>> "a" in {"a": 42, "b": 24}
True
>>> "x" in {"a": 42, "b": 24}
False
>>> "a" not in {"a": 42, "b": 24}
False
>>> "x" not in {"a": 42, "b": 24}
True





More information about the Python-list mailing list