0

I attempted

import random
from statistics import mode

numlist = []
for i in range(6):
    numlist.append(random.randint(1, 4))
for i in range(3):
    numlist.append(random.randint(1, 3))
for i in range(1):
    numlist.append(random.randint(1, 2))

print(mode(numlist))

Which I attempted to give 1 number 70% of the time, another number 20% of the time, and another number 10% of the time. However, working out the math, the split ends of being 50%, 30%, 20%

SantoshGupta7
  • 5,607
  • 14
  • 58
  • 116

3 Answers3

4

You are reinventing the choise with probabilities field p

x = np.random.choice([2,3,4], 1, p=[0.2, 0.1, 0.7])
random.randint(1, x)
user8426627
  • 903
  • 1
  • 9
  • 19
  • 2
    No need to involve numpy in this. `lambda: random.choices([2, 3, 4], [0.2, 0.1, 0.7])` – mypetlion Jul 19 '19 at 23:49
  • contrary to the docs of numpy, `random.choices` accepts an array of weights, of which the probabilities are the (approximate) normalization to a unit sum. So `random.choices([2, 3, 4], [2, 1, 7])` would be equivalent. – Walter Tross Jul 19 '19 at 23:53
1

When you use range(6) it returns 0,1,2,3,4,5. Your code returns a 60-30-10 list.

import random
from statistics import mode

numlist = []
for i in range(7):
    numlist.append(random.randint(1, 4))
for i in range(2):
    numlist.append(random.randint(1, 3))
for i in range(1):
    numlist.append(random.randint(1, 2))

Here it is wrapped in an function that lets you determine how many decades to include in your output.

import random

# stt for seven-twenty-ten
def stt_split(n=1):
    # returns lists with lengths that are multiples of ten
    numlist = []
    for decades in range(n):
        for i in range(7):
            numlist.append(random.randint(1, 4))
        for i in range(2):
            numlist.append(random.randint(1, 3))
        for i in range(1):
            numlist.append(random.randint(1, 2))
    return numlist

alice = stt_split()
print(alice) # 10 values in a list

bob = stt_split(4)
print(bob) # 40 values in a list

On the other hand, if you don't want a list with a set distribution returned, but you want the function to return a value calculated by a randomly selected function, you could try something like this.

import random

# stt for seven-twenty-ten
def stt_dice(n=1):
    # returns lists of random ints with length n
    numlist = []
    for decades in range(n):
        x = random.choices([2, 3, 4], [2, 1, 7])[0]    
        numlist.append(random.randint(1, x))
    return numlist

alice = stt_dice()
print(alice) # 1 value in a list

bob = stt_dice(10)
print(bob) # 10 values in a list
0
i = random.random(0, 9)
if i <= 1:
    <10% of the time>
elif i <= 3:
    <20% of the time>
else:
    <70% of the time>
miara
  • 847
  • 1
  • 6
  • 12