参考书籍:python程序设计
chapter9
1.
from random import random
def main():
printIntro()
probA, probB, n = getInputs()
winsA, winsB = simNGames(n, probA, probB)
printSummary(winsA, winsB)
def printIntro():
print("Thsi program simulates a gane of racquetball between two")
print('players called "A" and "B". The ability of each player is')
print("indicated by a probability (a number between 0 and 1) that")
print("the player wins the point when serving. Players A always")
print("has the first serve.")
def getInputs():
#returns three simulation parameters
a = float(input("What is the prob. player A wins a serve? "))
b = float(input("What is the prob. player B wins a serve? "))
n = int(input("How many games to simulate? "))
return a, b, n
def simNGames(n, probA, probB):
#simulates n games of racquetball between palyers whose
# abilities are represented by the probablity of winning a serve.
#Returns number of wins for A and B
winsA = winsB = 0
for i in range(n):
scoreA, scoreB = simOneGame(i, probA, probB)
if scoreA > scoreB:
winsA += 1
else:
winsB += 1
return winsA, winsB
def simOneGame(n, probA, probB):
#simulate a single game or racquetball between players whose
# abilities are represented by the probability of winning a serve.
#returns final scores for A and B.
if n % 2 == 0:
serving = "A"
#print("A is playing.")
else:
serving = "B"
#print("B is playing.")
scoreA = 0
scoreB = 0
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):
#a and b represent scores for a racquetball game.
#returns True if the game is over, False otherwise.
return a == 15 or b == 15
def printSummary(winsA, winsB):
#Prints a summary of wins for each other.
n = winsA + winsB
print("/nGames simulated: ", n)
print("Wins for A: {0} ({1:0.1%})".format(winsA, winsA / n))
print("Wins for B: {0} ({1:0.1%})".format(winsB, winsB / n))
if __name__ == "__main__":
main()
3.
#vallyball1
from random import random
def main():
printIntro()
probA, probB, n = getInputs()
winsA, winsB = simNGames(n, probA, probB)
printSummary(winsA, winsB)
def printIntro():
print("Thsi program simulates a gane of racquetball between two")
print('players called "A" and "B". The ability of each player is')
print("indicated by a probability (a number between 0 and 1) that")
print("the player wins the point when serving. Players A always")
print("has the first serve.")
def getInputs():
#returns three simulation parameters
a = float(input("What is the prob. player A wins a serve? "))
b = float(input("What is the prob. player B wins a serve? "))
n = int(input("How many games to simulate? "))
return a, b, n
def simNGames(n, probA, probB):
#simulates n games of racquetball between palyers whose
# abilities are represented by the probablity of winning a serve.
#Returns number of wins for A and B
winsA = winsB = 0
for i in range(n):
scoreA, scoreB = simOneGame(i, probA, probB)
if scoreA > scoreB:
winsA += 1
else:
winsB += 1
return winsA, winsB
def simOneGame(n, probA, probB):
#simulate a single game or racquetball between players whose
# abilities are represented by the probability of winning a serve.
#returns final scores for A and B.
if n % 2 == 0:
serving = "A"
#print("A is playing.")
else:
serving = "B"
#print("B is playing.")
scoreA = 0
scoreB = 0
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):
#a and b represent scores for a racquetball game.
#returns True if the game is over, False otherwise.
done = False
if (a >= 15 or b >= 15) and abs(a - b) >= 2:
done = True
return done
def printSummary(winsA, winsB):
#Prints a summary of wins for each other.
n = winsA + winsB
print("/nGames simulated: ", n)
print("Wins for A: {0} ({1:0.1%})".format(winsA, winsA / n))
print("Wins for B: {0} ({1:0.1%})".format(winsB, winsB / n))
if __name__ == "__main__":
main()
4.
#vallyball2
from random import random
def main():
printIntro()
probA, probB, n = getInputs()
winsA, winsB = simNGames(n, probA, probB)
printSummary(winsA, winsB)
def printIntro():
print("Thsi program simulates a gane of racquetball between two")
print('players called "A" and "B". The ability of each player is')
print("indicated by a probability (a number between 0 and 1) that")
print("the player wins the point when serving. Players A always")
print("has the first serve.")
def getInputs():
#returns three simulation parameters
a = float(input("What is the prob. player A wins a serve? "))
b = float(input("What is the prob. player B wins a serve? "))
n = int(input("How many games to simulate? "))
return a, b, n
def simNGames(n, probA, probB):
#simulates n games of racquetball between palyers whose
# abilities are represented by the probablity of winning a serve.
#Returns number of wins for A and B
winsA = winsB = 0
for i in range(n):
scoreA, scoreB = simOneGame(i, probA, probB)
if scoreA > scoreB:
winsA += 1
else:
winsB += 1
return winsA, winsB
def simOneGame(n, probA, probB):
#simulate a single game or racquetball between players whose
# abilities are represented by the probability of winning a serve.
#returns final scores for A and B.
if n % 2 == 0:
serving = "A"
#print("A is playing.")
else:
serving = "B"
#print("B is playing.")
scoreA = 0
scoreB = 0
while not gameOver(scoreA, scoreB):
if serving == "A":
if random() < probA:
scoreA += 1
else:
scoreB += 1
serving = "B"
else:
if random() < probB:
scoreB += 1
else:
scoreA += 1
serving = "A"
print(scoreA, scoreB)
return scoreA, scoreB
def gameOver(a, b):
#a and b represent scores for a racquetball game.
#returns True if the game is over, False otherwise.
return a == 25 or b == 25
def printSummary(winsA, winsB):
#Prints a summary of wins for each other.
n = winsA + winsB
print("/nGames simulated: ", n)
print("Wins for A: {0} ({1:0.1%})".format(winsA, winsA / n))
print("Wins for B: {0} ({1:0.1%})".format(winsB, winsB / n))
if __name__ == "__main__":
main()
10.
#This pro estimates the value of pi.
from random import random
def main():
n = int(input("Enter the number you want to play the games: "))
h = playNGames(n)
esti_pi = 4 * h / n
print("The estimation of pi is {0}.".format(esti_pi))
def playNGames(n):
h = 0
for i in range(n):
inCircle = playOneGame()
h = h + inCircle
return h
def playOneGame():
x, y = 2 * random() - 1, 2 * random() - 1
if x ** 2 + y ** 2 <= 1:
inCircle = 1
else:
inCircle = 0
return inCircle
if __name__ == "__main__":
main()
12.
#This pro simulates one-dim random walking
from random import random
def main():
n = int(input("Enter the step nums: "))
loc_pos = nStepWalk(n)
print("present location is {0}.".format(loc_pos))
def nStepWalk(n):
loc = 0
for i in range(n):
loc = OneStepWalk(loc)
return loc
def OneStepWalk(loc):
x = random()
if x <= 0.5:
loc += 1
else:
loc -= 1
return loc
if __name__ == "__main__":
main()
13.
#This pro simulates two-dim random walking
from random import random
def main():
n = int(input("Enter the step nums: "))
pos_x, pos_y = nStepWalk(n)
print("present location is ({0}, {1}).".format(pos_x, pos_y))
def nStepWalk(n):
loc_x, loc_y = 0, 0
for i in range(n):
next_x, next_y = OneStepWalk(loc_x, loc_y)
loc_x, loc_y = next_x, next_y
return loc_x, loc_y
'''
def OneStepWalk(loc_x, loc_y):
x = random()
y = random()
if x <= 0.5: #left and right about y with prob = 0.5
if y <= 0.5:#right
loc_y += 1
else:#left
loc_y -= 1
else: #back or front about x with prob = 0.5
if y <= 0.5:#front
loc_x += 1
else:#back
loc_x -= 1
return loc_x, loc_y
'''
def OneStepWalk(loc_x, loc_y):
x = random()
if x <= 0.25:
loc_x += 1
elif x <= 0.5:
loc_x -= 1
elif x <= 0.75:
loc_y += 1
else:
loc_y -= 1
return loc_x, loc_y
if __name__ == "__main__":
main()
14.
#This pro simulates random direction walking and plot the route.
from random import random
from graphics import *
import math
def drawWin():
win = GraphWin("route", 500, 500)
win.setBackground('white')
win.setCoords(-100, -100, 100, 100)
return win
def drawLine(x0, y0, x1, y1, win):
l = Line(Point(x0, y0), Point(x1, y1))
l.setOutline("black")
l.setWidth(2)
l.draw(win)
def main():
#input
n = int(input("Enter the step nums: "))
#draw window
win = drawWin()
#walk n steps
pos_x, pos_y = nStepWalk(n, win)
#print sim result
print("present location is ({0}, {1}).".format(pos_x, pos_y))
#click to close the window
win.getMouse()
win.close()
def nStepWalk(n, win):
loc_x, loc_y = 0, 0
for i in range(n):
next_x, next_y = OneStepWalk(loc_x, loc_y)
drawLine(loc_x, loc_y, next_x, next_y, win)#draw the line
loc_x, loc_y = next_x, next_y
return loc_x, loc_y
def OneStepWalk(loc_x, loc_y):
angle = random() * 2 * math.pi
next_x = loc_x + math.cos(angle)
next_y = loc_y + math.sin(angle)
return next_x, next_y
if __name__ == "__main__":
main()