Python dice rolling simulation

前端 未结 4 2054
借酒劲吻你
借酒劲吻你 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: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)
    

提交回复
热议问题