【问题标题】:Algorithm to perform K-combinations for all k on sentences对句子上的所有 k 执行 K 组合的算法
【发布时间】:2012-12-06 16:43:35
【问题描述】:

我有一个文件:test.txt,每一行都有一个句子。

Hello World  
99 Bottles of Beer  
Humpty Dumpty Sat on the wall

我希望生成一个输出,显示来自该文件的输入的所有组合(即 2n-1 个组合)。在上面的例子中,算法将溢出以下内容 - 每个组合都用管道分隔 (|)

Hello World  
99 Bottles of Beer  
Humpty Dumpty Sat on the wall  
Hello World | 99 Bottles of Beer  
Hello World | Humpty Dumpty Sat on the wall  
99 Bottles of Beer | Humpty Dumpty Sat on the wall  
Hello World | 99 Bottles of Beer | Humpty Dumpty Sat on the wall  

理想情况下,我希望在 bash、python 或 perl 脚本中完成此操作,但我愿意接受建议。

【问题讨论】:

  • 你有没有尝试过但失败了?如果是,那是什么?
  • 不是 (2^n)-1 吗?没有字符串的输出不是有效的吗?

标签: python bash combinations


【解决方案1】:
import itertools

l = [s.strip() for s in open('test.txt')]

for i in range(len(l)):
  print '\n'.join(map(' | '.join, itertools.combinations(l, i + 1)))

生产

Hello World
99 Bottles of Beer
Humpty Dumpty Sat on the wall
Hello World | 99 Bottles of Beer
Hello World | Humpty Dumpty Sat on the wall
99 Bottles of Beer | Humpty Dumpty Sat on the wall
Hello World | 99 Bottles of Beer | Humpty Dumpty Sat on the wall

如果你不喜欢'\n'.join() 的风格(我不确定我是否喜欢),你可以用显式循环替换它:

for i in range(len(l)):
  for c in map(' | '.join, itertools.combinations(l, i + 1)):
    print c

这有点冗长,但更经济。

【讨论】:

  • 哦等等,我忘了我可以使用组合。 刘海撞墙.
  • 谢谢大家!我花了最后 1 小时尝试使用 for 循环来做到这一点,但仍然无法产生我想要的输出。 屈从于 python 的 itertools 的强大功能
【解决方案2】:

你可以的

import itertools

file = open("test.txt")
lines = files.readlines()

current = []
for i in range(len(lines):
    current.append(i)

    for combination in set(itertools.permutations(current)):
        for l in combination:
            output+=' | '.join(lines[l])
        output+= '\n'
print output

我对我的 itertools 和 set 技能感到厌烦,但这应该可以,除非有内存限制..

【讨论】:

    猜你喜欢
    • 2021-06-30
    • 2010-09-12
    • 2013-01-15
    • 2020-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多