对句子上的所有k执行K组合的算法

时间:2012-12-06 08:13:18

标签: python bash combinations

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

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

我希望产生一个输出,显示该文件输入的所有组合(即2 n -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 个答案:

答案 0 :(得分:3)

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 :(得分:0)

你可以做到

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&amp ;;感到厌倦设置技能,但这应该有效,除非有内存限制..