14 python基础--复用和递归

14.1 代码复用

函数和对象是代码复用的两种主要形式
+ 函数:将代码命名,在代码层面上建立初步抽象
+ 对象:属性和方法,如<a>.<b>和<a>.<b>() 在函数之上再次组织进行抽样

14.2 模块化设计

通过函数或对象封装将程序划分为模块及模块间的表达
高内聚、低耦合

14.3 递归

特征:基例、链条
1、例子
  • f(n) =f(n-1)+f(n-2) --(当n=1或n=2时,f(n)=1)
def y(n):
    if n == 1 or n == 2:
        return 1
    else:
        return y(n-1)+y(n-2)
print(y(4))
>3
  • 字符串反转
def rvs(s):
    if s == '':
        return s
    else:
        return rvs(s[1:])+ s[0]

m = 'wefsdfsdvbngh'
print(rvs(m))

>hgnbvdsfdsfew
  • 汉诺塔
count =0
def y(n,start,end,mid):
    if n == 1:
        global count
        count += 1
        print('{}:{}->{}'.format(1,start,end))
    else:
        y(n-1,start,mid,end)
        count += 1
        y(n-1,mid,end,start)
        print('{}:{}->{}'.format(n,start,end))

y(9,'a','b','m')
print(count)
import  turtle as t
import time
def koch(size,n):
    if n ==0:
        t.fd(size)
    else:
        for i in [0,60,-120,60]:
            t.left(i)
            koch(size/3,n-1)

def main():
    t.setup(800,600,100,100)
    t.speed(100)
    t.pencolor('red')
    t.pensize(2)
    t.penup()
    t.goto(-300,0)
    t.pendown()
    koch(300,4)
    t.left(-120)
    koch(300,4)
    t.left(-120)
    koch(300,4)
    t.hideturtle()

main()
time.sleep(5)

猜你喜欢

转载自blog.csdn.net/qq_25672165/article/details/85059463