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

Python Exercise Example 24

Python Exercise Example 24

Python 100 Examples Python 100 Examples

**Problem:** There is a fraction sequence: 2/1, 3/2, 5/3, 8/5, 13/8, 21/13... Find the sum of the first 20 terms of this sequence.

**Analysis:** Pay attention to the pattern of change in the numerators and denominators.

Program source code:

Method 1:

Example

#!/usr/bin/python

-- coding: UTF-8 --

a

=

2.0

b

=

1.0

s

=

0

for

n

in

range

(

1

,

21

)

:

s

+=

a

/

b

t

=

a

a

=

a

b

b

=

t

print

(

s

)

Method 2:

Example

#!/usr/bin/python

-- coding: UTF-8 --

a

=

2.0

b

=

1.0

s

=

0.0

for

n

in

range

(

1

,

21

)

:

s

+=

a

/

b

b

,

a

=

a

,

a

b

print

(

s

)

s

=

0.0

for

n

in

range

(

1

,

21

)

:

s

+=

a

/

b

b

,

a

=

a

,

a

b

print

(

s

)

Method 3:

Example (Python 2.x)

#!/usr/bin/python

-- coding: UTF-8 --

a

=

2.0

b

=

1.0

l

=

[

]

l

.

append

(

a

/

b

)

for

n

in

range

(

1

,

20

)

:

b

,

a

=

a

,

a

b

l

.

append

(

a

/

b

)

print

reduce

(

lambda

x

,

y

:

x

y

,

l

)

Example (Python 3.x)

#!/usr/bin/python

from

functools

import

reduce

a

=

2.0

b

=

1.0

l

=

[

]

l

.

append

(

a

/

b

)

for

n

in

range

(

1

,

20

)

:

b

,

a

=

a

,

a

b

l

.

append

(

a

/

b

)

print

(

reduce

(

lambda

x

,

y

:

x

y

,

l

)

)

The output of the above example is:


32.6602607986

Python 100 Examples Python 100 Examples