Python's random module and python implementation method of weighted random algorithm, randompython

Source: Internet
Author: User

Python's random module and python implementation method of weighted random algorithm, randompython

Random is used to generate random numbers. 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 python random module and python implementation method of the weighted random algorithm are all the content that I have shared with you. I hope you can give us a reference and support for more.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.