【发布时间】:2016-12-21 07:42:21
【问题描述】:
我正在尝试从长度为 3900 的 ['A','B','C','D','E'] 字符生成字符串,并且每个字符的概率应为: {'A':0.1, 'B':0.3, 'C':0.3, 'D':0.1, 'E':0.2 } 在这个字符串中 我写了以下代码:
from random import random
from bisect import bisect
def weighted_choice(choices):
values, weights = zip(*choices)
total = 0
cum_weights = []
for w in weights:
total += w
cum_weights.append(total)
x = random() * total
i = bisect(cum_weights, x)
return values[i]
string_ = ''
for i in range(0,3900):
string_ = string_ + weighted_choice([("A",10), ("B",30), ("C",30),("D",10),("E",20)])
with open("rand_file","w") as f:
f.write(string_)
但它不会根据概率生成字符串(文件)。它以这样的概率生成:
C 0.2500264583
B 0.2499284457
E 0.1666428313
D 0.0833782424
A 0.0833758065
概率导致for循环每次都单独运行,没有考虑之前的结果。
请帮忙解决这个问题?
【问题讨论】:
标签: python python-2.7 python-3.x random