当前位置: 首页 > web >正文

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")

运行截图:

 

http://www.xdnf.cn/news/1937.html

相关文章:

  • 论文学习:《聚类矩阵正则化指导的层次图池化》
  • Java多线程
  • 2.5 桥梁桥面系及附属结构施工
  • kafka课后总结
  • Spring @Transactional 自调用问题深度解析
  • 【Unity 与c++通信】Unity与c++通信注意事项,参数传递
  • websheet之 自定义函数
  • 成都种业博览会预登记火热进行中,6月8日-9日成都世纪城新国际会展中心与您不见不散!
  • [密码学实战]商用密码产品密钥体系架构:从服务器密码机到动态口令系统
  • vue前端SSE工具库|EventSource 替代方案推荐|PUSDN平行宇宙软件开发者网
  • 如何申请游戏支付平台通道接口?
  • PyTorch生成式人工智能实战(3)——分类任务详解
  • 施磊老师基于muduo网络库的集群聊天服务器(七)
  • 容器的网络类型
  • 视频噪点多,如何去除画面噪点?
  • 【基于Qt的QQMusic项目演示第一章】从界面交互到核心功能实现
  • 常见移动机器人底盘模型对比(附图)
  • Codeforces Round 1020 (Div. 3) A-D
  • 用diffusers库从单文件safetensor加载sdxl模型(离线)
  • 系统分析师-第九、十章
  • 蓝桥杯 3. 密码脱落
  • gradio 订单处理agent
  • 通过VSCode远程连接到CentOS7/Ubuntu18等老系统
  • 燃气经营从业人员有哪些类别
  • Doris vs ClickHouse:深入对比MPP数据库聚合操作的核心区别
  • Excel表格批量翻译对照翻译(使用AI助手)
  • ESG跨境电商如何为国内的跨境电商企业打开国外的市场
  • JDK 24:Java 24 中的新功能
  • SOC估算:开路电压修正的安时积分法
  • Doris表设计与分区策略:让海量数据管理更高效