在Python中生成n长度位列表

Ger*_*ard 3 python permutation bit

我想要一个函数,它将为我提供指定长度的所有可能的字符串,这些字符串仅由零和1组成.例如:

spam(4)
Run Code Online (Sandbox Code Playgroud)

应该让我:

['0110', '0111', '0001', '0011', '0010', '0101', '0100', '1110', '1100', '1101', '1010', '1011', '1001', '1000']
Run Code Online (Sandbox Code Playgroud)

我试着用itertools.permutations这份工作.所以,这就是我所做的.

def getPerms(n):
    perms = getCandidates(n)
    res = []
    for i in perms:
        res.extend(permutations(i))
    res = clean(res)
    return res

def clean(ar):
    res = []
    for i in ar:
        temp = ""
        for j in i:
            temp += j
        res.append(temp)
    return list(set(res))

def getCandidates(n):
    res = []
    for i in range(1, n):
        res.append("1"*i + "0"*(n-i))
    return res
Run Code Online (Sandbox Code Playgroud)

但这非常低效,并在10上输入内存错误.

Vol*_*ity 8

itertools.product改用.

>>> import itertools
>>> [''.join(i) for i in itertools.product('01', repeat=4)]
['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111']
Run Code Online (Sandbox Code Playgroud)

使用函数(假设itertools已经导入):

def bitGen(n):
    return [''.join(i) for i in itertools.product('01', repeat=n)]
Run Code Online (Sandbox Code Playgroud)

对于较大的ns,返回发电机可能更合适.

def bitGen(n):
    return (''.join(i) for i in itertools.product('01', repeat=n))

# Alternatively:

def bitGen(n):
    for i in itertools.product('01', repeat=n):
        yield ''.join(i)
Run Code Online (Sandbox Code Playgroud)


nne*_*neo 7

你只是想生成位串,显然.这是我所知道的最快方式:

for i in xrange(1, 2**n-1):
    yield '{:0{n}b}'.format(i, n=n)
Run Code Online (Sandbox Code Playgroud)

这会生成长度恰好n包含至少一个1和一个0的每个位串.

例:

>>> def gen(n):
...     for i in xrange(1, 2**n-1):
...         yield '{:0{n}b}'.format(i, n=n)
... 
>>> list(gen(4))
['0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001', '1010', '1011', '1100', '1101', '1110']
Run Code Online (Sandbox Code Playgroud)