Recursive functions in Python

Source: Internet
Author: User

A recursive function is a function that calls itself directly or indirectly for looping


def mySum (L): If not L:return 0 else:return l[0]+mysum (l[1:]) print mySum ([1,2,3,4,5])

This function computes the and of all the elements of the list in a recursive way

At each level, the function recursively calls itself to calculate the balance of the remaining values of the list.


There is also a recursive method for calculating the factorial:


def factorial (n): If n==0 or N==1:return 1 else:return factorial (n-1) * Nprint (factorial (5)) 120



Recursive functions can also be used to calculate Fibonacci series

def Recur_fibo (n): "" "recursive function output Fibonacci sequence" "If n <= 1:return n Else:return (Recur_fibo (n-1) + recur_ Fibo (n-2))


There's a problem with the Fibonacci sequence, just the initial two-digit case is different.

If a staircase has an N-step stair, the person can cross a maximum of 2 steps at a time, and the total number of stair-climbing schemes is implemented as follows:

def DP (n): if n <= 2:return n else:return dp (n-1) + DP (n-2) print DP (5)


The recursion is introduced here.


Recursive functions in 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.