[BangPypers] Python Gotcha Fibonacci
shankha
shankhabanerjee at gmail.com
Sat Oct 4 13:35:36 CEST 2014
Try using pdb. Check the values of next and prev when it is called for
the second time. Similarly check the values of next and prev in
another execution.
You will enjoy it :-).
Try going through this answer:
http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument.
Thanks
Shankha Banerjee
On Sat, Oct 4, 2014 at 4:57 PM, Rajiv Subramanian M
<rajiv.m1991 at gmail.com> wrote:
> Hi Group,
>
> I just went through this article
> http://docs.python-guide.org/en/latest/writing/gotchas/
>
> written a Fibonacci program like this
>
> def fibonacci(next=[1], prev=[0]):
> data = prev.pop()
> prev.append(next.pop())
> next.append(prev[0] + data)
> return data
>
> for i in range(10):
> print fibonacci()
>
> It actually works, it prints first 10 fibonacci numbers
>
> My question is the following code doesn't work the same way as i expected
> it to work.
>
> def fibonacci(next=1, prev=0):
> data = prev
> prev = next
> next = data + next
> return data
>
> for i in range(10):
> print fibonacci()
>
> Instead of printing Fibonacci, it just prints 10 zeros
>
> means.. does python only remembers the list in default argument?
>
> --
>
> [image: --]
> Rajiv Subramanian M
> [image: http://]about.me/rajiv.m1991
> <http://about.me/rajiv.m1991?promo=email_sig>
> _______________________________________________
> BangPypers mailing list
> BangPypers at python.org
> https://mail.python.org/mailman/listinfo/bangpypers
More information about the BangPypers
mailing list