Python exercise question 021: Recursive Method for factorial, python021

Source: Internet
Author: User

Python exercise question 021: Recursive Method for factorial, python021

[Python exercise question 021]Use the recursive method to calculate 5 !.

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

First, you have to figure it out: 5! It refers to the "5 factorial", that is, 5! = 1*2*3*4*5.

Then, it is said that "recursion" is a function called for itself. It's strange to hear that the Code is as follows:

Def f (x): if x = 0: return 0 elif x = 1: return 1 else: return (x * f (x-1) print (f (5 ))

It indicates that if x = 5, the value of 5 * f (4) is returned. To know the value, you must first calculate the value of f (4. F (x), f (4) = 4 * f (3), so f (5) = 5*4 * f (3 ). Push to f (5) = 5*4*3*2 * f (1 ). The f (x) function says that when x = 1, the return value is 1. Therefore, f (5) = 5*4*3*2*1 = 120. Therefore, the output result is as follows:

120

It sounds very troublesome and hard to understand. What if recursive functions are not required? The most basic code can be written as follows:

F = 1for I in range (1, 6): f = f * iprint (f)

The same result is 120.

The Code of recursive functions is concise and the logic is clear. For this question ...... Yes?

 

++

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.