基于python数据结构与算法(四)——递归

一. 递归思想:

将问题分解为规模更小的去解决
举个例子:

案例一:递归实现任意进制的转化

def toStr(n,base):
	convertString = "0123456789ABCDEF"
	if n < base:
		return convertString[0]
	else:
		return toStr(n//base,base) + convertString[n%base]

print(toStr(1453,16))

基于python数据结构与算法(四)——递归_第1张图片

基于python数据结构与算法(四)——递归_第2张图片

案例二:绘制分形树

基于python数据结构与算法(四)——递归_第3张图片

基于python数据结构与算法(四)——递归_第4张图片

import turtle

def tree(branch_len):
	if branch_len > 5: # 树干太短不画,即递归结束
		t.forward(branch_len) # 画树干
		t.right(20) # 右倾斜20度
		tree(branch_len - 15) # 递归调用,画右边的小树,树干减15
		t.left(40) # 左回40度,即向左倾斜20度
		tree(branch_len - 15)
		t.right(20) # 回正
		t.backward(branch_len) # 海龟退回原位置


t = turtle.Turtle()
t.left(90) # 初始状态默认是向右的
t.penup()
t.backward(100)
t.pendown()
t.pencolor('green')
t.pensize(2)
tree(75) # 画树干长度75的二叉树
t.hideturtle()
turtle.done() # 结束绘制

案例三:谢尔宾斯三角形:

基于python数据结构与算法(四)——递归_第5张图片

import turtle


def sierpinski(degree, points):  # degree是阶数,points是一个字典,表示等边三角形的三个顶点坐标
    colormap = ['blue', 'red', 'green', 'white', 'yellow', 'orange']
    drawTriangle(points, colormap[degree])
    if degree > 0:
        sierpinski(degree - 1,
                   {'left': points['left'],
                    'top': getMid(points['left'], points['top']),
                    'right': getMid(points['left'], points['right'])})


        sierpinski(degree - 1,
                   {'left': getMid(points['left'], points['top']), 'top': points['top'],
                    'right': getMid(points['top'], points['right'])})

        sierpinski(degree - 1,
                   {'left': getMid(points['left'], points['right']),
                    'top': getMid(points['top'], points['right']),
                    'right': points['right']})


def drawTriangle(points, color):  # 绘制等边三角形
    t.fillcolor(color)
    t.penup()
    t.goto(points['top'])
    t.pendown()
    t.begin_fill()
    t.goto(points['left'])
    t.goto(points['right'])
    t.goto(points['top'])
    t.end_fill()


def getMid(p1, p2):  # 取两个点的中点,x,y坐标
    return ((p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2)


t = turtle.Turtle()  # 轮廓的三个顶点
points = {'left': (-200, -100),
          'top': (0, 200),
          'right': (200, -100)}

sierpinski(5, points)  # 画三角形

turtle.done()



案例四. 探索迷宫:

important!
基于python数据结构与算法(四)——递归_第6张图片

基于python数据结构与算法(四)——递归_第7张图片

迷宫的数据结构:Maze Class

class Maze:
	def __init__(self,mazeFileName):
		rowsInMaze = 0
		columnsInMaze = 0
		self.mazelist = []
		mazeFile = open(mazeFileName,'r') #从文本文件读入
		rowsInMaze = 0
		for line in mazeFile:
			rowList = []
			col = 0
			for ch in line[:-1]:
				rowList.append(ch)
				if ch =='S':
					welf.startRow = rowsInMaze
					self.startCol = col 
				col = col + 1
			rowsInMaze = rowsInMaze + 1
			self.mazelist.append(rowlist)
			columnsInMaze = len(rowList)

基于python数据结构与算法(四)——递归_第8张图片

基于python数据结构与算法(四)——递归_第9张图片

基于python数据结构与算法(四)——递归_第10张图片

基于python数据结构与算法(四)——递归_第11张图片

基于python数据结构与算法(四)——递归_第12张图片

基于python数据结构与算法(四)——递归_第13张图片

基于python数据结构与算法(四)——递归_第14张图片

递归代码:
基于python数据结构与算法(四)——递归_第15张图片

你可能感兴趣的:(#,算法入门)