[Python] 2 implementations of random numbers based on weights

Source: Internet
Author: User

Problem:

For example, we want to choose a number from different provinces, each province's weight is not the same, direct selection of random number is definitely not possible, you need a model to solve the problem.

Simplify to the following questions:

The key for the dictionary is the province, and value is the weight, and we now need a function that selects a province based on the weights each time.

{"A": 2, "B": 2, "C": 4, "D": Ten, "E": 20}


Solve:

This is the most can think and can see the version, do not know that there is no more efficient and useful algorithms.

#!/usr/bin/env python#-*-coding:utf-8-*-#python2.7x#random_weight.py #author: [email protected] 2014-10-11 ' Each element has weights, then enter {"A" according to the random value of the weight: 2, "B": 2, "C": 4, "D": Ten, "E": 20} Outputs a value "' Import randomimport collections as Colldata = {" A ": 2, "B": 2, "C": 4, "D": 6, "E": one} #第一种 according to the element weight value "A".        And so on, each element takes a weight element into an array, and then the most array subscript random number gets the weight def list_method (): All_data = [] for V, W in Data.items (): temp = [] For I in Range (W): Temp.append (v) all_data.extend (temp) n = random.randint (0,len (All_data) -1) return All_data[n] #第二种 is also to calculate the sum of weights, take out a random number, traverse all elements, add the weights sum, when the sum is greater than or equal to the random number when the stop, remove the current tuple def iter_method (): Total        = SUM (Data.values ()) rad = Random.randint (1,total) cur_total = 0 res = "" For K, V in Data.items ():    Cur_total + = v if rad<= cur_total:res = k break return res def test (method): Dict_num = coll.defaultdict (int) for I in Range: Dict_num[eval (method)] + = 1 foR i,j in Dict_num.items (): Print I, j if __name__ = = "__main__": Test ("List_method ()") print "-" *50     Test ("Iter_method ()")

Results of one execution

A 4C 14B 7E 44D--------------------------------------------------a 8C 16B 6E 43D 27



Ideas:

Ideas are very primitive can refer to the following connection, there are other good ways to communicate together!!

Code: https://gist.github.com/orangle/d83bec8984d0b4293710

Reference:

http://jzkangta.iteye.com/blog/1326302

http://blog.csdn.net/ajian005/article/details/19301689


This article is derived from "Orangleliu notebook " Blog, be sure to keep this source http://blog.csdn.net/orangleliu/article/details/39997489

[Python] 2 implementations of random numbers based on weights

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.