python - Numpy array item order - 序列的平均分布

标签 python algorithm numpy random graph-theory

假设我有一个打乱的 numpy 数组:

a = np.array([1,2,3,4,5,6]*6)
np.random.shuffle(a)

如何确保打乱后的数组中的每一项都以相同的次数跟随其他项?

例如,我想确保数字 1 在数组中跟随数字 2 的次数与它跟随数字 4 的次数相同。对于所有其他数字也是如此

对于这个问题,我们可以假设列表是循环的,即第一项跟在最后一项之后

通常我会发布一些我尝试过的代码,但我对此一头雾水。

我能想到的最低效的方法是编写一个函数来计算一个数字跟随另一个数字的次数,然后检查所有计数是否相等。如果没有,重新洗牌。

但这并不能保证我最终会得到一个满足平等分配标准的列表。

最佳答案

这是我能想到的最好的。请注意,对于 36 个数字,每个数字必须紧跟在另一个数字之后一次。

while True:
    x = {i: set(range(1,7)) for i in range(1,7)}

    a = [random.choice(range(1,7))]  # start with a random number
    last = a[-1]
    while x[last]:
        next = random.choice(list(x[last]))
        x[last].remove(next)
        a.append(next)
        last = next

    if len(a) == 37:
        # We get to length 37 if and only if each set above is exhausted.
        # In this case, the first item will always equal the last item
        # (proof left as an exercise for the reader), so remove it.
        a = a[:-1]
        break

print(''.join(str(i) for i in a))

对我来说,生成的 221164425231355145433465615366263241 似乎满足标准。

关于python - Numpy array item order - 序列的平均分布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33271172/

相关文章:

python - 使用共享内存从单独的 C 进程访问 numpy 数组

python - 改变签名的装饰器是一个不好的模式吗?

python - 使用优化模块的 Scipy 错误。将数组转换为 Fortran 失败

n X n 矩阵的行列式代码

枚举一个矩形可以被分割成 n 个更小的矩形的所有可能方式的算法

python - 重复数组n次

python - 获取属性错误 : 'Tensor' object has no attribute 'log_prob' while saving a tensorflow model

python - 将列表插入单个 sqlite 数据库列

algorithm - 使用 n 个节点之间的 k 个链接最小化总距离

python - 你如何制作 numpy 数组的 ggplot 图?