Python-生成给定长度的所有可能的1和0数组的算法
Python - Algorithm to generate all possible arrays of ones and zeros of a given length
我的目标是想出一个长度为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的情况下打印从0
到2 ** n
的数字,并用零填充:
for i in range(2 ** n):
print('{0:b}'.format(i).rjust(n, '0'))
请注意,这在任何语言中都会带来一个简单得多的解决方案。您所需要的只是一个函数,将基数从10转换为基数2。然后,对于从0
到2 ** 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关键字后面的第二个参数是结果的长度。
相关文章:
- 有可能在Armadillo中复制MATLAB circshift方法吗
- 在他自己的方法中,有可能将一个对象取消引用到另一个对象吗
- 有可能使shared_ptr协变吗
- 有可能在信号处理程序中设置promise吗
- 是否有可能实现O(N)时间和O(1)空间解决方案,以实现C++中的字符串循环移位
- 是否有可能构建面向Linux和Windows的.Net Core C++ / CLI应用程序?
- 是否有可能使用debug_info获取ELF文件的源代码?
- C++,是否有可能/如何定义在.h和.cpp源文件中调用函数的类构造函数
- 有可能在C++中有类的查找表吗
- 是否有可能让 c++ dll 在后台运行 python 程序并让它填充向量图?如果是这样,如何?
- 向量的大小是否有可能为 1 但其中的元素数量为零?
- 是否有可能编写新的叮当声现代化规则?
- 是否有可能通过指向另一个未关联的子对象的指针来获取指向一个子对象的指针?
- 是否有可能通过演绎指南实现整个 std::make_tuple 功能?
- 是否有可能在没有复制的情况下传递 std::vector<int> 作为参数来获得 std::vector<std::array<int, 3>>?
- 是否有可能具有放入容器的移动操作的类型?
- 是否有可能通过溢出 C 中的第一个元素来写入数组第二个元素
- 声明是否有可能逃脱其封闭的名称空间
- git-是否有互联网上某处所有可能错误的列表
- 是否有可能有一个派生类继承最终函数但创建相同的函数(而不是重写)