程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[original launch] learn Python recursive algorithm from Xiao Hui

編輯:Python

This article has participated in 「 New people's creation ceremony 」 Activities , Start the road of nuggets creation together .

 Statement : The copyright belongs to me , Offenders will investigate .
Please quote source for reprint https://juejin.cn/post/7111942157082034212

1.1.  recursive algorithm

1.1.1.  Algorithm definition

Recursive algorithm is a simple algorithm , That is, through known conditions , Draw an intermediate inference from a particular relation , Until the result of the algorithm .

1.1.2.  The basic idea

Recursive algorithms are divided into forward and backward , The forward method is based on the known conditions , Work out the problem to be solved step by step ; The inverse method starts from the results of known problems , The conditions for the beginning of the problem can be worked out step by step with the expression of iterated representation , That is, the inverse process of the forward method .

1.1.3.  Code implementation - Rabbits breed

Problem description :

The rabbit has given birth to a little rabbit every month since three months , The little rabbit grows up to three months later and has been born every month , If the rabbits don't die , So the first month from a little rabbit to N After a month , What is the total number of rabbits ?

Algorithm analysis :

Get the number of rabbits per month :

1 (1)=1
1 (2)=1
1 1 (3)=2
1 1 1 (4)=3
1 1 1 1 1 (5)=5
1 1 1 1 1 1 1 1 1 (6)=8
………… (N)=?
As we can see above , For the typical Fibonacci sequence , namely
f(n)=f(n-1)+f(n-2) n>2
f(n)=1 n<=2

Code implementation :

【 example 1-1】  Rabbits breed :

def fib(n):
    if n<=2:
        return 1
    else:
        return fib(n-1)+fib(n-2)
if __name__ == '__main__':
n = 30
    print("%d The number of rabbits after months is :%d"%(n, fib(n)))

Execution results :

30 The number of rabbits after months is :832040


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved