gpt4 book ai didi

python - 我想要一个程序将所有可能的组合写入文本文件的不同行

转载 作者:太空狗 更新时间:2023-10-30 02:00:52 25 4
gpt4 key购买 nike

我想编写一个程序,将一组变量的每个组合打印到一个文本文件中,从而创建一个单词列表。每个答案都应该写在单独的一行上,并将 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(足以存储一种组合)。我希望这会有所帮助。

关于python - 我想要一个程序将所有可能的组合写入文本文件的不同行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/241533/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com