"Life is short, Python is a song."--python Functional Programming 03

Source: Internet
Author: User
Tags for in range

Python recursion

If a function calls the function itself internally, the function is a recursive function;

Here's a classic example: using Python recursion to find factorial

def fact (j):    sum=0    if j==0:        sum=1    Else:        sum =j*fact (j-1)    return  sum for in range (5):     Print ('%d!=%d'% (i,fact (i)))

After the CPS transformation eliminates the general recursion,

id=Lambda  x:xdef  Factcps (n):    def  F (n,k):        if n==0:            return K (1)        Else:            return f (n-1,Lambda x:k (nx))    return F (n,id)

Tail recursion Optimization

Tail recursion is based on the tail call of the function, each level calls the return value of the return function to update the call stack, instead of creating a new call stack, similar to the implementation of the iteration, time and space optimization of the general recursion;

def fact (n,sum=0)    if n==0:        return  sum    Else  :        return fact (n-1,sum+n)

"Life is short, Python is a song."--python Functional Programming 03

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.