Questions:
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: orangleliu@gmail.com 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} Output a value "' Import random import collections as Coll data = {"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 R Ange (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 the elements, add the weights to sum, stop when sum is greater than or equal to a random number, take out 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[eva L (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
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://www.bitsCN.com/article/65060.htm
Http://www.bitsCN.com/article/65058.htm