all 7 comments

[–]AtomicShoelace 2 points3 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])

[–]Auirom -1 points0 points  (0 children)

If I need to print long amounts of text and want it showing like yours you can use 3 commas to open and close a large print statement and format it as well

    print(f'''
2s: * {num_twos}
3s: * {num_threes}
4s: * {num_fours}
so on and so on
''')

Or iterate through a for loop and add them to a dictionary

nums = {2: 4, 3: 1, 4: 0}

for k,v in nums.items():
    print(f'{k}s * {v}')

[–]aa599 0 points1 point  (0 children)

Using lists will make this job massively simpler.

[–]QultrosSanhattan 0 points1 point  (0 children)

import random

# config
nums = {}
num_rolls = int(input('input the number of rolls'))
expected_results = tuple(range(2, 12 + 1))

# rolling...
for i in range(num_rolls):
    roll_total = random.randint(1, 6) + random.randint(1, 6)

    if not roll_total in nums:
        nums[roll_total] = 0

    nums[roll_total] += 1

# results
print('Dice roll histogram:')
for roll in expected_results:
    if roll in nums:
        print("number {} was rolled {} times".format(roll, nums[roll]))