Python implementation of Python's random module and weighted stochastic algorithm

Source: Internet
Author: User
Tags shuffle

The random number is used to generate numbers, and we can use it to randomly generate a number or select a string.

    • Random.seed (x) changes the seeding seed of the random number generator.

      It is generally not necessary to specifically set Seed,python to automatically select Seed.

    • Random.random () to generate a random floating point number n,0 <= N < 1
    • Random.uniform (A, b) is used to generate a random number of floating-point numbers in a specified range, resulting in a random integer a<=n<=b;
    • Random.randint (A, b) is used to generate a specified range of integers, a is the lower bound, B is the upper limit, the resulting random integer a<=n<=b; if a=b, then n=a; if a>b, error
    • Random.randrange ([start], stop [, step]) from within the specified range [Start,stop], gets a random number in the collection incremented by the specified cardinality, the base default value is 1
    • Random.choice (Sequence) obtains a random element from the sequence, and the parameter sequence represents an ordered type, not a specific type, which refers to list,tuple, string, etc.
    • Random.shuffle (X[,random]) is used to disrupt (shuffle) the elements in a list, altering the original list
    • Random.sample (sequence,k) randomly fetches k elements from a specified sequence as a fragment, without altering the original sequence

So now that the basics are there, let's implement a weighted random algorithm :

The weighted stochastic algorithm is generally used in the following scenarios: There is a set of s, inside such as a,b,c,d these four items. At this point we want to randomly extract an item, but the probability of extraction is different, for example, we want to draw a probability is 50%, the probability of pumping B and C is 20%,d probability is 10%. In general, we can give each of the weights, the probability of extraction proportional to this weight. Then the above set becomes:

{A:5,b:2,c:2,d:1}

Method One:

The simplest way to do this is to:

Expand the sequence by the weight value to: lists=[a,a,a,a,a,b,b,c,c,d], and then Random.choice (lists) randomly select one on the line. Although the time complexity of this selection is O (1), but the amount of data is large, the space consumption is too large.

#Coding:utf-8ImportRandomdefweight_choice (list, weight):""":p Aram list: The weight sequence for the selected sequence:p Aram Weight:list: Return: Selected value"""new_list= []     forI, ValinchEnumerate (list): New_list.extend (Val*Weight[i])returnRandom.choice (new_list)if __name__=="__main__":    Print(Weight_choice (['A','B','C','D'], [5, 2, 2, 1])

Method Two:

The more common approach is this:

Calculates the sum of the weights sums, then randomly selects a number r between 1 and sum, then iterates through the collection, counts the sum of the weights of the traversed items, and stops the traversal if it is greater than or equal to R, and selects the item that is encountered.

In the above set, for example, Sum equals 10, and if it is random to 1-5, it exits the traversal when the first number is traversed. Match the probability of the selection.

When you choose to traverse the collection, its time complexity is O (n).

#Coding:utf-8Importrandomlist= ['A','B','C','D']defweight_choice (weight):""":p aram weight:list corresponding weight sequence: return: The index of the selected value in the original list"""T= Random.randint (0, SUM (weight)-1)     forI, ValinchEnumerate (weight): t-=ValifT <0:returnIif __name__=="__main__":    Print(List[weight_choice ([5, 2, 2, 1]))

Method Three:

You can sort the original sequence by weight first. In this way, high-probability items can be quickly encountered, reducing the traversal of the items. (Because Rnd decrements the fastest (minus the largest number first))
Compare {a:5,b:2,c:2,d:1} and {b:2,c:2,a:5,d:1}
The former expectation of traversing steps is 5/10*1+2/10*2+2/10*3+1/10*4=19/10 and 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 order of the original sequence also takes time.

The prefix and sequence of a weight value are first made, and then after generating a random number T, you can use the binary capable to find the prefix and sequence, then the time complexity of the selection is O (Logn).

#Coding:utf-8ImportRandomImportbisectlist= ['A','B','C','D']defweight_choice (weight):""":p aram weight:list corresponding weight sequence: return: The index of the selected value in the original list"""Weight_sum=[] Sum=0 forAinchWeight:sum+=a weight_sum.append (sum) t= Random.randint (0, Sum-1)    returnbisect.bisect_right (weight_sum, T)if __name__=="__main__":    Print(List[weight_choice ([5, 2, 2, 1]))

Python implementation of Python's random module and weighted stochastic algorithm

Related Article

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.