Latest web development tutorials

Python comprend des exercices 24

Python 100 Li Python 100 Li

Titre: Il y a une séquence de notes: 2 / 1,3 / 2,5 / 3,8 / 5,13 / 8,21 / 13 et l'avant ... calculé le nombre de colonnes 20.

Analyse du programme: Maintenez la variation du numérateur et le dénominateur.

Source Code:

Méthode:

#!/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

Deuxième méthode:

#!/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

Troisième méthode:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

a = 2.0
b = 1.0
l = []
for n in range(1,21):
    b,a = a,a + b
    l.append(a / b)
print reduce(lambda x,y: x + y,l)

L'exemple ci-dessus sortie est:

32.6602607986

Python 100 Li Python 100 Li