Python Practice Example 28

Python 100例Python 100 Examples

Question:Five people are sitting together. Ask the fifth person how old they are. They say they are 2 years older than the fourth person. Ask the fourth person their age, they say they are 2 years older than the third person. Ask the third person, they say they are 2 years older than the second person. Ask the second person, they say they are 2 years older than the first person. Finally, ask the first person, they say they are 10 years old. How old is the fifth person?

Program analysis:Use the recursion method. Recursion is divided into two stages: backtracking and forward recursion. To know the fifth person's age, you need to know the fourth person's age, and so on, deducing back to the first person (10 years old), then deducing forward again.

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 result of the above example is:

18

Python 100例Python 100 Examples

Other extensions