Dictionary

Phu Sam psam1304 at gmail.com
Tue Feb 26 23:54:16 EST 2019


The condition  'if not fibs.get(n):'  will not work because
n = 0
      fibs.get(0) is 0 so not 0 is 1

Here is the modified code that works:

fibs={0:0,1:1}
def rfib(n):
      if n == 0 or n == 1:
          return fibs[n]
      else:
        fibs[n]=rfib(n-2)+rfib(n-1)
        return fibs[n]

>>> rfib(8)
21
>>> fibs
{0: 0, 1: 1, 2: 1, 3: 2, 4: 3, 5: 5, 6: 8, 7: 13, 8: 21}


Cheers,

Phu





On Sun, Feb 24, 2019 at 10:56 AM Himanshu Yadav <
himanshuyadav9630994925 at gmail.com> 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]
>
> Why it is gives error??
> --
> https://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list