相对有难度的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库绘制了一个三维曲面图

猜你喜欢

转载自blog.csdn.net/weixin_51378457/article/details/129478778