Issue
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.
Solution
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 (but it's definitely not statistically accurate):
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]))
Answered By - amirali mollaei
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.