Python:异步随机损坏?

Python : Async random broken?

所以 rn 我在异步工作 python,我必须处理随机数。 问题是,对于 0 到 4 之间的数字,我经常得到相同的数字,如下所示:

3 2 0 2 4 0 1 4 2 1 4 2 1 3 2 3 2 2 2 1 0 3 2 2 2 0 0 4 3 0 3 4 4 0 3 3 3 3 2 4 4 4 0

当然只有五种可能,但是看看最后,我连续得到4个3,大概是1/625的几率,我们不说我得到相同3的次数连续几次。

我的代码如下所示:

when async ready :
  random.seed(time.time())

async event:
  index = random.randint(0,4)
  async.send(someList[index])

它也是一个不和谐的机器人,所以代码会连续运行,所以如果重要的话,种子只会被 donc 一次

如果没有更完整但最小的示例,我们无法确定您使用的代码是否按预期工作,但在 42 个元素的长列表中,一个值连续重复 4 次是很常见的。检查以下生成 1000 次 42 长随机列表的代码,检查每个列表中最长的重复,并计算它发生的频率。

import random
import matplotlib.pyplot as plt


length_of_longest = []

for j in range(1000):
    random.seed(j)
    rndstr = "".join([str(random.randint(0, 4)) for _ in range(42)])
    for i in range(1, 42):
        total = 0
        for my_str in "01234":
            for_my_str = rndstr.count(my_str*i)
            total += for_my_str
        if total == 0:
            length_of_longest.append(i-1)  # this length was not found
            break

# plot the results
fig, ax = plt.subplots()
ax.set_xticks([i+0.5 for i in range(8)], labels=range(8))
fig.patch.set_facecolor('white')
plt.hist(length_of_longest,bins=range(0,max(length_of_longest)+2))

这会产生以下情节:

x-axis 表示最长重复 x 的频率(例如在 x=5 时,序列中有 11111 或 33333 或...),y 表示有多少个系列找到这个 属性 out of 1000.

可以看出,在大约15%-20%的情况下,最长序列的长度为4,但也可能在1000次中出现几次,即选择相同的值7连续几次。