Python implements two weight-based random number methods

Source: Internet
Author: User

Python implements two weight-based random number methods

This article mainly introduces two methods for implementing weight-based random numbers in Python. This article provides the implementation code directly. For more information, see

Problem:

For example, if we want to select a number from different provinces, and the weights of each province are different, directly selecting a random number will definitely not work. We need a model to solve this problem.

Simplified to the following:

The dictionary key represents the province, and the value represents the weight. Now we need a function to select a province based on the weight each time.

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

Solution:

This is the most visible version that can be thought of. I don't know if there are any more efficient and useful algorithms.

?

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

 

'''''

Each element has a weight, and then random values are obtained based on the weight.

 

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

Output A Value

'''

Import random

Import collections as coll

 

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

 

# The first method is to put each element's weight element into an Array Based on the element's Weight Value "A" * 2..., and then obtain the weight by the maximum array subscript and random number.

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]

 

# The second method is to calculate the sum of weights, retrieve a random number, traverse all elements, and add weights to sum. When sum is greater than or equal to a random number, stop and retrieve the current tuples.

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

Result of one execution

?

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

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.