ami*_*mel 3 python combinations permutation combinatorics
我正在做一些像下面这样的分词实验.
lst是一系列字符,output是所有可能的单词.
lst = ['a', 'b', 'c', 'd']
def foo(lst):
...
return output
output = [['a', 'b', 'c', 'd'],
['ab', 'c', 'd'],
['a', 'bc', 'd'],
['a', 'b', 'cd'],
['ab', 'cd'],
['abc', 'd'],
['a', 'bcd'],
['abcd']]
Run Code Online (Sandbox Code Playgroud)
我已经检查过combinations并permutations在itertools库中,
并尝试过组合学.
然而,似乎我在看错了,因为这不是纯粹的排列和组合......
似乎我可以通过使用大量循环来实现这一点,但效率可能很低.
编辑
单词顺序很重要,因此组合喜欢['ba', 'dc']或['cd', 'ab']无效.
订单应始终从左到右.
编辑
@Stuart的解决方案在Python 2.7.6中不起作用
编辑
@Stuart的解决方案在Python 2.7.6中有效,请参阅下面的注释.
itertools.product 应该能够帮助你.
这个想法是这样的: - 考虑由板块分隔的A1,A2,......,AN.将有N-1板.如果有平板,则存在分段.如果没有平板,则有连接.因此,对于给定的长度为N的序列,您应该具有2 ^(N-1)个这样的组合.
就像下面这样
import itertools
lst = ['a', 'b', 'c', 'd']
combinatorics = itertools.product([True, False], repeat=len(lst) - 1)
solution = []
for combination in combinatorics:
i = 0
one_such_combination = [lst[i]]
for slab in combination:
i += 1
if not slab: # there is a join
one_such_combination[-1] += lst[i]
else:
one_such_combination += [lst[i]]
solution.append(one_such_combination)
print solution
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1988 次 |
| 最近记录: |