Program plan:
- Import random.
- Define “main()” function.
- Call the function “printIntro()”.
- Get input using “getInputs()” function.
- Call function “simNMatches()” to find the matches.
- Call function “printSummary()”.
- Define a function “printIntro()”.
- Print the statements.
- Define a function “getInputs()”.
- Get the value for simulation parameter “a” from the user.
- Get the value for simulation parameter “b” from the user.
- Get the value for simulation parameter “n” from the user.
- Returns the three simulation parameters.
- Define a function “simNMatches()”.
- Initialize values.
- Iterate a for loop up to “n”.
- Call the function “simOneMatch()”.
- If condition.
- Increment the value of “matchA” by 1.
- Else.
- Increment the value of “matchB” by 1.
- Return the value of “matchA” and “matchB”.
- Define a function “simOneMatch()”.
- Initialize the values “wisnA” and “WinsB” as 0.
- Accumulate number of games.
- Iterate a while loop.
- Call a function “simOneGame()”.
- If condition.
- Increment the value of “winA” by 1.
- Increment the value of “x” by 1.
- Else condition.
- Increment the value of “winsB” by 1.
- Increment the value of “x” by 1.
- Return the value of “winsA” and “winsB”.
- Define a function “simOneGame()”.
- Call a function “findService()” to a value “serving”.
- Initialize values.
- Iterate a while loop.
- If condition “serving == "A"”.
- If condition “random() < probA”.
-
- Increment the value of “scoreA” by 1.
- If not the condition.
-
- Assign a value “B” to a variable “serving”.
- Else if condition.
-
- If condition “random() < probB” increment the value of “scoreB” by 1.
- Increment the value of “scoreB” by 1.
- If not the condition.
-
- assign a value “A” to a variable “serving”
- Return “scoreA”, “scoreB”..
- assign a value “A” to a variable “serving”
- If condition “serving == "A"”.
- Define a function “findService()”.
- If condition “x % 2 == 0”.
- Return “A”.
-
-
- If not the condition.
- Return “B”.
- If not the condition.
-
-
- Return “A”.
- If condition “x % 2 == 0”.
- Define a function “gameOver()”.
- If the condition satisfies.
- Return the value of “b”.
-
-
-
- Else if condition “b == 0 and a == 7”.
- Return the value of “a”.
- Else if condition “abs(a-b) >= 2”.
- Return “True”.
- If not the condition
- Return a value “False”.
- Else if condition “b == 0 and a == 7”.
-
-
-
- Return the value of “b”.
- If the condition satisfies.
- Define a function “printSummary()”.
- Add the value of “matchA” and “matchB” and store in a variable “n”.
- Print the value of “n”.
- Print the value of “matchA”.
- Print the value of “matchB”.
- main for function call
This is a revision of the racquetball simulation. The problem has two major changes:
The program has to calculate results for best of n games.
First service is alternated between A and B. The odd numbered games of the match are served first by A and even numbered games are first served by B.
Explanation of Solution
Program:
#import random
from random import random
#define main() function
def main():
#call the function printIntro()
printIntro()
#get input using getInputs() function
probA, probB, n = getInputs()
#calling function simNMatches() to find the matches
matchA, matchB = simNMatches(n, probA, probB)
#call function printSummary()
printSummary(matchA, matchB)
#define a function printIntro()
def printIntro():
print("This program simulates a game of racquetball between two")
print('players called "A" and "B". The abilities of each player is')
print("indicated by a probability (a number between 0 and 1) that")
print("reflects the likelihood of a player winning the serve.")
print("Player A has the first serve.")
#define a function getInputs()
def getInputs():
#get the value for simulation parameter ‘a’ from the user
a = eval(input("What is the prob. player A wins a serve? "))
#get the value for simulation parameter ‘b’ from the user
b = eval(input("What is the prob. player B wins a serve? "))
#get the value for simulation parameter ‘n’ from the user
n = eval(input("How many games to simulate? "))
#Returns the three simulation parameters
return a, b, n
#define a function simNMatches()
def simNMatches(n, probA, probB):
#initialize values
matchA = matchB = 0
#iterate a for loop up to n
for i in range(n):
#call the function simOneMatch()
winsA, winsB = simOneMatch(probA, probB)
#if condition
if winsA > winsB:
#increment the value of matchA by 1
matchA = matchA + 1
#else
else:
#increment the value of matchB by 1
matchB = matchB + 1
#return the value of matchA and matchB
return matchA, matchB
#define a function simOneMatch()
def simOneMatch(probA, probB):
#initialize the values wisnA and WinsB as 0
winsA = winsB = 0
#accumulate number of games
x = 1
#iterate a while loop
while winsA !=2 and winsB !=2:
#calling a function simOneGame()
scoreA, scoreB = simOneGame(probA, probB, x)
#if condition
if scoreA > scoreB:
#increment the value of winA by 1
winsA = winsA + 1
#increment the value of x by 1
x = x+1
#else condition
else:
#increment the value of winsB by 1
winsB = winsB + 1
#increment the value of x by 1.
x = x+1
#return the value of winsA and winsB
return winsA, winsB
#define a function simOneGame()
def simOneGame(probA, probB, x):
#call a function findService() to a value “serving”
serving = findService(x)
#initialize values
scoreA = 0
scoreB = 0
#iterate a while loop.
while not gameOver(scoreA, scoreB):
#if condition
if serving == "A":
#if condition
if random() < probA:
#increment the value of scoreA by 1
scoreA = scoreA + 1
#if not the condition
else:
#assign a value “B” to a variable “serving”
serving = "B"
#else if condition
elif serving == "B":
#if condition
if random() < probB:
#increment the value of scoreB by 1
scoreB = scoreB + 1
#if not the condition
else:
#assign a value “A” to a variable “serving”
serving = "A"
#return
return scoreA, scoreB
#define a function findService()
def findService(x):
#if condition
if x % 2 == 0:
#return “A”
return "A"
#if not the condition
else:
#return “B”
return "B"
#define a function gameOver()
def gameOver(a, b):
#if the condition satisfies
if a == 0 and b == 7:
#return the value of “b”
return b == 7
#else if condition
elif b == 0 and a == 7:
#return the value of a
return a == 7
#else if condition
elif abs(a-b) >= 2:
#return “True”
return True
#if not the condition
else:
#return a value “False”
return False
#define a function printSummary()
# Prints a summary of wins for each players
def printSummary(matchA, matchB):
#add the value of matchA and matchB and store in a variable n.
n = matchA + matchB
#print the value of n
print("\nGames simulated: ", n)
#print the value of matchA
print("Wins for A: {0} ({1:0.1%})".format(matchA, matchA/n))
#print the value of matchB
print("Wins for B: {0} ({1:0.1%})".format(matchB, matchB/n))
# main for function call
if __name__ == '__main__': main()
Output:
This program simulates a game of racquetball between two
players called "A" and "B". The abilities of each player is
indicated by a probability (a number between 0 and 1) that
reflects the likelihood of a player winning the serve.
Player A has the first serve.
What is the prob. player A wins a serve? 0.5
What is the prob. player B wins a serve? 0.7
How many games to simulate? 2
Games simulated: 2
Wins for A: 1 (50.0%)
Wins for B: 1 (50.0%)
Want to see more full solutions like this?
Chapter 9 Solutions
Python Programming: An Introduction to Computer Science, 3rd Ed.
- A wrestling tournament has 256 players. Each match includes 2 players. The winner each match will play another winner in the next round. The tournament is single elimination, so no one will wrestle after they lose. The 2 players that are undefeated play in the final game, and the winner of this match wins the entire tournament. How would you determine the winner? Here is one algorithm to answer this question. Compute 256/2 = 128 to get the number of pairs (matches) in the first round, which results in 128 winners to go on to the second round. Compute 128/2 = 64, which results in 64 matches in the second round and 64 winners, to go on to the third round. For the third round compute 64/2 = 32, so the third round has 64 matches, and so on. The total number of matches is 128 + 64 + 32+ .... Finish this process to find the total number of matches.arrow_forwardIn a Chess match "a + b", each player has a clock which shows a minutes at the start and whenever a player makes a move, b seconds are added to this player's clock. Time on a player's clock decreases during that player's turns and remains unchanged during the other player's turns. If the time on some player's clock hits zero (but not only in this case), this player loses the game. N+1 There's a 3 + 2 blitz chess match. After N turns (i.e. moves made by 2 N white and moves made by black), the game ends and the clocks of the two 2 players stop; they show that the players (white and black) have A and B seconds left respectively. Note that after the N-th turn, b = 2 seconds are still added to the clock of the player that made the last move and then the game ends. Find the total duration of the game, i.e. the number of seconds that have elapsed from the start of the game until the end.arrow_forwardCorrect answer will upvoted else downvoted Petya found out with regards to another game "Kill the Dragon". As the name recommends, the player should battle with mythical beasts. To overcome a mythical serpent, you need to kill it and shield your palace. To do this, the player has a crew of n legends, the strength of the I-th saint is equivalent to man-made intelligence. As per the principles of the game, precisely one saint should go kill the mythical serpent, all the others will shield the palace. On the off chance that the mythical serpent's protection is equivalent to x, you need to send a saint with a strength of essentially x to kill it. Assuming the winged serpent's assault power is y, the absolute strength of the saints protecting the palace ought to be ssentially y. The player can build the strength of any legend by 1 for one gold coin. This activity should be possible quite a few times. There are m winged serpents in the game, the I-th of them has protection equivalent to…arrow_forward
- There is an upcoming football tournament, and the n participating teams are labelled from 1 to n. Each pair of teams will play against each other exactly once. Thus, a total of n(n−1) /2 matches will be held, and each team will compete in n − 1 of these matches.arrow_forwardCorrect answer will be upvoted else downvoted. Computer science. You and your companions live in n houses. Each house is situated on a 2D plane, in a point with integer organizes. There may be various houses situated in a similar point. The chairman of the city is requesting you for places for the structure from the Eastern show. You need to track down the number of spots (focuses with integer arranges), so the outline distance from every one of the houses to the show is insignificant. The display can be inherent a similar point as some house. The distance between two focuses (x1,y1) and (x2,y2) is |x1−x2|+|y1−y2|, where |x| is the outright worth of x. Input First line contains a solitary integer t (1≤t≤1000) — the number of experiments. The principal line of each experiment contains a solitary integer n (1≤n≤1000). Next n lines portray the places of the houses (xi,yi) (0≤xi,yi≤109). It's reliable that the amount of everything n doesn't surpass 1000. Output For…arrow_forwardThis is for a modeling and simulation class. It requires statistics.arrow_forward
- Q1. Let’s play a dice game with a pair of dice following these rules:1. At the beginning, you throw a pair of dice. If the two numbers add up to 5, 6, 7, 8, or 9, thegame immediately stops.2. If your first throw does not meet those 5 totals, you would continue until you get either 11 or12.Get 1000 simulations of this paired dice game. What is the average number of dice throw per game?You can use the sample() function to simulate the dice.arrow_forwardThere are m towns in a straight line, with a road joining each pair of consecutive towns. Legends say that an ordinary person in one of these towns will become a hero by completing a sequence of n quests. The first quest will be completed in their home town, but after each quest they may complete their next quest either in the same town or after moving to a neighbouring town.For example, if n = 5 and m = 4, a resident of town 2 may become a hero as follows:• begin in town 2 for quest 1,• then move to town 3 for quest 2,• stay in town 3 for quest 3,• return to town 2 for quest 4, and• move to town 1 for quest 5.Design an algorithm which runs in O(nm) time and finds the total number of waysto complete n quests.arrow_forwardAdam begins to master programming. The main undertaking is drawing a fox! Notwithstanding, that ends up being excessively hard for a novice, so she chooses to draw a snake all things being equal. A snake is an example on a n by m table. Mean c-th cell of r-th column as (r, c). The tail of the snake is situated at (1, 1), then, at that point, it's body reaches out to (1, m), then, at that point, goes down 2 lines to (3, m), then, at that point, goes left to (3, 1, etc. Your undertaking is to draw this snake for Adam: the unfilled cells ought to be addressed as speck characters ('.') and the snake cells ought to be loaded up with number signs ('#'). Consider test tests to comprehend the snake design for the programming concepts.arrow_forward
- write a recursive method to schedule compatible activities that result in the maximum usage of the room.arrow_forwardImplement a java project to help in the study analysis with the following steps:• Read from the user the number of cities (minimum 6 cities.)• For each city: city name and the number of persons (minimum 10 persons) are entered.• For each person in a city: mass and height should be entered, BMI and BMI category have to becomputed and printed.• For each city, the number of persons and percent ratio in each BMI category should be computedand printedarrow_forwardPython answer only. Correct answer will upvoted else downvoted. It is the ideal opportunity for your very first race in the game against Ronnie. To make the race intriguing, you have wagered a dollars and Ronnie has wagered b dollars. Yet, the fans appear to be frustrated. The fervor of the fans is given by gcd(a,b), where gcd(x,y) means the best normal divisor (GCD) of integers x and y. To make the race seriously invigorating, you can perform two kinds of activities: Increment both an and b by 1. Diminishing both an and b by 1. This activity must be performed if both an and b are more noteworthy than 0. In one action, you can play out any of these activities. You can perform self-assertive (potentially zero) number of moves. Decide the greatest energy the fans can get and the base number of moves needed to accomplish it. Note that gcd(x,0)=x for any x≥0. Input The principal line of input contains a solitary integer t (1≤t≤5⋅103) — the number of experiments.…arrow_forward
- Database System ConceptsComputer ScienceISBN:9780078022159Author:Abraham Silberschatz Professor, Henry F. Korth, S. SudarshanPublisher:McGraw-Hill EducationStarting Out with Python (4th Edition)Computer ScienceISBN:9780134444321Author:Tony GaddisPublisher:PEARSONDigital Fundamentals (11th Edition)Computer ScienceISBN:9780132737968Author:Thomas L. FloydPublisher:PEARSON
- C How to Program (8th Edition)Computer ScienceISBN:9780133976892Author:Paul J. Deitel, Harvey DeitelPublisher:PEARSONDatabase Systems: Design, Implementation, & Manag...Computer ScienceISBN:9781337627900Author:Carlos Coronel, Steven MorrisPublisher:Cengage LearningProgrammable Logic ControllersComputer ScienceISBN:9780073373843Author:Frank D. PetruzellaPublisher:McGraw-Hill Education