[英]Python - Algorithm to generate all possible arrays of ones and zeros of a given length
My goal is to come up with an array of all possible bit combinations of length n. 我的目标是提出一个长度为n的所有可能位组合的数组。 For example, if n = 3, the target answer set should look like
例如,如果n = 3,则目标答案集应如下所示
000,
001,
010,
100,
011,
101,
110,
111
I've found the algorithmic solution , by I have completely no experience in iterators and C++ in general. 我找到了算法解决方案 ,我完全没有迭代器和C ++的经验。 Could someone give a hint how to rewrite the next function in python?
有人可以提示如何在python中重写下一个函数吗?
>>> import itertools
>>> result = ["".join(item) for item in itertools.product("01", repeat=3)]
>>> print result
['000', '001', '010', '011', '100', '101', '110', '111']
Without itertools: print the numbers from 0
to 2 ** n
in base 2 and pad them with zeros: 没有itertools:在基数2中打印
0
到2 ** n
的数字并用零填充它们:
for i in range(2 ** n):
print('{0:b}'.format(i).rjust(n, '0'))
Note that this leads to a much simpler solution in any language. 请注意,这可以在任何语言中提供更简单的解决方案。 All you need is a function to convert from base ten to base two.
您所需要的只是将基数从基数转换为基数2的函数。 Then, for each number from
0
to 2 ** n
, you convert it to base 2 and print or store the conversion. 然后,对于从
0
到2 ** n
每个数字,将其转换为基数2并打印或存储转换。
To convert x
to base two, divide it by 2
until it reaches 0
and keep track of the remainders. 要将
x
转换为基数2,请将其除以2
直到达到0
并跟踪余数。 The list of remainders, in reverse order, is x
in base 2: 剩余的列表以相反的顺序在基数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 always has a few handy libraries or functions to make complex things easy, and to make long taking work short. Python总是有一些方便的库或函数来简化复杂的事情,并且可以缩短工作时间。
In itertools.product()
your first parameter should be an array of the characters of which you want all possibilities, and the second after the repeat-keyword is the length of the results. 在
itertools.product()
您的第一个参数应该是您想要所有可能性的字符数组,而repeat-keyword之后的第二个参数应该是结果的长度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.