1

just working on a homework question where it asks to produce a dice rolling program where one or two numbers may be more likely to print than the rest. For example 2 and/or 3 might be 10% or 20% more likely to print than other elements on the dice. I got the code up to the point where I can get it to print a random number on the dice but can't figure out how to have a weighted output.

input:

  def roll_dice(n, faces = 6):
    rolls = []
    rand = random.randrange

    for x in range (n):

      rolls.append(rand(1, faces + 1 ))

    return rolls

  print (roll_dice(5))

output: [5, 11, 6, 7, 6, 5]

Nicolas Gervais
  • 33,817
  • 13
  • 115
  • 143
snk
  • 91
  • 1
  • 8
  • Does this answer your question? [Python Weighted Random](https://stackoverflow.com/questions/14992521/python-weighted-random) – G. Anderson Oct 30 '19 at 19:54

2 Answers2

1
from scipy import stats
values = np.arange(1, 7) 
prob = (0.1, 0.2, 0.3, 0.1, 0.1, 0.2) # probabilities must sum to 1
custm = stats.rv_discrete(values=(values, prob))

for i in range(10):
    print(custm.rvs())

1, 2, 3, 6, 3, 2, 3, 2, 2, 1

Source: scipy.stats.rv_discrete

Nicolas Gervais
  • 33,817
  • 13
  • 115
  • 143
0

If you are on Python 3

import random
rolls = random.choices([1,2,3,4,5,6],weights=[10,10,10,10,10,50], k=10)

rolls
out:[1, 3, 2, 5, 3, 4, 6, 6, 6, 4]
visibleman
  • 3,175
  • 1
  • 14
  • 27