我如何计算一组数字/位的所有可能性(在 python 中,或者任何与此相关的语言) [英] How do I compute all possibilities for an array of numbers/bits (in python, or any language for that matter)

查看:38
本文介绍了我如何计算一组数字/位的所有可能性(在 python 中,或者任何与此相关的语言)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经连续绞尽脑汁 3 个小时了,但我还是没明白,所以我在这里问.(我在标题中写了 Python,但这几乎适用于任何语言)

I have been wracking my brains out for 3 hours straight, but I still don't get it, so I am asking here. (I wrote Python in the title, but this could be for pretty much any language)

假设我有一个固定长度 n 的位数组(但也可能是定义范围内的整数),假设为 5.

Let's assume I have an array of bits (but it may also be integers in a defined range) of fixed length n, let's say 5.

array=[0,1,1,0,0]

现在,我如何生成数字范围内可能的所有数组(在位的情况下,为 2).

Now, how do I generate ALL arrays, which are possible in the number range (in the case of bits, 2).

所以:

[0,0,0,0,0], [0,0,0,0,1], [0,0,0,1,0], [0,0,0,1,1] ...

我曾尝试在这里寻找解决方案,但我总能找到类似的解决方案,但并不能完全解决我的问题.

I have tried searching for a solution here, but I always find something which is similar, but which doesn't quite solve my problem.

为了解决这个问题,我尝试了各种循环,但我总是得到不止一次的一种可能性(不应该发生),或者没有得到所有可能的.

To solve this, I have tried various loops, but I always end up either getting one possibility more than once (should not happen), or not getting all possible ones.

我可以使用 if 语句来做到这一点(检查组合是否已经存在),但这似乎很简单.

I can manage to do this with if statements (to check if a combination already exists), but that seems very unsophisticated.

有没有一种简单的方法,只使用循环来获得所有的可能性?

Is there a simple method, using only loops, to obtain all possibilities?

谢谢

由于下面提到了这一点,不,这不是作业.这是为了研究以实现二元状态的贝叶斯网络.(开/关).

Since this was mentioned below, no, this is not homework. This is for research in order to implement a Bayesian network of binary states. (on/off).

推荐答案

在 Python 中,使用 itertools 像这样的东西

In Python, use itertools for stuff like this

from itertools import product
for i in product([0,1], repeat=5): 
    print i

产量:

(0, 0, 0, 0, 0)
(0, 0, 0, 0, 1)
(0, 0, 0, 1, 0)
(0, 0, 0, 1, 1)
(0, 0, 1, 0, 0)
etc...

这篇关于我如何计算一组数字/位的所有可能性(在 python 中,或者任何与此相关的语言)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆