首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >万能的Python代码实例

万能的Python代码实例

原创
作者头像
用户10815521
发布2023-12-10 22:46:10
发布2023-12-10 22:46:10
4000
举报
文章被收录于专栏:万能的Python万能的Python

1. 用Python写算法题

代码语言:python
复制
def bubble_sort(arr):
    n = len(arr)
    for i in range(n):
        for j in range(0, n - i - 1):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]

def main():
    arr = [64, 34, 25, 12, 22, 11, 90]
    print("原始数组:")
    print(arr)

    bubble_sort(arr)
    print("排序后的数组:")
    print(arr)

main()

2. 用Python玩剪刀石头布

代码语言:python
复制
import random

def get_user_choice():
    print("请输入你的选择:")
    print("1. 石头")
    print("2. 剪刀")
    print("3. 布")
    choice = int(input("请选择(1/2/3): "))
    return choice

def get_computer_choice():
    return random.randint(1, 3)

def determine_winner(user, computer):
    if user == computer:
        return "平局"
    elif (user == 1 and computer == 2) or (user == 2 and computer == 3) or (user == 3 and computer == 1):
        return "用户赢了"
    else:
        return "电脑赢了"

def main():
    print("欢迎来到石头、剪刀、布游戏!")
    user_choice = get_user_choice()
    computer_choice = get_computer_choice()
    print("电脑选择了:", computer_choice)
    result = determine_winner(user_choice, computer_choice)
    print("结果:", result)

main()

3. 用Python玩冒险游戏

代码语言:python
复制
def intro():
    print("欢迎来到文本冒险游戏!")
    print("在这个游戏中,你将扮演一个勇敢的英雄,探索一个危机四伏的世界。")
    print("你的决定将决定你的命运。祝你好运!")
    print()

def choose_path():
    print("你站在一个分叉路口。你可以选择向左走,也可以选择向右走。")
    path = input("你要走哪条路?(左/右): ").lower()

    if path == "左":
        print("你选择了向左走。你遇到了一头狮子!")
        lion_encounter()
    elif path == "右":
        print("你选择了向右走。你发现了一个宝箱!")
        treasure_chest()
    else:
        print("无效的输入。请重新输入。")
        choose_path()

def lion_encounter():
    print("狮子看起来很饿,它向你扑来。")
    action = input("你要做什么?(战斗/逃跑): ").lower()

    if action == "战斗":
        print("你勇敢地与狮子战斗,最终成功击败了它。你继续前进。")
        treasure_chest()
    elif action == "逃跑":
        print("你试图逃跑,但狮子追上了你,将你杀死了。游戏结束。")
    else:
        print("无效的输入。请重新输入。")
        lion_encounter()

def treasure_chest():
    print("你找到了一个宝箱,里面装满了金币和珠宝。恭喜你赢得了游戏!")

intro()
choose_path()

4. 用Python表白

这段代码首先导入了numpy和matplotlib.pyplot库。然后,我们创建了一个在0到2π之间均匀分布的一维数组t。接下来,我们使用t来计算爱心曲线的x和y坐标。最后,我们使用matplotlib的plot函数来画出爱心,并使用axis函数来设置坐标轴的属性。

代码语言:python
复制
import numpy as np
import matplotlib.pyplot as plt

t = np.linspace(0, 2 * np.pi, 1000)
x = 16 * np.sin(t) ** 3
y = 13 * np.cos(t) - 5 * np.cos(2 * t) - 2 * np.cos(3 * t) - np.cos(4 * t)

plt.plot(x, y, color='red')
plt.axis('equal')
plt.axis('off')
plt.show()

5. 用Python画正弦波

这段代码创建了一个简单的动画。它显示了一个正弦波的动态变化。每一帧都会稍微改变波的位置,从而产生一种波浪动起来的效果。

代码语言:python
复制
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation

# Set up the figure, the axis, and the plot element
fig, ax = plt.subplots()
x = np.linspace(0, 2*np.pi, 200)
line, = ax.plot(x, np.sin(x))

def animate(i):
    line.set_ydata(np.sin(x + i / 10))  # update the data
    return line,

# Create an animation
ani = FuncAnimation(fig, animate, frames=100, interval=20, blit=True)

plt.show()

6. 用Python画二维路径图

这段代码生成了一个二维随机漫步的可视化。在每一步,漫步者都随机地向上、下、左或右移动一步。随着步数的增加,您可以看到漫步者的路径如何在二维空间中发展。

代码语言:python
复制
import matplotlib.pyplot as plt
import random

# Number of steps
n = 1000

# X and Y coordinates
x = [0]
y = [0]

# Creating the random walk
for i in range(1, n):
    step_x = x[i - 1] + random.choice([-1, 1])
    step_y = y[i - 1] + random.choice([-1, 1])
    x.append(step_x)
    y.append(step_y)

# Plotting the random walk
plt.plot(x, y)
plt.title("2D Random Walk")
plt.xlabel("X Axis")
plt.ylabel("Y Axis")
plt.show()

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 用Python写算法题
  • 2. 用Python玩剪刀石头布
  • 3. 用Python玩冒险游戏
  • 4. 用Python表白
  • 5. 用Python画正弦波
  • 6. 用Python画二维路径图
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档