- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我想编写一个程序,将一组变量的每个组合打印到一个文本文件中,从而创建一个单词列表。每个答案都应该写在单独的一行上,并将 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/
降本手段一招鲜,增效方法吃遍天; 01 互联网行业里; 降本策略千奇百怪,手段却出奇一致;增效方法五花八门,手段更是花里胡哨; 对于企业来说;
有什么方法可以使用 angularjs 中的部分进行代码分组吗? 原因 --- 我的 Controller 包含太多代码。该 Controller 包含了多个方法和大量功能的代码,降低了代码的可读性。
不幸的是,我的数据库的数据模型必须改变,所以我正在寻找最轻松的方式来迁移我的数据。 此时情况如何: create table cargo{ id serial primary key, per
在 QTextEdit 对象中,假设我想知道字符在鼠标光标下的位置。 我会写... void MyQTextEditObject::mousePressEvent(QMouseEvent* mouse
是否可以在 C++ 中返回一个 return 语句或做一些具有类似功能的事情? 例如,如果代码中有几个函数将指针作为输入,并且每个函数都检查指针是否为 nullptr,这将很方便。如果它是一个 nul
我的 PC 上有一个控制台应用程序,它是 signalR 服务器。 我有一个 html 页面,它是互联网上的 signalR 客户端。但我尝试连接服务器,但我有一个错误的请求 400 错误。如果服务器
我想将应用程序作为后台进程运行。当点击应用程序图标时,它不会显示任何 View ,只会启动后台进程。 最佳答案 对于 iOS 这是不可能的,但是对于 android,react native 有 he
我知道有(昂贵的)框架可以让你在 VS C# 中编写 android 应用程序并将其编译为 android apk。 我也知道,可以在 VS 中编写 Java 应用程序(link)。 是否有可能,甚至
我在做: can :manage, :all if user.role == 'admin' can :approve, Anuncio do |anuncio| anuncio.try(:apr
我是一名优秀的程序员,十分优秀!