python 下的数据结构与算法---5:递归(Recursion)

定义:递归就是不断分割整体成部分直到可以轻易解决分割出来的部分。

递归表达式三定律:

       1:递归表达式必须有个最小单元     (最小单元既是停止递归调用以及能够直接运算的)

       2:递归表达式在运算过程中必须向最小单元移动

       3:递归表达式必须递归的调用自己

一:简单实例:

       1:求数字数组所有元素的和

    def sum(seq=[]):

      if len(seq)==1:

        return seq[0]

      return seq[0]+sum(seq[1:])

    print('sum of the list:',sum([1,2,3,4,5,6,7,8,9]))

       2:求阶乘

    def factorial(n):

      if n==1:

        return 1

                  return n*factorial(n-1)

    print('10!=',factorial(10))

  3:将十进制数转化为任意进制的string型字符串

    #回顾一下在讲堆的应用时也实现了类似功能

    convert_string = "0123456789ABCDEF"

    def to_str(n, base):

      global convert_string

      if n < base:

        return convert_string[n]

      else:

        return to_str(n//base, base) + convert_string[n % base]

    print(to_str(769, 2))

       4:反转字符串

    def reverse(string):

      if len(string)==1:

        return str(string)

          return str(string[len(string)-1])+reverse(string[:len(string)-1])

    print(reverse('string'))

  5:汉诺塔问题(hanoi)

    问题:古代有一个梵塔,塔内有3个座A、B、C,开始时A座上面有64个盘子,盘子大小不等,大的在下,小的在上。现要求将这64个盘子从A全部移到C上,每次只允许移动一个盘子,且在移动过程中在3个座上都始终保持大盘在下,小盘在上。移动过程中可以利用B座。

    注意:下面的实现过程不像上面单独的把最小单元提取出来进行处理与返回,我们知道,最小单元是只有一个盘,直接移动就是了,对应下面当height为1时,此时move_tower(height - 1, from_pole, middle_pole, to_pole)与move_tower(height - 1, middle_pole, to_pole, from_pole)调用时height-1的结果是0,故什么都不返回。

                   def move_tower(height, from_pole, to_pole, middle_pole):

                         if height >= 1:

                                move_tower(height - 1, from_pole, middle_pole, to_pole)

                                 move_disk(from_pole, to_pole)

                                move_tower(height - 1, middle_pole, to_pole, from_pole)

      def move_disk(fp,tp):

                         print("moving disk from",fp,"to",tp)

      move_tower(3, "A", "B", "C")

二:复杂实例之走出迷宫

       1:画图之turtle模块

    

    import turtle

    my_turtle = turtle.Turtle()

    my_win = turtle.Screen()

    def draw_spiral(my_turtle, line_len):

      if line_len > 0:

                      my_turtle.forward(line_len)

              my_turtle.right(90)     #只是转向90°

              draw_spiral(my_turtle, line_len - 5)

    draw_spiral(my_turtle, 100)

    my_win.exitonclick()                  #点击图像后退出

   

  2:迷宫分析

         基本原理:分别按上下左右的顺序来进行迭代行走,一个方向碰壁后进入下一个方向

         需叠加:要纪录走过的路,这样避免画圈式死循环

原文地址:https://www.cnblogs.com/pengsixiong/p/5322347.html