Python exercise question 023: 2 years older than the next student, python023

Source: Internet
Author: User

Python exercise question 023: 2 years older than the next student, python023

[Python exercise question 023]Five people sat together and asked how old is the fifth person? He said he is two years older than 4th. Asked about the age of 4th People, he said he was two years older than 3rd people. Ask the third person, and say that the person is two years older than 2nd. Ask 2nd people, saying they are two years older than the first. Finally, I asked the first person that he was 10 years old. How old is the fifth person?

-----------------------------------------------------

This is really ...... Can it be calculated by mental computing? Well, we should train recursive functions again. These questions are not clear about recursive functions recently. However, it seems that I have understood the method of recursive functions. The code for this question is as follows:

Def f (n): if n = 1: return 10 else: return f (n-1) + 2 print (f (5 ))

The output result is as follows:

18

In fact, it is not hard to understand that the first person is 2 years older than the last one. In the function expression, f (n) = f (n-1) + 2. Well, I seem to be able to understand recursion, yeah ~

Follow the rules and write non-recursive code:

A = 10for I in range (4): a + = 2 print ()

Now, it seems familiar with the for loop. The question is indeed effective ~~~

 

++

Source: getting started with programming languages: 100 typical examples [Python]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.