程式設計方法論
體育競技
from random import random
def printIntro():
print("這個程式模擬兩個選手A和B 的某種競技比賽")
print("程式執行需要A和B的能力值(0-1)")
def getInputs():
a = eval(input("請輸入選手A的能力值(0-1):"))
b = eval(input("請輸入選手B的能力值(0-1):"))
n = eval(input("請輸入模擬比賽的場次:"))
return a, b, n
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 gameOver(a, b):
return a == 15 or b == 15
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 printSummary(winsA, winsB):
n = winsA + winsB
print("競技分析開始,共模擬{}場比賽".format(n))
print("選手A獲勝{}場,佔比{:0.1%}".format(winsA, winsA/n))
print("選手B獲勝{}場,佔比{:0.1%}".format(winsB, winsB/n))
def main():
printIntro()
probA, probB, n = getInputs()
winsA, winsB = simNGames(n, probA, probB)
printSummary(winsA, winsB)
main()
這個程式模擬兩個選手A和B 的某種競技比賽
程式執行需要A和B的能力值(0-1)
請輸入選手A的能力值(0-1):0.45
請輸入選手B的能力值(0-1):0.5
請輸入模擬比賽的場次:1000
競技分析開始,共模擬1000場比賽
選手A獲勝368場,佔比36.8%
選手B獲勝632場,佔比63.2%
體育競技測試用例
import Sports
print(Sports.simNGames(500,0.45,0.5))
print(Sports.simNGames(1000,0.5,0.45))
print(Sports.simNGames(5000,0.44,0.46))
print(Sports.gameOver(15,10))
print(Sports.gameOver(6,8))
print(Sports.gameOver(3,15))
print(Sports.simOneGame(0.45,0.5))
print(Sports.simOneGame(0.5,0.45))
(180, 320)
(672, 328)
(2299, 2701)
True
False
True
(10, 15)
(15, 14)
批量安裝包
import os
libs ={"wordcloud","imageio"}
try:
for lib in libs:
os.system("pip install"+lib)
print("successful")
except:
print("false")
successful