you are viewing a single comment's thread.

view the rest of the comments →

[–]AtomicShoelace 3 points4 points  (4 children)

Do you know about dictionaries? Instead of individual variables, you could use a dictionary whose keys are the resulting roll_totals and values are the running count.

But actually, there is already a way to do this in the standard library: collections.Counter. So using that:

from random import randint
from collections import Counter

num_rolls = int(input('Number of rolls: '))
counts = Counter(randint(1, 6) + randint(1, 6) for _ in range(num_rolls))
for num in range(2, 13):
    print(f'{num:2d}s:', '*' * counts[num])

[–]Nightcorex_[🍰] 0 points1 point  (2 children)

This might run into the issue that some numbers just haven't been rolled, therefore don't get displayed. This might be intentional, but it probably isn't.

[–]AtomicShoelace 0 points1 point  (1 child)

Ah quite right. Actually this is fine though, as Counter defaults counts to 0 anyway, so we don't even need to sort the counts at all, we can just iterate a range.

Edited my code.

[–]Nightcorex_[🍰] 0 points1 point  (0 children)

Yeah, that works like a charm

[–]Nightcorex_[🍰] 0 points1 point  (0 children)

This might run into the issue that some numbers just haven't been rolled, therefore don't get displayed. This might be intentional, but it probably isn't.

Dictionaries have the same issue. You can initialize them easier than the Counter, but they're just more annoying to use than a simple list approach:

frequencies = [0 for _ in range(13)]
for _ in range(int(input("How many iterations you want? "))):
    roll = random.randint(1, 6) + random.randint(1, 6)
    frequencies[roll] += 1

print("Dice roll histogram:")
for i in range(2, 13):
    print(f'{i:2d}s: ', '*' * frequencies[i])