# coding: utf-8
import random
import time
def random_index(rate):
"""随机变量的概率函数"""
# 参数rate为list
# 返回概率事件的下标索引
start = 0
index = 0
randnum = random.randint(1, sum(rate))
for index, scope in enumerate(rate):
start += scope
if randnum <= start:
break
return index
def main():
arr = ['red', 'green', 'blue'] rate = [45, 30, 25] red_times = 0
green_times = 0
blue_times = 0
for i in range(10000):
index = random_index(rate)
if index == 0:
red_times += 1
elif index == 1:
green_times += 1
elif index == 2:
blue_times += 1
dict = {arr[0]: red_times, arr[1]: green_times, arr[2]: blue_times}
print(dict)
# print(red_times, green_times, blue_times)
start = time.perf_counter()
main()
end = time.perf_counter()
print(end - start)