-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrandom_demo.py
More file actions
82 lines (66 loc) · 1.82 KB
/
random_demo.py
File metadata and controls
82 lines (66 loc) · 1.82 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# coding: utf-8
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/12/20 19:02
# @Author : ZhangSheng@xiaoyezi.com
# @File : random_demo.py
import random
def random_index(rate):
"""随机变量的概率函数"""
#
# 参数rate为list<int>
#
start = 0
randnum = random.randint(1, sum(rate))
for index, item in enumerate(rate):
print 'index, item = ', index, item
start += item
if randnum <= start:
break
return index
def main():
arr = ['red', 'green', 'blue']
rate = [30, 45, 25]
red_times = 0
green_times = 0
blue_times = 0
others = 0
for i in xrange(10000):
random.seed()
random_color = arr[random_index(rate)]
if random_color == 'red':
red_times += 1
elif random_color == 'green':
green_times += 1
elif random_color == 'blue':
blue_times += 1
else:
others += 1
# print 'others'
print red_times, green_times, blue_times, others
def get_random_option_by_rate(option_rate=[1, 1]):
if not option_rate or not sum(option_rate) or sum([abs(int(i)) for i in option_rate]) != sum(option_rate):
return 0
random.seed()
rand_val = random.randint(1, sum(option_rate))
item_sum = 0
for index, item in enumerate(option_rate):
item_sum += item
if rand_val <= item_sum:
break
return index+1
def test_random():
_true, _false = 0, 0
for i in xrange(1000):
_value = get_random_option_by_rate(option_rate=[1, 1])
if _value:
if _value == 1:
_true += 1
else:
_false += 1
else:
pass
print '_true, _false = ', _true, _false
if __name__ == '__main__':
# main()
test_random()