We need to write a program for randomly generating equipment. The quality of the equipment is classified into four equal parts. The probability is different and the probability is equal to 1. This isObtain elements with the specified probability. Python does not directly implement this function.
Find a solution. First, random a floating point number ranging from 0 to 1, and then calculate the increasing cumulative probability of repeating elements and their probabilities until the probability value is greater than the pseudo-random number, the corresponding element is the selected element.
Another similar task is to randomly retrieve weights defined by a sequence of non-negative integers-Based on opportunity rather than probability. There is a generator solution to implement this problem. The generator first prepares a table. The number of its elements is sum (relative_odds). Each element in the sequence can appear in the table multiple times, the number of occurrences is equal to the non-negative integer corresponding to the relative_odds sequence. Once the table is created, the generator body can become small and fast, because it only needs to delegate the random retrieval work to random. choice.
The code and test of both are as follows:
1 import random 2 3 def random_pick1(some_list, probabilities): 4 x = random.uniform(0, 1) 5 sum_probability = 0.0 6 for item, item_probability in zip(some_list, probabilities): 7 sum_probability += item_probability 8 if x < sum_probability: 9 break 10 return item 11 12 def random_pick2(sequence, relative_odds): 13 table = [ z for x, y in zip(sequence, relative_odds) for z in [x]*y ] 14 while True: 15 yield random.choice(table) 16 17 l1 = ['green', 'blue', 'purple', 'yellow']18 l2 = [0.7, 0.1, 0.05, 0.15]19 for i in xrange(10):20 print random_pick1(l1, l2)21 22 print '=' * 2023 24 l3 = [100, 10, 5, 15]25 gene = random_pick2(l1, l3)26 for res in zip('1234567890', gene):27 print res
A possible output is as follows: