there is a problem, holp someone could help me,thanks

nathan huang nathan.huang.python at gmail.com
Wed Aug 24 13:50:46 EDT 2011


hi John
it's simple,
let's make a little modification for the scipt:
def fib(x):
    if x==0 or x==1: return 1
    else: return fib(x-1) + fib(x-2)

for i in range(10):
    print 'fib(%s): ' % i, fib(i)

result:
fib(0):  1
fib(1):  1
fib(2):  2
fib(3):  3
fib(4):  5
fib(5):  8
fib(6):  13
fib(7):  21
fib(8):  34
fib(9):  55

you see, when we put 0 or 1 into fib, we definitely get 1 individually,  if
we put 2 into fib(), inside script we get two fib() result plus 1 + 1.  If
we put 9 into fib(), we get plus of two results of fib(7) and fib(8), that
is 21 + 34, so we get 55.
hope it can give you a little help.

On Thu, Aug 25, 2011 at 12:46 AM, John Gordon <gordon at panix.com> wrote:

> In <f99a156b-56b4-41f4-9599-0dcc31a47b0f at v9g2000pri.googlegroups.com>
> kangshufan at hotmail.com writes:
>
> > Hi everyone
>
> > I just study python for a few time.
> > Now I have a problem and I holp someone can help me.
> > There is a piece of code:
>
> > def fib(x):
> >     if x==0 or x==1: return 1
> >     else: return fib(x-1) + fib(x-2)
>
> > Could you explain how it works?
> > Thanks for you help.
>
> > Vince
>
> When a function calls itself, as fib() does, it's called recursion.
>
>  http://en.wikipedia.org/wiki/Recursion_(computer_science)
>
> Basically the fib() method keeps calling itself with smaller and smaller
> arguments until it gets 1 or 0.
>
> --
> John Gordon                   A is for Amy, who fell down the stairs
> gordon at panix.com              B is for Basil, assaulted by bears
>                                -- Edward Gorey, "The Gashlycrumb Tinies"
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20110825/c3322fe0/attachment.html>


More information about the Python-list mailing list