I had a list with four elements and to choose one of them maximizing chances of the first elements I did this:
from random import choice
_list = [19,14,29,3]
element = choice((a[0],a[0],a[0],a[0],a[1],a[1],a[1],a[2],a[2],a[3]))
Although now the number of elements in _list
is variable, trying to preserve the same behavior of before I coded this piece:
from random import choice
_list = [19,14,29,3,.......] # n elements
weighted = []
for i in range(len(_list)):
for j in range(len(_list)-i):
weighted.append(_list[i])
element = choice(weighted)
Are there any other methods that can achieve the same result with less code and be more efficient? Because I think that if n
gets too big, then weighted
will be enormous and will slow down my algorithm.