Python实验三
实验 3 函数与代码复用
目的:理解函数封装与递归思想 实验任务:
1. 基础 :编写函数 cal_factorial(n)计算阶乘(循环实现)。
1. 基础 :编写函数 cal_factorial(n)计算阶乘(循环实现)。
def cal_factorial(n):
if n < 0:
raise ValueError("n must be a non-negative integer")
result = 1
for i in range(1, n + 1):
result *= i
return result
2. 进阶 :用递归实现斐波那契数列(考虑添加缓存优化)。
from functools import lru_cache
@lru_cache(maxsize=None) # 使用装饰器添加缓存
def fibonacci(n):
if n <= 0:
raise ValueError("n must be a positive integer")
if n == 1 or n == 2:
return 1
return fibonacci(n - 1) + fibonacci(n - 2)
3. 拓展 :科赫曲线正向、反向绘制,加入绘制速度、绘制颜色等额外 功能
import matplotlib.pyplot as plt
import numpy as np
def koch_curve(x1, y1, x2, y2, n, direction="forward"):
if n == 0:
plt.plot([x1, x2], [y1, y2], color="blue", linewidth=1)
return
# 计算分段点
x3 = (2 * x1 + x2) / 3
y3 = (2 * y1 + y2) / 3
x4 = (x1 + x2) / 2 + (y2 - y1) * np.sqrt(3) / 6
y4 = (y1 + y2) / 2 - (x2 - x1) * np.sqrt(3) / 6
x5 = (x1 + 2 * x2) / 3
y5 = (y1 + 2 * y2) / 3
if direction == "forward":
koch_curve(x1, y1, x3, y3, n - 1, direction)
koch_curve(x3, y3, x4, y4, n - 1, direction)
koch_curve(x4, y4, x5, y5, n - 1, direction)
koch_curve(x5, y5, x2, y2, n - 1, direction)
elif direction == "backward":
koch_curve(x5, y5, x4, y4, n - 1, direction)
koch_curve(x4, y4, x3, y3, n - 1, direction)
koch_curve(x3, y3, x1, y1, n - 1, direction)
koch_curve(x2, y2, x5, y5, n - 1, direction)
def draw_koch_curve(n, length=300, direction="forward"):
fig, ax = plt.subplots()
ax.set_aspect('equal')
ax.axis('off')
x1, y1 = 0, 0
x2, y2 = length, 0
koch_curve(x1, y1, x2, y2, n, direction)
plt.show()
if __name__ == "__main__":
print("\nDrawing Koch Curve:")
draw_koch_curve(n=4, direction="forward") # 正向绘制
draw_koch_curve(n=4, direction="backward") # 反向绘制
提示:递归函数需注意终止条件,避免栈溢出
完整代码:
import matplotlib.pyplot as plt
import numpy as np
from functools import lru_cache
import timedef cal_factorial(n):if n < 0:raise ValueError("n must be a non-negative integer")result = 1for i in range(1, n + 1):result *= ireturn result@lru_cache(maxsize=None)
def fibonacci(n):if n <= 0:raise ValueError("n must be a positive integer")if n == 1 or n == 2:return 1return fibonacci(n - 1) + fibonacci(n - 2)def koch_curve(x1, y1, x2, y2, n, direction="forward", color="blue"):if n == 0:plt.plot([x1, x2], [y1, y2], color=color, linewidth=1)returnx3 = (2 * x1 + x2) / 3y3 = (2 * y1 + y2) / 3x4 = (x1 + x2) / 2 + (y2 - y1) * np.sqrt(3) / 6y4 = (y1 + y2) / 2 - (x2 - x1) * np.sqrt(3) / 6x5 = (x1 + 2 * x2) / 3y5 = (y1 + 2 * y2) / 3if direction == "forward":koch_curve(x1, y1, x3, y3, n - 1, direction, color)koch_curve(x3, y3, x4, y4, n - 1, direction, color)koch_curve(x4, y4, x5, y5, n - 1, direction, color)koch_curve(x5, y5, x2, y2, n - 1, direction, color)elif direction == "backward":koch_curve(x5, y5, x4, y4, n - 1, direction, color)koch_curve(x4, y4, x3, y3, n - 1, direction, color)koch_curve(x3, y3, x1, y1, n - 1, direction, color)koch_curve(x2, y2, x5, y5, n - 1, direction, color)def draw_koch_curve(n, length=300, direction="forward", color="blue"):fig, ax = plt.subplots()ax.set_aspect('equal')ax.axis('off')x1, y1 = 0, 0x2, y2 = length, 0koch_curve(x1, y1, x2, y2, n, direction, color)plt.show()if __name__ == "__main__":print("Testing cal_factorial:")print("Factorial of 5:", cal_factorial(5)) print("Factorial of 0:", cal_factorial(0)) print("\nTesting fibonacci:")start_time = time.time()for i in range(1, 11):print(f"Fibonacci({i}):", fibonacci(i))end_time = time.time()print(f"Time taken: {end_time - start_time:.6f} seconds")print("\nDrawing Koch Curve:")print("Forward Koch Curve:")draw_koch_curve(n=4, length=300, direction="forward", color="blue")print("Backward Koch Curve:")draw_koch_curve(n=4, length=300, direction="backward", color="red")
运行截图: