Python Forum
NEED HELP Pseudo-Random Numbers
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
NEED HELP Pseudo-Random Numbers
#1
Hey everyone. I've been coding for about a month now. Trying to figure out the assignment I got this week. THe assignment asked me to find if there were any shutouts in a simulation of games and report them. I defined shutout() and Summary(). I feel I am headed in the right direction. I just need a few more pointers.

from random import random

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

def printIntro():
    print("THis program simulates a game of racquetball between two")
    print('players called "A" and "B". The ability of each player is')
    print("the player wins the point when serving. Player A alwyas")
    print("has the first serve.")

def getInputs():
    #Returns the 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 players whose
    #   abilities are represented by the probability of winning a serve.
    #Returns number of wins for A and B
    winsA = winsB = 0
    for i in range(n):
        scoreA, scoreB = simOneGame(probA, probB)
        if scoreA > scoreB:
            winsA = winsA + 1
        else:
            winsB = winsB + 1
    return winsA, winsB

def simOneGame(probA, probB):
    #Simulates a single game of racquetball between players whose
    # abilities are represented by theprobability of winning a serve.
    #Returns final scores for A and B
    serving = "A"
    scoreA = 0
    scoreB = 0
    shutoutsA = 0
    shutoutsB = 0
    while not gameOver(scoreA,scoreB):
        if serving == "A":
            if random() < probA:
                scoreA = scoreA + 1
            else:
                serving = "B"
                
        else:
            if random() < probB:
                scoreB = scoreB + 1
            else:
                serving = "A"
        
    return scoreA, scoreB

def shutout(scoreA, scoreB):
    shutoutsA = 0
    shutoutsB = 0
    while simNGames(probA, probB):
        if scoreA == 0:
            shutoutsB = shutoutsB + 1
        if scoreB == 0:
            shutoutsA = shutoutsA + 1
    return shutoutsA, shutoutsB
    

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 player.
    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))
    
def Summary (shutoutsA, shutoutsB):
    print(shutoutsA)
    print(shutoutsB)


if __name__== '__main__': main()
Reply
#2
What problems are you having?
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
It either wont print at all or says 'shutoutsA' or 'shutoutsB' is not defined. It all depends where I go to try and print the 'shutouts'.

This is what I get:
Error:
"Traceback (most recent call last): File "C:/Users/kongurinn/Downloads/CS 1400/Exercise #9/rqtballPractice.py", line 87, in <module> if __name__== '__main__': main() File "C:/Users/Kongurinn/Downloads/CS 1400/Exercise #9/rqtballPractice.py", line 8, in main Summary(shutoutsA, shutoutsB) NameError: name 'shutoutsA' is not defined"
Reply
#4
That's because you haven't defined them in the right scope. Variables defined in one function are not visible in other functions, at least not in Python. You have to explicitly pass them using parameters and return statements. The variables shutoutsA and shutoutsB seem to only get defined in simOneGame. But simOneGame does not return them, so not other function has access to those definitions.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#5
I thought I passed the variables on when I coded these lines:

def shutout(scoreA, scoreB):
    shutoutsA = 0
    shutoutsB = 0
    while simNGames(probA, probB):
        if scoreA == 0:
            shutoutsB = shutoutsB + 1
        if scoreB == 0:
            shutoutsA = shutoutsA + 1
    return shutoutsA, shutoutsB
Shouldn't I be able to use the shutoutsA and shutoutsB variables?
How would you do it?
Reply
#6
Yes, that would work, but I don't see where you call the shutout function in your code.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#7
when you do a return from a function, it returns the value, not the names under which that function stored the values.  when you return 2 values separated by a comma, you are returning a value which is a type known as a tuple, containing those 2 values.  you do need to call the function and do it in a way that properly uses the value the function will return, such as assigning that value to a variable, or to multiple variables.  you can also call a function and ignore the value it returns.

if you wish to have variables returned from a function, and have the code that called that function get the same names, it is possible to do.  but it is more complicated, requiring changes to how the function returns them and how the caller accepts them.  but, i suggest not ever thinking about something like that unless you have a specific reason to do it.  in my few years of programming in python, i have never encountered such a need.  i doubt if anyone here ever has, so i'm not going to explain how.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#8
Can someone give me a short example of how to do this properly?

That's, honestly, how I learn best.
Reply
#9
def function1(fielda, fieldb):
    print('fielda: {}, fieldb: {}'.format(fielda, fieldb)

def function2():
    field1 = 5
    field2 = 3
    function1(field1, field2)

if __name__ == '__main__':
    function2()
result:
Output:
fielda: 5, fieldb: 3
The field names don't have to be the same between functions (but they can be as well)
Reply
#10
i agree.  examples of minimal code, doing what is to be learned, and as little else as possible, while still making a reasonable example, is a good way to learn, for many people, including myself.  one other thing that usually helps is that the example be complete in the usability sense.  if it is a function or class or being given in that form, it should still be complete.  it should be possible to copy the code the a file, maybe named as specified and used in that form.  if it is a command, then it should be able to run as a command.  example code that genuinely needs to import a module that does not come built-in to python should be indicated with how a regular user can install it.  it is best to avoid the need to install anything for an example unless the example is illustrating how to use what is to be installed.

i love to get examples.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Random Generator: From Word to Numbers, from Numbers to n possibles Words Yamiyozx 2 1,369 Jan-02-2023, 05:08 PM
Last Post: deanhystad
  Convert list of numbers to string of numbers kam_uk 5 2,935 Nov-21-2020, 03:10 PM
Last Post: deanhystad
  Stein's GCD according to given pseudo code wanttolearn 2 1,920 Aug-27-2020, 07:58 PM
Last Post: wanttolearn
  Scaling random numbers within specific range schniefen 4 3,135 Oct-28-2019, 11:22 AM
Last Post: jefsummers
  How to Generate and Print An Array with Random Numbers in Python in the johnnynitro99293 14 9,451 Sep-20-2019, 11:56 AM
Last Post: ichabod801
  Write pseudo code for a class assignment Scrimshot 3 3,329 May-07-2019, 05:38 PM
Last Post: Scrimshot
  random numbers and stats cliffhop23 2 6,853 Feb-22-2018, 09:16 PM
Last Post: glidecode
  Regular Expressions in Files (find all phone numbers and credit card numbers) Amirsalar 2 4,054 Dec-05-2017, 09:48 AM
Last Post: DeaD_EyE
  List with Random Numbers AnjyilLee 5 9,259 Oct-14-2017, 09:22 PM
Last Post: buran
  pseudo code for a quiz tsaward 4 7,630 Sep-15-2017, 09:59 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020