简体   繁体   中英

Changing my code to run this program "n" times

I needed to write a program that would figure out the probability that if I roll a dice 12 times every number on the dice will appear at least once. The question was proposed that there are 6 people and we all decided to roll a die once a month for a year. Whoever has their number come up gets to pick the restaurant. What is the probability that everyone will get to pick their restaurant at least once. So I wrote a program that will roll a dice 12 times and keep track of the outcome. If every number in my random method comes out, that means that everyone got a chance to pick a restaurant (Success). If one of the numbers stays at zero in a 12 roll set, that means not everyone got to pick a restaurant (Failure). My program works great and runs when the user types "roll" and quits if the user types "Q". It keeps track of successes and divides that by number of times the program is run. I started out with a very simple die roll program that runs from a while loop, and then built all of the functionality from there. In the end, I realized that I need my program to run so 100 or 1000 times to find a good probability average. I'm not best coder as I guess you can see from my code, but I coded myself into a corner, and want to be able to run this "n" times without me spending hours trying to figure this out. I'm sure better coders on here would be able to help me very easily. Thank you in advance. Here is my code.

import random

global success
success = 0
global eachturn
eachturn = 0


def main():
    rolling = True
    while rolling:
        roll_again = input("Ready to roll? ENTER=Roll. Q=Quit. ")
        if roll_again.lower() != "q":
            global chance
            global result
            global n1
            global n2
            global n3
            global n4
            global n5
            global n6
            n1 = n2 = n3 = n4 = n5 = n6 = 0
            droll = 1
            result = 0
            for number in range(1, 13):
                result = random.randint(1, 6)
                print("Roll {0} = {1}".format(droll, result))
                droll += 1
                counter()
            print(
                "\n---- Stats: ----\nTimes number one appeared: {}\nTimes number two appeared: {}\n"
                "Times number three appeared: {}\nTimes number four appeared: {}\nTimes number five appeared: {}\n"
                "Times number six appeared: {}".format(
                    n1, n2, n3, n4, n5, n6))
            iszero()
            turncounter()
            print("This increments when all numbers 1-6 are part of the 12 roll outcome:")
            print(success)
            print("The amount of times the program is run (12 rolls of a dice):")
            print(eachturn)
            print("This is the success divided by the number of program runs:")
            print(success/eachturn)

        else:
            rolling = False

    print("Thanks for playing.")


def counter():
    global result
    global n1
    global n2
    global n3
    global n4
    global n5
    global n6
    if result == 1:
        n1 += 1
    elif result == 2:
        n2 += 1
    elif result == 3:
        n3 += 1
    elif result == 4:
        n4 += 1
    elif result == 5:
        n5 += 1
    elif result == 6:
        n6 += 1
    else:
        print("droll = {}".format(result))
        return None


def iszero():
    global zero
    global success
    zero = 0
    if n1 == 0:
        return zero
    elif n2 == 0:
        return 0
    elif n3 == 0:
        return 0
    elif n4 == 0:
        return 0
    elif n5 == 0:
        return 0
    elif n6 == 0:
        return 0
    else:
        zero += 1
        success += 1
        return zero


def turncounter():
    global eachturn
    eachturn += 1


main()

Here is an example of the output from running 1 time. However, when I type "roll" several times it increments properly to give me my (success/(number of runs))

在此处输入图片说明

Please help me figure out how to run this "n" times. I guess I need to remove my while loop maybe, or is there an easier way to pull this off without changing too much?

There's a few things here. First, to your specific question, you could just modify your loop so that instead of checking for input in main() , you just loop a fixed number of times. You might do that with something like:

def main():
    for round in range(1000):
        global chance
        global result
        global n1
        ...
        print("This is the success divided by the number of program runs:")
        print(success/eachturn)

That said, this is an absolutely massive amount of code for something that could be just a few lines:

In [51]: def run():
    ...:     return len({random.randint(1, 6) for _ in range(12)}) == 6
    ...:

In [52]: sum([run() for _ in range(10000)]) / 10000
Out[52]: 0.4287

Each call of run generates 12 random numbers from 1 to 6 and stores them in a set (which eliminates duplicates). It then checks that all 6 are present, returns True if so, and False if not. You can then just call run() 10000 times, sum up the values (since Python will treat True as 1) and then divide by the number of runs to get a probability estimate.

Even that aside, you can improve what you have by avoiding using globals instead and using data structures like list s or dict s to store values instead of individual integer values and such, but that's a separate discussion altogether.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM