我想编写一个程序,将一组变量的每个组合打印到一个文本文件,创建一个单词列表。每个答案应写在一个单独的行上,并将1位,2位和3位的所有结果写入单个文本文件。

有没有一种简单的方法可以编写一个可以实现此目的的python程序?下面是打印1,2和3位数的所有二进制数组合时我期望的输出示例:

Output:
0  
1

00  
01  
10  
11

000  
001  
010  
011  
100  
101  
110  
111
有帮助吗?

解决方案

解决问题的一个解决方案,对于您可能拥有的任何应用程序而言都是一般的:

def combinations(words, length):
    if length == 0:
        return []
    result = [[word] for word in words]
    while length > 1:
        new_result = []
        for combo in result:
            new_result.extend(combo + [word] for word in words)
        result = new_result[:]
        length -= 1
    return result

基本上,这会逐渐在所有组合的内存中构建一棵树,然后返回它们。然而,它是内存密集型的,因此对于大规模组合来说是不切实际的。

问题的另一个解决方案实际上是使用计数,然后将生成的数字转换为单词列表中的单词列表。为此,我们首先需要一个函数(称为 number_to_list()):

def number_to_list(number, words):
    list_out = []
    while number:
        list_out = [number % len(words)] + list_out
        number = number // len(words)
    return [words[n] for n in list_out]

事实上,这是一个将十进制数转换为其他基数的系统。然后我们写出计数功能;这相对简单,将构成应用程序的核心:

def combinations(words, length):
    numbers = xrange(len(words)**length)
    for number in numbers:
        combo = number_to_list(number, words)
        if len(combo) < length:
            combo = [words[0]] * (length - len(combo)) + combo
        yield combo

这是一个Python生成器;使它成为一个生成器允许它使用更少的RAM。将数字转换为单词列表后,还有一些工作要做;这是因为这些列表需要填充,以便它们处于请求的长度。它会像这样使用:

>>> list(combinations('01', 3))
[['0', '0', '0'], ['0', '0', '1'],
['0', '1', '0'], ['0', '1', '1'],
['1', '0', '0'], ['1', '0', '1'],
['1', '1', '0'], ['1', '1', '1']]

如您所见,您可以找到列表清单。这些子列表中的每一个都包含原始单词的序列;然后,您可以执行类似 map(''。join,list(combinations('01',3)))的操作来检索以下结果:

['000', '001', '010', '011', '100', '101', '110', '111']

然后你可以把它写到磁盘上;但是,更好的想法是使用生成器具有的内置优化并执行以下操作:

fileout = open('filename.txt', 'w')
fileout.writelines(
    ''.join(combo) for combo in combinations('01', 3))
fileout.close()

这将只使用尽可能多的RAM(足以存储一个组合)。我希望这会有所帮助。

其他提示

# Given two lists of strings, return a list of all ways to concatenate
# one from each.
def combos(xs, ys):
    return [x + y for x in xs for y in ys]

digits = ['0', '1']
for c in combos(digits, combos(digits, digits)):
    print c

#. 000
#. 001
#. 010
#. 011
#. 100
#. 101
#. 110
#. 111

在大多数语言中都不应该太难。以下伪代码有帮助吗?

for(int i=0; i < 2^digits; i++)
{
     WriteLine(ToBinaryString(i));
}

下面给出了产生列表的所有排列的基本功能。在这种方法中,通过使用生成器来懒惰地创建排列。

def perms(seq):
    if seq == []:
        yield []
    else:
        res = []
        for index,item in enumerate(seq):
            rest = seq[:index] + seq[index+1:]
            for restperm in perms(rest):
                yield [item] + restperm

alist = [1,1,0]
for permuation in perms(alist):
    print permuation
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top