有效地找到单词的所有可能的唯一排列[重复]

问题描述 投票:-1回答:2

这个问题在这里已有答案:

让我说我有下面这个词:“aabb”然后所有可能独特的排列是:“aabb”,“abab”,“baba”,“abba”,“baab”和“bbaa”。请注意,有4个! = 24种方法,但4选择2 = 6.我目前拥有的是一种天真的方法:找到所有排列,包括重复,然后删除重复:

def permutations(l):
    if len(l) <=1:
        yield l
    else:
        for p in permutations(l[1:]):
            for i in range(len(l)):
                yield p[:i] + l[0] + p[i:]

print(set(permutations("aabb")))

我的问题是,他们是否存在更有效的方法来找到所有这些排列?

编辑:我不希望一种方法遵循找到所有排列的低效想法,然后删除重复。我的代码示例已经这样做了!

编辑:coldspeed正确标记我的问题重复。正确的答案是使用sympy的multiset_permutations函数:

>>> from sympy.utilities.iterables import multiset_permutations
>>> list(multiset_permutations([1,1,1]))
[[1, 1, 1]]
>>> list(multiset_permutations([1,1,2]))
[[1, 1, 2], [1, 2, 1], [2, 1, 1]]

,根据@Bill Bell。

python algorithm math combinatorics discrete-mathematics
2个回答
0
投票

你可以使用permutationsitertoolsset返回独特的元素,然后使用join将字符串作为单个元素。列表理解方式如下。

from itertools import permutations
result = [''.join(lst) for lst in set((permutations("aabb")))]
print (result)

产量

['aabb', 'baba', 'bbaa', 'abab', 'abba', 'baab']

0
投票

可以使用permutationsset()删除重复项

from itertools import permutations
res=set()
for i in permutations('aabb'):
    res.add(i)

产量

set([('b', 'a', 'b', 'a'), ('b', 'b', 'a', 'a'), ('a', 'b', 'b', 'a'), ('a', 'a', 'b', 'b'), ('b', 'a', 'a', 'b'), ('a', 'b', 'a', 'b')])

如果需要字符串列表的结果

map(''.join,set(permutations('aabb')))

产量

['baba', 'bbaa', 'abba', 'aabb', 'baab', 'abab']
© www.soinside.com 2019 - 2024. All rights reserved.