Python實現基於權重的隨機數2種方法

來源:互聯網
上載者:User

Python實現基於權重的隨機數2種方法

   這篇文章主要介紹了Python實現基於權重的隨機數2種方法,本文直接給出實現代碼,需要的朋友可以參考下

  問題:

  例如我們要選從不同省份選取一個號碼,每個省份的權重不一樣,直接選隨機數肯定是不行的了,就需要一個模型來解決這個問題。

  簡化成下面的問題:

  字典的key代表是省份,value代表的是權重,我們現在需要一個函數,每次基於權重選擇一個省份出來

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

  解決:

  這是能想到和能看到的最多的版本,不知道還沒有更高效好用的演算法。

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

#!/usr/bin/env python

# -*- coding: utf-8 -*-

#python2.7x

#random_weight.py

#author: orangleliu@gmail.com 2014-10-11

 

'''''

每個元素都有權重,然後根據權重隨機取值

 

輸入 {"A":2, "B":2, "C":4, "D":10, "E": 20}

輸出一個值

'''

import random

import collections as coll

 

data = {"A":2, "B":2, "C":4, "D":6, "E": 11}

 

#第一種 根據元素權重值 "A"*2 ..等,把每個元素取權重個元素放到一個數組中,然後最數組下標取隨機數得到權重

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]

 

#第二種 也是要計算出權重總和,取出一個隨機數,遍曆所有元素,把權重相加sum,當sum大於等於隨機數位時候停止,取出當前的元組

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(100):

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()")

  一次執行的結果

  ?

1

2

3

4

5

6

7

8

9

10

11

A 4

C 14

B 7

E 44

D 31

--------------------------------------------------

A 8

C 16

B 6

E 43

D 27

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.