相对有难度的Python例子

1.查找两个文件中共同出现的单词

import re

def get_words(file_path):
    """获取一个文件内所有单词"""
    with open(file_path, 'r') as f:
        content = f.read()
    words = re.findall(r'\b\w+\b', content)
    return set(words)

file1 = "file1.txt"
file2 = "file2.txt"

words1 = get_words(file1)
words2 = get_words(file2)

common_words = words1 & words2

print("共同出现的单词有:", common_words)

这个程序会读取两个文本文件并分别提取出所有单词,然后计算出这两个文件中共同出现的单词并输出结果。

2.使用递归算法求解汉诺塔问题

def hanoi(n, source, target, temp):
    """递归算法求解汉诺塔问题"""
    if n == 1:
        print("将盘子从", source, "移动到", target)
    else:
        hanoi(n - 1, source, temp, target)
        print("将盘子从", source, "移动到", target)
        hanoi(n - 1, temp, target, source)

hanoi(3, "A", "C", "B")

这个程序使用递归算法来解决汉诺塔问题。在这个问题中,我们需要将n个盘子从源柱子移动到目标柱子,同时借助一个临时柱子。其中,每一个盘子都比下面的盘子小。这个程序会输出每一步移动的盘子以及对应的柱子。

3.使用matplotlib绘制三维曲面图

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

fig = plt.figure()
ax = Axes3D(fig)

X = np.arange(-5, 5, 0.1)
Y = np.arange(-5, 5, 0.1)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='rainbow')

plt.show()

这个程序使用matplotlib库绘制了一个三维曲面图

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱分享的大户爱

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值