Random is used to generate random numbers. we can use it to randomly generate numbers or select strings. & Amp; #8226; random. seed (x) changes the seed of the random number generator. Generally, you do not need to set seed. Python automatically selects seed. & Amp; #8226; random. random () is used to generate a random floating point number n, 0 & lt; n & lt; 1 & amp; #8226; random. uniform (a, B) is used to generate a random number. we can use it to randomly generate numbers or select strings.
• Random. seed (x) changes the seed of the random number generator.
Generally, you do not need to set seed. Python automatically selects seed.
• Random. random () is used to generate a random floating point number n, 0 <= n <1
• Random. uniform (a, B) is used to generate a random floating point number within a specified range. the generated random integer a <= n <= B;
• Random. randint (a, B) is used to generate an integer in the specified range. a is the lower limit, B is the upper limit, and the generated random integer a <= n <= B; if a = B, n = a. If a> B, an error is returned.
• Random. randrange ([start], stop [, step]) obtains a random number from the set in the specified range [start, stop) that increments by the specified base number. the default base value is 1.
• Random. choice (sequence) gets a random element from the sequence. the sequence parameter indicates an ordered type, which is not a specific type. it generally refers to list, tuple, string, and so on.
• Random. shuffle (x [, random]) is used to disrupt (shuffling) elements in a list and change the original list.
• Random. sample (sequence, k) randomly obtains k elements from the specified sequence as a part to return, without changing the original sequence
Now that the basic knowledge is available, we can implement a weighted random algorithm:
Weighted random algorithms are generally used in the following scenarios: there is A set of S, such as A, B, C, and D. In this case, we want to randomly extract an item from the item, but the probability of extraction is different. for example, we want to obtain A with A probability of 50%, B and C with A probability of 20%, and D with A probability of 10%. In general, we can attach a weight to each item. the probability of extraction is proportional to this weight. Then the above set is:
{A: 5, B: 2, C: 2, D: 1}
Method 1:
The simplest method is as follows:
Extend the sequence to: lists = [A, B, B, C, C, D] based on the weight, and then random. choice (lists) can be selected randomly. Although the time complexity of this selection is O (1), a large amount of data will consume too much space.
# Coding: utf-8import randomdef weight_choice (list, weight): "": param list: sequence to be selected: param weight: weight sequence corresponding to list: return: the value "new_list = [] for I, val in enumerate (list): new_list.extend (val * weight [I]) return random. choice (new_list) if name = "main": print (weight_choice (['A', 'B', 'C', 'D'], [5, 2, 2, 1])
Method 2:
The common method is as follows:
Calculate the sum of weights, select a random number R between 1 and sum, and traverse the entire set to calculate the sum of weights of the items traversed. if the sum is greater than or equal to R, the traversal is stopped, select an item.
Take the preceding set as an example. sum is equal to 10. if the number is random to 1-5, the traversal will exit when the first number is traversed. The selected probability is met.
When selecting a set, we need to traverse it. its time complexity is O (n ).
# Coding: utf-8import randomlist = ['A', 'B', 'C', 'D'] def weight_choice (weight): "": param weight: weight sequence corresponding to list: return: Index of the selected value in the original list "" t = random. randint (0, sum (weight)-1) for I, val in enumerate (weight): t-= val if t <0: return iif name = "main ": print (list [weight_choice ([5, 2, 2, 1])
Method 3:
You can first sort the original sequence by weight. In this way, items with high probability can be quickly encountered, reducing the number of items that are traversed. (Because rnd is the fastest decreasing speed (first minus the maximum number ))
Compare {A: 5, B: 2, C: 2, D: 1} and {B: 2, C: 2, A: 5, D: 1}
The expectation of the former is 5/10*1 + 2/10*2 + 2/10*3 + 1/10*4 = 19/10 while the latter is 2/10*1 + 2/10*2 + 5/10*3 + 1/10*4 = 25/10.
This increases the average selection speed, but the sorting of the original sequence also takes time.
Create a weight value prefix and sequence, and then generate a random number t. you can use the binary method to find the prefix and sequence. then, the time complexity of the selection is O (logn).
# Coding: utf-8import randomimport bisectlist = ['A', 'B', 'C', 'D '] def weight_choice (weight): "": param weight: weight sequence corresponding to list: return: Index of the selected value in the original list "weight_sum = [] sum = 0 for a in weight: sum + = a weight_sum.append (sum) t = random. randint (0, sum-1) return bisect. bisect_right (weight_sum, t) if name = "main": print (list [weight_choice ([5, 2, 2, 1])
The above is a detailed description of python's random module, weighted random algorithms, and implementation methods. For more information, see other related articles in the first PHP community!