Python learning Function (iv)--recursion

Source: Internet
Author: User

1. What is recursion: recursion is higher than iteration;

Calling yourself in a recursive function, such as Next, will fall into a dead loop:

def recursion ():
return recursion ()
Tip: Python3 The recursive layer depth is 100 layers, you can change the recursive layer depth
Import Sys
Sys.setrecursionlimit (10000)

To implement factorial in a non-recursive way:

def factorail (n):
result = N
Range (1,n):
Result *= I
return result
Print (Factorail (5))

Results: 120

To implement factorial in a recursive way:

 #用递归求阶乘
def factorail1 (n):
if n== 0:
Return 0
if n==1:
  Return 1
Else:
  return n * FACTORAIL1 (n1)
Print (Factorail1 (6))

Results: 720

Implementation of the 2.fibonacci recursive sequence:

  #用递归方法实现 
if n = 1:
return 1
if n = = 2:
return 1
else:
return Fibonacci (N-1) + Fibonacci (N-2)
print (Fibonacci (20)

Results: 6765

#---------------------

#用非递归方法实现
def fibonacci1 (n):
s1=1
S2=1
S3=1
if N < 1:
print (" wrong input! ")
return-1
else:
while (N-2) > 0:
S3 = s1+s2
S1 = s2
S2 = s3
N -=1
Return S3
print (fibonacci1 (12)

3. Hanoi



Python learning Function (iv)--recursion

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.