递归

用for循环实现阶乘:

1 def factorial(n):
2     result = 1
3     for i in range(2, n+1):
4         result *= i
5     return result
6 print(factorial(5))
View Code

用递归实现阶乘:

1 def factorial(n):
2      if n == 1:
3          return 1
4      else:
5          return n * factorial(n - 1)
6 print(factorial(6))
View Code

优点:

  • 递归使代码看起来更加整洁、优雅
  • 可以用递归将复杂任务分解成更简单的子问题
  • 使用递归比使用一些嵌套迭代更容易

缺点:

  • 递归的逻辑很难调试、跟进
  • 递归调用的代价高昂(效率低),因为占用了大量的内存和时间。

递归就是自己调自己。

1 def calc(n):
2     print(n)
3     if n/2>1:
4         res = calc(n/2)
5         print('res=',res)
6     return n
7 print(calc(10))
View Code

这段关于递归的代码展示的是递归如何调用自己,结束后又如何回去的。首先程序把第1行读到内存,然后执行第7行,---->调用calc()

函数,---->到第二行,打印出10---->进入第3行,满足if判断语句---->进入第4句,因为calc()函数有返回值,所以这里把返回值赋值给

变量res,本身第4句属于函数调用,只不过调用的是自身,所以---->执行第一句,进入第2句,打印出5---->继续判断,继续自己调用

自己---->2.5---->1.25---->此时不再满足if语句---->执行第6句,返回给谁呢?返回给变量res---->执行第5句,打印res=1.25---->继续执行

第6句,打印res=2.5---->打印res=5---->打印10---->结束。

1 def calc(n):
2     print(n)
3     if n/2>1:
4         res = calc(n/2)
5         print('res=',res)
6     return n
7 print(calc(10))

用for循环及列表实现斐波那契数列:

1 def fibs(num):
2      result = [0,1]
3      for i in range(num-2):
4          result.append(result[-2] + result[-1])
5      return result
6 print(fibs(10))
7 #运行结果:[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

用循环实现斐波那契数列:

1 def fibs(max):
2     n,a,b = 0,0,1
3     while n < max:
4         print (a)
5         a,b = b,a+b
6         n = n + 1
7     return 'done'
8 print(fibs(10))

或者:

1 1 def fibs(n):
2 2      a,b = 0,1
3 3      while a < n:
4 4          print (a)
5 5          a,b = b,a+b
6 6 fibs(8)

 利用递归实现:

1 def fibs(n):
2      if n == 0 or n == 1:
3          return 1
4      else :
5          return fibs(n-1) + fibs(n-2)
6 for i in range(10):
7     print(fibs(i))

或者:

 1 def fab(n):
 2   if n==0:
 3     return 0
 4   if n==1:
 5     return 1
 6   else:
 7     result=int(fab(n-2))+int(fab(n-1))
 8     return result
 9 for i in range(10):
10     print(fab(i))

用递归做二分查找:

#二分法算法找数字的思路:要在一个有序的数字列表中找到一个数字,
#拿数字列表的中间数与要查找的数字不断比较就行
import time
def found(data_source,find_n):
    mid=int(len(data_source)/2)
    if len(data_source)>=1:
    #if mid>0:
        if find_n<data_source[mid]:
            found(data_source[:mid],find_n)
         #print(data_source[:mid])
        elif find_n>data_source[mid]:
            found(data_source[mid:],find_n)
         #print(data_source[mid:])
        else:
            print('find_n=',data_source[mid])
    else:
        print('can not find %d'%find_n)
if __name__ == '__main__':
    data=list(range(1,1000000))
    starttime=time.time()
    found(data,782761)
    endtime = time.time()
    print('The running time is %d ms'%((endtime-starttime)*1000))
#运行结果:
#find_n= 782761
#The running time is 12 ms
View Code
原文地址:https://www.cnblogs.com/yibeimingyue/p/9327212.html