Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Exercise Example 6

Python Exercise Example 6

Python 100 Examples Python 100 Examples

**Problem:** The Fibonacci sequence.

**Program Analysis:** The Fibonacci sequence, also known as the golden ratio sequence, refers to a sequence like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

In mathematics, the Fibonacci sequence is defined recursively as follows:


F0 = 0     (n=0)
F1 = 1    (n=1)
Fn = F[n-1]+ F[n-2](n=>2)

Program source code:

Method 1

#!/usr/bin/python

-- coding: UTF-8 --

def

fib

(

n

)

:

a

,

b

=

1

,

1

for

i

in

range

(

n

1

)

:

a

,

b

=

b

,

a

b

return

a

Output the 10th Fibonacci number

print

(

fib

(

10

)

)

Method 2

#!/usr/bin/python

-- coding: UTF-8 --

Using recursion

def

fib

(

n

)

:

if

n

==

1

or

n

==

2

:

return

1

return

fib

(

n

1

)

fib

(

n

2

)

Output the 10th Fibonacci number

print

(

fib

(

10

)

)

The above example outputs the 10th Fibonacci number; the result is:


55

Method 3

If you need to output a specified number of Fibonacci numbers, you can use the following code:

#!/usr/bin/python

-- coding: UTF-8 --

def

fib

(

n

)

:

if

n

==

1

:

return

[

1

]

if

n

==

2

:

return

[

1

,

1

]

fibs

=

[

1

,

1

]

for

i

in

range

(

2

,

n

)

:

fibs

.

append

(

fibs

[

1

]

fibs

[

2

]

)

return

fibs

Output the first 10 Fibonacci numbers

print

(

fib

(

10

)

)

The output of the above program is:


[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

Python 100 Examples Python 100 Examples