Python dice rolling simulation

前端 未结 4 1944
借酒劲吻你
借酒劲吻你 2021-01-16 08:58

I\'m having trouble with a code where I need to roll a six-sided die 1000 times and then return a list of how many times each number on the die was rolled.

The code

相关标签:
4条回答
  • 2021-01-16 09:02

    You should do random.randint(1, 7), otherwise you will never get a 6.

    ...
    roll = random.randint(1, 7)
    
    0 讨论(0)
  • 2021-01-16 09:02
    import random
    
    def dice():
    
        print random.randint(1,6)
    
    dice()
    
    0 讨论(0)
  • 2021-01-16 09:13

    You have a small typo; you are testing for equality, not assigning:

    four == four+1
    

    should be:

    four = four+1
    

    However, you already have a number between 1 and 6, why not make that into an index into the results list? That way you don't have to use so many if statements. Keep your data out of your variable names:

    def rollDie(number):
        counts = [0] * 6
        for i in range(number):
            roll = random.randint(1,6)
            counts[roll - 1] += 1
        return counts
    
    0 讨论(0)
  • 2021-01-16 09:22

    I can't improve on Martijn Pieters's answer. :-) But this problem can be more conveniently solved using a list.

    import random
    
    def rollDie(number):
        # create a list with 7 values; we will only use the top six
        rolls = [0, 0, 0, 0, 0, 0, 0]
        for i in range(0, number):
            roll=int(random.randint(1,6))
            rolls[roll] += 1
        return rolls
    
    if __name__ == "__main__":
        result = rollDie(1000)
        print(result[1:])  # print only the indices from 1 to 6
    

    And, this is a little bit tricky, but here is a better way to create a list of 7 entries all set to zero:

    rolls = [0] * 7
    

    Why count the zeros yourself? It's easier to just make Python do the work for you. :-)

    EDIT: The list is length 7 because we want to use indices 1 through 6. There is also a position 0 in the list, but we don't use it.

    Another way to do it is to map the dice rolls onto indices. It's a pretty simple mapping: just subtract 1. So, a die roll of 1 would go into index 0 of the list, a die roll of 2 would go into index 1, and so on. Now we will use every position in the list.

    Here's that version:

    import random
    
    def rollDie(number):
        rolls = [0] * 6
        for i in range(0, number):
            roll=int(random.randint(1,6))
            rolls[roll - 1] += 1
        return rolls
    
    if __name__ == "__main__":
        result = rollDie(1000)
        print(result)
    
    0 讨论(0)
提交回复
热议问题