1

I'm trying to get my code below working to have the results organized rather than random.

This is what's happening now.

sum = 9 count = 117
sum = 6 count = 142
sum = 3 count = 58
sum = 7 count = 172
sum = 8 count = 129
sum = 5 count = 109
sum = 4 count = 87
sum = 11 count = 53
sum = 12 count = 31
sum = 10 count = 72

And what I'm trying to achieve is

    sum = 1 count = 117
    sum = 2 count = 142
    sum = 3 count = 58
    sum = 4 count = 172
    sum = 5 count = 129
    sum = 6 count = 109
    sum = 7 count = 87
    sum = 8 count = 53
    sum = 12 count = 31

etc. While omitting any number that hasn't been rolled. I'd ideally like to use a list instead of a dictionary but any time I try it I get varying errors. Currently this outputs the amount but not in order.

    import random
    
    print("results")
    occurrences = []
    for i in range(1000):
        die1 = random.randint(1, 6)
        die2 = random.randint(1, 6)
        roll = die1 + die2
        current = occurrences[roll, ]
        occurrences[roll] = current + 1
    
    for roll, count in occurrences[]
        print(f"sum = {roll} count = {count}")
Drophead
  • 19
  • 1
  • 7

1 Answers1

0

A recipe for dictionary-based roll occurrence counting would be:

  1. First initialize all roll possibilities within a dictionary (the example below makes use of dictionary comprehension) where the dict keys are the roll value and the dict values are the corresponding occurence.

  2. Count each time a roll happens with the +=1 statement (in-place add up 1).

  3. Sort the dictionary with another dictionary comprehension operated on the sorted dictionary values (here, the occurrence of each roll).

  4. Loop over the dictionary keys (rolls) and corresponding values (occurrences) in order to show the output.

Here is your code with the above statements included:

import random

print("results")
occurrences = {k: 0 for k in range(2, 13)}

for i in range(10000):
    die1 = random.randint(1, 6)
    die2 = random.randint(1, 6)
    roll = die1 + die2
    occurrences[roll] += 1

occurrences = {k: v for k, v in sorted(occurrences.items(), key=lambda item: item[1], reverse=True)}

for roll, count in occurrences.items():
    print(f"sum = {roll} count = {count}")

which outputs the following result with 10,000 rolls:

sum = 7 count = 1653
sum = 6 count = 1398
sum = 8 count = 1325
sum = 5 count = 1162
sum = 9 count = 1142
sum = 10 count = 842
sum = 4 count = 812
sum = 11 count = 578
sum = 3 count = 540
sum = 2 count = 295
sum = 12 count = 253
Leonard
  • 2,510
  • 18
  • 37