Recursion of Python

Source: Internet
Author: User

Tag: is the tail recursive efficiency stack Overflow save optimization return problem condition

Recursion is the function that calls this function internally.

Characteristics of recursion:

1. There must be a definite end condition, otherwise it will turn into a dead loop, the final detonation system.

2. Each time you enter a deeper level of recursion, the problem size should be reduced compared to the previous recursion.

3. Recursive execution is inefficient, and too many recursive hierarchies can cause stack overflow.

Example: Recursion

def factorial (n):
If n==1:
Return 1
Return N*factorial (n-1)

Print (factorial (4)) #输出4的阶乘

Tail-Recursive optimization:

def CAL (N):
Print (n)
Return Cal (N+1)
Cal ()

The variables and contents of the functions executed at each recursive time are not saved in the stack, so the recursive stack is not full.

Recursion of 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.