Search code examples
pythonhistogramdice

Python - Rolling two dice with different numbers of sides


I've already written the code for a program that takes the number of sides from the user and rolls two of those dice 1000 times and shows the sums on a histogram.

How do I do the same thing but the user can choose different dice, for example a 6 sided and an 8 sided one?

This is my code for the similar dice:

from random import randint
import matplotlib.pyplot as plt
from collections import defaultdict

#Asking for the sides
n = int(input("How many sides? 6, 8 or 10?\n"))
number = 1000 #How many times it's rolled

#Making empty dictionaries for each type of die
sums6 = defaultdict(int)
sums8 = defaultdict(int)
sums10 = defaultdict(int)

#Making conditions for each type and plotting the histograms
if n == 6:
    for _ in range(number):
        die1 = randint(1,6)
        die2 = randint(1,6)
        sums6[die1 + die2] += 1
    plt.bar(list(sums6.keys()), sums6.values(), color='b')
    plt.xlabel('Result')
    plt.ylabel('Frequency of Result')
    plt.grid(axis='y', alpha=0.5)
    plt.show()
if n == 8:
    for _ in range(number):
        die1 = randint(1,8)
        die2 = randint(1,8)
        sums8[die1 + die2] += 1
    plt.bar(list(sums8.keys()), sums8.values(), color='g')
    plt.xlabel('Result')
    plt.ylabel('Frequency of Result')
    plt.grid(axis='y', alpha=0.5)
    plt.show()
if n == 10:
    for _ in range(number):
        die1 = randint(1,10)
        die2 = randint(1,10)
        sums10[die1 + die2] += 1
    plt.bar(list(sums10.keys()), sums10.values(), color='r')
    plt.xlabel('Result')
    plt.ylabel('Frequency of Result')
    plt.grid(axis='y', alpha=0.5)
    plt.show()

Solution

  • If you only want user to be able to input multiple sides in a dice you could just take 2 variables as input and generate random numbers from them, also no need to add conditions, you can just specify the selected number of sides in dice in the randint itself

    from random import randint
    import matplotlib.pyplot as plt
    from collections import defaultdict
    
    #Asking for the sides
    n = int(input("How many sides Dice1? 6, 8 or 10?\n"))
    m = int(input("How many sides Dice2? 6, 8 or 10?\n"))
    number = 1000 #How many times it's rolled
    
    #Making empty dictionaries for each type of die
    sums = defaultdict(int)
    
    #Making conditions for each type and plotting the histograms
    
    for _ in range(number):
        die1 = randint(1,n)
        die2 = randint(1,m)
        sums[die1 + die2] += 1
    plt.bar(list(sums.keys()), sums.values(), color='b')
    plt.xlabel('Result')
    plt.ylabel('Frequency of Result')
    plt.grid(axis='y', alpha=0.5)
    plt.show()