Python-生成给定长度的所有可能的1和0数组的算法

Python - Algorithm to generate all possible arrays of ones and zeros of a given length

本文关键字:有可能 算法 数组 Python-      更新时间:2023-10-16

我的目标是想出一个长度为n的所有可能的比特组合的数组。例如,如果n=3,目标答案集应该看起来像

000,
001,
010,
100,
011,
101,
110,
111

我已经找到了算法解决方案,因为我在迭代器和C++方面完全没有经验。有人能提示一下如何在python中重写下一个函数吗?

>>> import itertools
>>> result = ["".join(item) for item in itertools.product("01", repeat=3)]
>>> print result
['000', '001', '010', '011', '100', '101', '110', '111']

不使用itertools:在基数为2的情况下打印从02 ** n的数字,并用零填充:

for i in range(2 ** n):
    print('{0:b}'.format(i).rjust(n, '0'))

请注意,这在任何语言中都会带来一个简单得多的解决方案。您所需要的只是一个函数,将基数从10转换为基数2。然后,对于从02 ** n的每个数字,将其转换为基数2并打印或存储转换。

要将x转换为基数2,请将其除以2,直到达到0,并跟踪余数。余数列表按相反顺序为基数2:中的x

x = 13
13 / 2 = 6 remainder 1
 6 / 2 = 3 remainder 0
 3 / 2 = 1 remainder 1
 1 / 2 = 0 remainder 1
=> 13 in base 2 = 1101
import itertools
#Possible characters
n = [0, 1]
#Asking required length
l = int(input("length: "))
#Putting all possibilities in list
r = list(itertools.product(n, repeat=l))
print(r)

Python总是有一些方便的库或函数来简化复杂的事情,缩短耗时。

itertools.product()中,第一个参数应该是一个字符数组,您想要它的所有可能性,repeat关键字后面的第二个参数是结果的长度。