[Life Bitter short PYTHON song] -- PYTHON functional programming 03, python03

Source: Internet
Author: User

[Life Bitter short PYTHON song] -- PYTHON functional programming 03, python03

Python Recursion

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

The following is 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 sumfor i in range(5):    print('%d!=%d'%(i,fact(i)))

Remove general recursion after CPS transformation,

id=lambda x:xdef factCPS(n):    def f(n,k):        if n==0:            return k(1)        else:            return f(n-1,lambda x:k(n*x))    return f(n,id)

Tail recursion Optimization

Tail recursion is based on the function's End call. Each level of call directly returns the function's return value to update the call stack, instead of creating a new call stack, similar to iterative implementation, optimized General recursion in time and space;

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

 

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.