22-python Basic 11-recursive function

Source: Internet
Author: User

Recursive

1. Definition: Inside a function, other functions can be called. If a function calls itself internally, the function is a recursive function.

Factorial instances

1 n = Int (input (">>:")) 2 3 4 def f (n): 5     s =     for i in range (2, (n + 1)): 7         s *= i8     return S9 print ( F (n))

Recursive

1 def factorial_new (n): 2  3     if N==1:4         return return     n*factorial_new (n-1) 6  7 print ( Factorial_new (3))

Features of recursive functions:

1 calling its own function

2 There is an obvious end condition, the problem size decreases compared to the last recursion

Advantages: Simple definition, clear logic, all recursive functions can be written in a circular way, but the logic of the loop is not as clear as recursion.

However, the efficiency of recursion is not high, too many recursive levels will lead to stack overflow, about 1000 layers.

2. Fibonacci Sequence
1 def fibnum (n):          #斐波那契数列 2     A, b = 0, 1 3 for     I in range (n): 4         B, a = A+b, b 5     return b 6 n = int (input (">>:")) 7 if n = = 1:8     print (0) 9 elif n = = 2:10     print (1) else:12     print (Fibnum (n-2))

Write with recursion

1 def fibo (n): 2     before = 0 3 after     = 1 4     if n = = 0 or N = = 1:5         return n 6  7     if n <= 3: 8         return 1 9     return Fibo (n-1) +fibo (n-2) print (Fibo (3))

Recursive efficiency is low, when the number is too large, it will be very slow

Limitations of 3.python recursion
Import Sys
Print (Sys.getrecursionlimit ())
#1000
Sys.setrecursionlimit (10000)
Print (Sys.getrecursionlimit ())
#10000

22-python Basic 11-recursive function

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.