第8 章

8.1
from random import random

def printIntro():
print("这个程序模拟乒乓球比赛,分析体育竞技规律。")
print("程序运行需要输入两个选手的能力值(0 - 1之间的小数)和模拟比赛的场次。")

def getInputs():
a = eval(input("请输入选手A的能力值(0 - 1): "))
b = eval(input("请输入选手B的能力值(0 - 1): "))
n = eval(input("请模拟比赛的场次: "))
return a, b, n

def simOneGame(probA, probB):
scoreA, scoreB = 0, 0
serving = "A"
while not gameOver(scoreA, scoreB):
if serving == "A":
if random() < probA:
scoreA += 1
else:
serving = "B"
else:
if random() < probB:
scoreB += 1
else:
serving = "A"
return scoreA, scoreB

def gameOver(a, b):
return a >= 11 and (a - b) >= 2 or b >= 11 and (b - a) >= 2

def simNGames(n, probA, probB):
winsA, winsB = 0, 0
for i in range(n):
scoreA, scoreB = simOneGame(probA, probB)
if scoreA > scoreB:
winsA += 1
else:
winsB += 1
return winsA, winsB

def printSummary(winsA, winsB):
n = winsA + winsB
print(f"共模拟了{n}场比赛")
print(f"选手A获胜 {winsA} 场,占比 {winsA / n:.1%}")
print(f"选手B获胜 {winsB} 场,占比 {winsB / n:.1%}")

def main():
printIntro()
probA, probB, n = getInputs()
winsA, winsB = simNGames(n, probA, probB)
printSummary(winsA, winsB)

if name == "main":
main()

8.2
from random import random

def printIntro():
print("这个程序模拟篮球比赛,分析体育竞技规律。")
print("程序运行需要输入两个球队的能力值(0 - 1之间的小数)和模拟比赛的场次。")

def getInputs():
a = eval(input("请输入球队A的能力值(0 - 1): "))
b = eval(input("请输入球队B的能力值(0 - 1): "))
n = eval(input("请输入模拟比赛的场次: "))
return a, b, n

def simOneGame(probA, probB):
scoreA, scoreB = 0, 0
while True:

if random() < probA:
scoreA += 2
else:

if random() < probB:
scoreB += 2
else:

pass

if scoreA >= 100 or scoreB >= 100:
break
return scoreA, scoreB

def simNGames(n, probA, probB):
winsA, winsB = 0, 0
for _ in range(n):
scoreA, scoreB = simOneGame(probA, probB)
if scoreA > scoreB:
winsA += 1
else:
winsB += 1
return winsA, winsB

def printSummary(winsA, winsB):
n = winsA + winsB
print(f"共模拟了{n}场比赛")
print(f"球队A获胜 {winsA} 场,占比 {winsA / n:.1%}")
print(f"球队B获胜 {winsB} 场,占比 {winsB / n:.1%}")

def main():
printIntro()
probA, probB, n = getInputs()
winsA, winsB = simNGames(n, probA, probB)
printSummary(winsA, winsB)

if name == "main":
main()

8.6
from PIL import Image, ImageFilter

def create_emboss_image(input_path, output_path):
"""
使用Pillow库生成图像浮雕效果

:param input_path: 输入图像路径
:param output_path: 输出图像路径
"""
image = Image.open(input_path)
embossed_image = image.filter(ImageFilter.EMBOSS)
embossed_image.save(output_path)

if name == "main":
input_image_path = "C:\Users\CY\Pictures\Screenshots\屏幕截图 2025-05-25 151545.png"
output_image_path = "C:\Users\CY\Pictures\Screenshots\浮雕效果_屏幕截图 2025-05-25 151545.png"
create_emboss_image(input_image_path, output_image_path)

posted @ 2025-05-25 15:28  piuky  阅读(70)  评论(0)    收藏  举报