(笔记)第5周 函数和代码复用

313 阅读3分钟

中国大学MOOC - Python语言程序设计 - 第5周

5.1 函数的定义与使用

5.2 实例7: 七段数码管绘制

#drawSevenDigits
import turtle as t
import time as time

# 绘制数码管间隔:每一段都留一定空白,更美观
def drawGap():
    t.penup()
    t.fd(5)

# 绘制单段数码管:画一条线
def drawLine(flag):
    drawGap()
    t.pendown() if flag else t.penup()
    t.fd(40)
    drawGap()
    t.right(90)

# 根据数字绘制七段数码管:画一个数字
def drawDigit(digit):
    # 数码管有七段,按固定顺序绘制
    drawLine(True) if digit in [2, 3, 4, 5, 6, 8, 9] else drawLine(False) # 笔画1
    drawLine(True) if digit in [0, 1, 3, 4, 5, 6, 7, 8, 9] else drawLine(False)
    drawLine(True) if digit in [0, 2, 3, 5, 6, 8, 9] else drawLine(False)
    drawLine(True) if digit in [0, 2, 6, 8] else drawLine(False)
    t.left(90)
    drawLine(True) if digit in [0, 4, 5, 6, 8, 9] else drawLine(False)
    drawLine(True) if digit in [0, 2, 3, 5, 6, 7, 8, 9] else drawLine(False)
    drawLine(True) if digit in [0, 1, 2, 3, 4, 7, 8, 9] else drawLine(False)
    t.left(180) # 转回去(水平向右),为绘制其他数字做好准备
    t.penup()
    t.fd(20)    # 为绘制其他数字确定起点位置

# 画多个数字
def drawData(data):
    # 设输入的数据类型是“2020+09-01=”,希望绘制成“2020年09月01日”
    t.pencolor('red')
    for i in data:
        if i == '+':
            t.write('年', font = ('Arial', 18, 'normal')) # 绘制汉字
            t.fd(40)
            t.pencolor('green')
        elif i == '-':
            t.write('月', font = ('Arial', 18, 'normal'))
            t.fd(40)
            t.pencolor('blue')
        elif i == '=':
            t.write('日', font = ('Arial', 18, 'normal'))
            t.fd(40)
        else:
            drawDigit(eval(i))

def main():
    # 初始化
    t.setup(800, 350, 200, 200)
    t.penup()
    t.fd(-300)
    t.pensize(5)
    # 绘制当前日期
    drawData(time.strftime('%Y+%m-%d=', time.gmtime()))
    # 结束绘制
    t.hideturtle()
    t.done() # 避免绘画窗体 Python Turtle Graphics(未响应)而且可以保留绘画窗体不闪退
    
main()

5.3 代码复用与函数递归

递归 例1:字符串反转

#reverseStr.py 字符串反转
def rvsStr(s):
    if s == "" :
        return s # 别漏了s...
    else :
        return rvsStr(s[1:]) + s[0] # 分成两部分:第一个字符+其余字符,建立递归链条

print(rvsStr('hello world'))

# 当然,可以直接用 s[::-1]

递归 例2:汉诺塔问题

#solveHanoi
def Hanoi(n, src, dst, mid):
    global count # 需要声明是全局变量
    if n == 1: # 第1个盘子(最上面那个)
        print('{0}:{1}->{2}'.format(n, src, dst))
        count += 1
    else:
        # 把前n-1个从src搬运到mid
        Hanoi(n-1, src, mid, dst)
        # 把第n个(最后一个)从src搬运到dst
        print('{0}:{1}->{2}'.format(n, src, dst))
        count += 1
        # 再把前n-1个从mid搬运到dst
        Hanoi(n-1, mid, dst, src)

# 测试1:共2个盘子
count = 0
Hanoi(2, '源', '目标', '中间')
print('总次数 = {}'.format(count))

# 测试2:共3个盘子
count = 0
Hanoi(3, '源', '目标', '中间')
print('总次数 = {}'.format(count))

5.4 模块4: PyInstaller库的使用

5.5 实例8 科赫雪花小包裹

#drawKoch.py 科赫雪花
import turtle as t
import os

def kochCurve(len, n):
    if n == 0:
        t.fd(len)
    else:
        for angle in [0, 60, -120, 60]:
            t.left(angle)
            kochCurve(len/3, n-1)

def main():
    # 初始化
    t.setup(600,600)
    t.penup()
    t.goto(-200, 100) # 直接goto移动
    t.pendown()
    t.pensize(2)
    # 画雪花
    level = 3 # 3阶科赫雪花,阶数
    for i in range(3):
        kochCurve(400, level)
        t.right(120)
    # 结束绘制
    t.hideturtle()
    t.done() # 避免绘画窗体 Python Turtle Graphics(未响应)而且可以保留绘画窗体不闪退


main()

Python Turtle Graphics(未响应)解决办法 - CSDN

练习题

5.3 任意累积

我的提问

#practice3_add.py

def cmul(*s):
    m = 1
    for i in s:
        m *= i
    return m

print(eval("cmul({})".format(input())))

# 理解
"""
input()返回字符串

"cmul({})".format(input())是把字符串填到一个字符串里面,
得到eu仍然是字符串。如输入是1,2,3,会得到:"cmul(1,2,3)"。
注意到此时相当于输入了(1,2,3)这个元组

eval("cmul({})".format(input()))是把字符串n的""去掉。
仍以上面的例子为例,"cmul(1,2,3)"去掉"",则得到cmul(1,2,3),
相当于运行函数cmul(1,2,3)

最后print该函数的返回结果,即return的m
"""