渐入佳境。
# coding: utf-8 import turtle ''' # =================turtle练手== def draw_spiral(my_turtle, line_len): if line_len > 0: my_turtle.forward(line_len) my_turtle.right(70) draw_spiral(my_turtle, line_len-10) my_tur = turtle.Turtle() my_win = turtle.Screen() draw_spiral(my_tur, 200) my_win.exitonclick() # =================分形树== def tree(branch_len, my_turtle): if branch_len > 5: my_turtle.forward(branch_len) my_turtle.right(20) tree(branch_len-15, my_turtle) my_turtle.left(40) tree(branch_len - 15, my_turtle) my_turtle.right(20) my_turtle.backward(branch_len) my_tur = turtle.Turtle() my_win = turtle.Screen() my_tur.left(90) my_tur.up() my_tur.backward(100) my_tur.down() my_tur.color('green') tree(100, my_tur) my_win.exitonclick() # =================谢尔宾斯基三角形== def draw_triangle(points, color, my_turtle): my_turtle.fillcolor(color) my_turtle.up() my_turtle.goto(points[0][0], points[0][1]) my_turtle.down() my_turtle.begin_fill() my_turtle.goto(points[1][0], points[1][1]) my_turtle.goto(points[2][0], points[2][1]) my_turtle.goto(points[0][0], points[0][1]) my_turtle.end_fill() def get_mid(p1, p2): return (p1[0]+p2[0])/2, (p1[1]+p2[1])/2 def sierpinski(points, degree, my_turtle): color_map = ['blue', 'red', 'green', 'white', 'yellow', 'violet', 'orange'] draw_triangle(points, color_map[degree], my_turtle) if degree > 0: sierpinski([points[0], get_mid(points[0], points[1]), get_mid(points[0], points[2])], degree-1, my_turtle) sierpinski([points[1], get_mid(points[0], points[1]), get_mid(points[1], points[2])], degree-1, my_turtle) sierpinski([points[2], get_mid(points[2], points[1]), get_mid(points[0], points[2])], degree-1, my_turtle) my_tur = turtle.Turtle() my_win = turtle.Screen() my_points = [[-100, -50], [0, 100], [100, -50]] sierpinski(my_points, 4, my_tur) my_win.exitonclick() ''' # =======================================汉诺塔== def move_tower(height, from_pole, to_pole, with_pole): if height >= 1: move_tower(height-1, from_pole, with_pole, to_pole) move_disk(from_pole, to_pole, height) move_tower(height-1, with_pole, to_pole, from_pole) def move_disk(fp, tp, disk_name): print('moving 碟子 {0} from {1} to {2}'.format(disk_name, fp, tp)) high = 4 move_tower(high, '起始杆', '末尾杆', '中间杆')
C:\Users\Sahara\.virtualenvs\untitled\Scripts\python.exe D:/test/python_recursion.py moving 碟子 1 from 起始杆 to 中间杆 moving 碟子 2 from 起始杆 to 末尾杆 moving 碟子 1 from 中间杆 to 末尾杆 moving 碟子 3 from 起始杆 to 中间杆 moving 碟子 1 from 末尾杆 to 起始杆 moving 碟子 2 from 末尾杆 to 中间杆 moving 碟子 1 from 起始杆 to 中间杆 moving 碟子 4 from 起始杆 to 末尾杆 moving 碟子 1 from 中间杆 to 末尾杆 moving 碟子 2 from 中间杆 to 起始杆 moving 碟子 1 from 末尾杆 to 起始杆 moving 碟子 3 from 中间杆 to 末尾杆 moving 碟子 1 from 起始杆 to 中间杆 moving 碟子 2 from 起始杆 to 末尾杆 moving 碟子 1 from 中间杆 to 末尾杆 Process finished with exit code 0