0

How could I randomize a list or array of numbers with different percentages? For example:

    import random
random = random.randint(1, 3)

if random == 1:
  print('1')
elif random == 2:
  print('2')
elif random == 3:
  print('3')


#1 = blank%percent chance of happening
#2…
#3…

To clarify, is there a way for there to be a certain percent chance for the 1 (or any other number) to print? Like 1 has a 4% chance of happening, 2 has a 93% chance of happening, and 3 has a 3% chance of happening. Just a question that popped up.

1 Answers1

0

you can use np.random.choice

import numpy as np
print(np.random.choice([1, 2, 3], p=[0.04, 0.93, 0.03]))

Edit: if you don't want to use numpy you can also use random.choises

import random
print(random.choices([1, 2, 3], [0.04, 0.93, 0.03])[0])

Edit 2: after some testing i think i got this function working fine for python < 3.10.x:

def random_choise(choises, weights):
    assert len(choises) == len(weights), "the length of choises should be equel to the length of weights!"
    assert sum(weights) == 1.0, "the sum of weights should be equel to 1.0!"
    choises_ = []
    while len(choises_) == 0:
        rands = [random.random()*10 for _ in range(len(choises))]
        choises_ = [c for r, w, c in zip(rands, weights, choises) if w > r]
    return choises_[random.randint(0, len(choises_)-1)]

print(random_choise([1, 2, 3], [0.04, 0.93, 0.03]))
  • The code editor I am using does not support numpy, is there any other way to do this? –  Oct 26 '22 at 17:27
  • @Mouse you can install numpy using `pip install numpy` – amirali mollaei Oct 26 '22 at 17:34
  • I don’t want to install anything because I don’t have any expertise (I also just don’t have to resources). Besides using numpy (I’ll keep in mind this strategy for later things), is there any other way? –  Oct 26 '22 at 17:36
  • @Mouse you can also use `random.choises` – amirali mollaei Oct 26 '22 at 17:39
  • AttributeError: module 'random' has no attribute 'choices' on line 2 –  Oct 26 '22 at 17:42
  • Perhaps its just the editor, I will probably try a different one later. –  Oct 26 '22 at 17:42
  • @Mouse sorry now that i looked, random.choices added in python 3.10+, you should implement a function for that, or you can update your python – amirali mollaei Oct 26 '22 at 17:46