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

Python Exercise Example 28

Python Exercise Example 28

Python 100 Examples Python 100 Examples

**Problem:** Five people sit together. How old is the fifth person? He says he is 2 years older than the fourth. The fourth says he is 2 years older than the third. The third says he is 2 years older than the second. The second says he is 2 years older than the first. Finally, the first says he is 10 years old. How old is the fifth person?

**Program analysis:** Use recursion. Recursion has two stages: backward deduction and forward deduction. To know the age of the fifth person, you need to know the age of the fourth person, and so on, until you reach the first person (10 years old), then deduce back.

Program source code:

Example

#!/usr/bin/python

-- coding: UTF-8 --

def

age

(

n

)

:

if

n

==

1

:

c

=

10

else

:

c

=

age

(

n

1

)

2

return

c

print

(

age

(

5

)

)

The output of the above example is:


18

Python 100 Examples Python 100 Examples