Re[2]: [Tutor] fibonacci

antonmuhin at rambler.ru antonmuhin at rambler.ru" <antonmuhin@rambler.ru
Wed Feb 12 02:50:03 2003


Hello Ike,

Wednesday, February 12, 2003, 9:30:26 AM, you wrote:

IH> writing a program to do this would be simple as well...

IH> def fib(index):
IH>     first=1
IH>     second=1
IH>     for i in range(index):
IH>         new=first+second
IH>         first=second
IH>         second=new
IH>     return new

IH> then this function would give the nth number in a fibonacci sequence

There might be a small bug: fib(1) calculates to 2 that is not 1st fib
(of course, it depends on how you count it :).

Here I'd like suggest slightly modified variant:

def fib(n, first = 1, second = 1):
    if n == 1:
        return first
    elif n == 2:
        return second
    else:
        for i in range(n - 2):
            first, second = second, first + second
        return second

-- 
Best regards,
 anton                            mailto:antonmuhin@rambler.ru