I am trying to create a loop that will generate a series of probabilities against which a list of values can be compared. I need the probabilities to be in list form and the length of the list can vary. For example, if the list is lst = [1, 2, 3]
and I want to set the probability of calling lst[2]
at 80% with equal likelihood of the other two values, I would use p = [0.1, 0.1, 0.8]
.
I want to be able to cycle through all of the possible probabilities (with a definable step, in this case step = 0.1
). My logic has got stuck at this point:
lst = [1, 2, 3]
step = 0.1
for p in probability_gen_function(lst, step):
print(p)
loop_1 -> p = [0.1, 0.1, 0.8]
loop_2 -> p = [0.1, 0.2, 0.7]
---
loop_n -> p = [0.8, 0.1, 0.1]
I can see ways for my probability_gen_function
to generate random lists of probabilities, but not how to systematically cycle through them. Any suggestions would be appreciated.
You can use a recursive generator function:
lst = [1, 2, 3]
step = 0.1
def prob_gen(d, s, c = []):
if len(c) == len(d):
yield [round(i, 2) for i in c]
else:
r = 10-sum(int(k*10) for k in c)
for i in ([r] if len(c)+1 == len(d) else range(1, r)):
yield from prob_gen(d, s, c+[s*i])
print(list(prob_gen(lst, step)))
Output:
[[0.1, 0.1, 0.8], [0.1, 0.2, 0.7], [0.1, 0.3, 0.6], [0.1, 0.4, 0.5], [0.1, 0.5, 0.4], [0.1, 0.6, 0.3], [0.1, 0.7, 0.2], [0.1, 0.8, 0.1], [0.2, 0.1, 0.7], [0.2, 0.2, 0.6], [0.2, 0.3, 0.5], [0.2, 0.4, 0.4], [0.2, 0.5, 0.3], [0.2, 0.6, 0.2], [0.2, 0.7, 0.1], [0.3, 0.1, 0.6], [0.3, 0.2, 0.5], [0.3, 0.3, 0.4], [0.3, 0.4, 0.3], [0.3, 0.5, 0.2], [0.3, 0.6, 0.1], [0.4, 0.1, 0.5], [0.4, 0.2, 0.4], [0.4, 0.3, 0.3], [0.4, 0.4, 0.2], [0.4, 0.5, 0.1], [0.5, 0.1, 0.4], [0.5, 0.2, 0.3], [0.5, 0.3, 0.2], [0.5, 0.4, 0.1], [0.6, 0.1, 0.3], [0.6, 0.2, 0.2], [0.6, 0.3, 0.1], [0.7, 0.1, 0.2], [0.7, 0.2, 0.1], [0.8, 0.1, 0.1]]