Python 二进制序列 x 位长的所有排列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4928297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
all permutations of a binary sequence x bits long
提问by ComputationalSocialScience
I would like to find a clean and clever way (in python) to find all permutations of strings of 1s and 0s x chars long. Ideally this would be fast and not require doing too many iterations...
我想找到一种干净而聪明的方法(在 python 中)来查找 1s 和 0s x 字符长的字符串的所有排列。理想情况下,这会很快并且不需要进行太多迭代......
So, for x = 1 I want: ['0','1'] x =2 ['00','01','10','11']
所以,对于 x = 1 我想要: ['0','1'] x =2 ['00','01','10','11']
etc..
等等..
Right now I have this, which is slow and seems inelegant:
现在我有这个,它很慢而且看起来不优雅:
self.nbits = n
items = []
for x in xrange(n+1):
ones = x
zeros = n-x
item = []
for i in xrange(ones):
item.append(1)
for i in xrange(zeros):
item.append(0)
items.append(item)
perms = set()
for item in items:
for perm in itertools.permutations(item):
perms.add(perm)
perms = list(perms)
perms.sort()
self.to_bits = {}
self.to_code = {}
for x in enumerate(perms):
self.to_bits[x[0]] = ''.join([str(y) for y in x[1]])
self.to_code[''.join([str(y) for y in x[1]])] = x[0]
采纳答案by Josh Bleecher Snyder
itertools.productis made for this:
itertools.product是为此而制作的:
>>> import itertools
>>> ["".join(seq) for seq in itertools.product("01", repeat=2)]
['00', '01', '10', '11']
>>> ["".join(seq) for seq in itertools.product("01", repeat=3)]
['000', '001', '010', '011', '100', '101', '110', '111']
回答by Sebastian Paaske T?rholm
You can use itertools.product()for doing this.
您可以使用它itertools.product()来执行此操作。
import itertools
def binseq(k):
return [''.join(x) for x in itertools.product('01', repeat=k)]
回答by Glenn Maynard
There's no need to be overly clever for something this simple:
对于这么简单的事情,没有必要过于聪明:
def perms(n):
if not n:
return
for i in xrange(2**n):
s = bin(i)[2:]
s = "0" * (n-len(s)) + s
yield s
print list(perms(5))
回答by Ignacio Vazquez-Abrams
Python 2.6+:
Python 2.6+:
['{0:0{width}b}'.format(v, width=x) for v in xrange(2**x)]
回答by inspectorG4dget
Kudos to all the clever solutions before me. Here is a low-level, get-you-hands-dirty way to do this:
感谢我面前的所有聪明的解决方案。这是一个低级的,让你动手的方法来做到这一点:
def dec2bin(n):
if not n:
return ''
else:
return dec2bin(n/2) + str(n%2)
def pad(p, s):
return "0"*(p-len(s))+s
def combos(n):
for i in range(2**n):
print pad(n, dec2bin(i))
That should do the trick
这应该够了吧

