在Python中,使用itertools模块生成列表的所有排列非常简单。我有一种情况,我使用的列表只有两个字符(即'1122')。我想生成所有独特的排列。
对于字符串'1122',有6个唯一的排列(1122,1212,1221等),但itertools.permutations将产生24个项目。仅记录唯一排列很简单,但收集它们需要的时间比所有720项都要多。
是否有一个函数或模块在生成排列时会考虑重复的元素,所以我不必自己编写?
答案 0 :(得分:18)
This web page看起来很有希望。
def next_permutation(seq, pred=cmp):
"""Like C++ std::next_permutation() but implemented as
generator. Yields copies of seq."""
def reverse(seq, start, end):
# seq = seq[:start] + reversed(seq[start:end]) + \
# seq[end:]
end -= 1
if end <= start:
return
while True:
seq[start], seq[end] = seq[end], seq[start]
if start == end or start+1 == end:
return
start += 1
end -= 1
if not seq:
raise StopIteration
try:
seq[0]
except TypeError:
raise TypeError("seq must allow random access.")
first = 0
last = len(seq)
seq = seq[:]
# Yield input sequence as the STL version is often
# used inside do {} while.
yield seq[:]
if last == 1:
raise StopIteration
while True:
next = last - 1
while True:
# Step 1.
next1 = next
next -= 1
if pred(seq[next], seq[next1]) < 0:
# Step 2.
mid = last - 1
while not (pred(seq[next], seq[mid]) < 0):
mid -= 1
seq[next], seq[mid] = seq[mid], seq[next]
# Step 3.
reverse(seq, next1, last)
# Change to yield references to get rid of
# (at worst) |seq|! copy operations.
yield seq[:]
break
if next == first:
raise StopIteration
raise StopIteration
>>> for p in next_permutation([int(c) for c in "111222"]):
... print p
...
[1, 1, 1, 2, 2, 2]
[1, 1, 2, 1, 2, 2]
[1, 1, 2, 2, 1, 2]
[1, 1, 2, 2, 2, 1]
[1, 2, 1, 1, 2, 2]
[1, 2, 1, 2, 1, 2]
[1, 2, 1, 2, 2, 1]
[1, 2, 2, 1, 1, 2]
[1, 2, 2, 1, 2, 1]
[1, 2, 2, 2, 1, 1]
[2, 1, 1, 1, 2, 2]
[2, 1, 1, 2, 1, 2]
[2, 1, 1, 2, 2, 1]
[2, 1, 2, 1, 1, 2]
[2, 1, 2, 1, 2, 1]
[2, 1, 2, 2, 1, 1]
[2, 2, 1, 1, 1, 2]
[2, 2, 1, 1, 2, 1]
[2, 2, 1, 2, 1, 1]
[2, 2, 2, 1, 1, 1]
>>>
2017年8月12日
七年后,这里有一个更好的算法(更清晰):
from itertools import permutations
def unique_perms(series):
return {"".join(p) for p in permutations(series)}
print(sorted(unique_perms('1122')))
答案 1 :(得分:1)
使用set使解决方案更简单。具有重复字符的字符串,以及 不重复 用作输入。
import re
from itertools import permutations
def perm(s):
l = re.split('\B',s)
return set(list(permutations(l,len(l))))
l = '1122'
perm(l)
{('1', '1', '2', '2'),
('1', '2', '1', '2'),
('1', '2', '2', '1'),
('2', '1', '1', '2'),
('2', '1', '2', '1'),
('2', '2', '1', '1')}
l2 = '1234'
perm(l2)
{('1', '2', '3', '4'),
('1', '2', '4', '3'),
('1', '3', '2', '4'),
('1', '3', '4', '2'),
('1', '4', '2', '3'),
('1', '4', '3', '2'),
('2', '1', '3', '4'),
('2', '1', '4', '3'),
('2', '3', '1', '4'),
('2', '3', '4', '1'),
('2', '4', '1', '3'),
('2', '4', '3', '1'),
('3', '1', '2', '4'),
('3', '1', '4', '2'),
('3', '2', '1', '4'),
('3', '2', '4', '1'),
('3', '4', '1', '2'),
('3', '4', '2', '1'),
('4', '1', '2', '3'),
('4', '1', '3', '2'),
('4', '2', '1', '3'),
('4', '2', '3', '1'),
('4', '3', '1', '2'),
('4', '3', '2', '1')}
答案 2 :(得分:1)
这也是常见的面试问题。如果无法使用标准库modules,请考虑以下实现:
我们定义了lexicographic ordering of permutations。一旦我们做 我们可以从最小排列和增量开始 直到我们达到最大排列为止。
def next_permutation_helper(perm):
if not perm:
return perm
n = len(perm)
"""
Find k such that p[k] < p[k + l] and entries after index k appear in
decreasing order.
"""
for i in range(n - 1, -1, -1):
if not perm[i - 1] >= perm[i]:
break
# k refers to the inversion point
k = i - 1
# Permutation is already the max it can be
if k == -1:
return []
"""
Find the smallest p[l] such that p[l] > p[k]
(such an l must exist since p[k] < p[k + 1].
Swap p[l] and p[k]
"""
for i in range(n - 1, k, -1):
if not perm[k] >= perm[i]:
perm[i], perm[k] = perm[k], perm[i]
break
# Reverse the sequence after position k.
perm[k + 1 :] = reversed(perm[k + 1 :])
return perm
def multiset_permutation(A):
"""
We sort array first and `next_permutation()` will ensure we generate
permutations in lexicographic order
"""
A = sorted(A)
result = list()
while True:
result.append(A.copy())
A = next_permutation_helper(A)
if not A:
break
return result
输出:
>>> multiset_permutation([1, 1, 2, 2])
[[1, 1, 2, 2], [1, 2, 1, 2], [1, 2, 2, 1], [2, 1, 1, 2], [2, 1, 2, 1], [2, 2, 1, 1]]
您可以在此行使用join将可变列表的输出转换为字符串:
result.append("".join(map(str, A.copy())))
获得:
['1122', '1212', '1221', '2112', '2121', '2211']
答案 3 :(得分:0)
more-itertools.distinct_permutations(iterable)
产生可迭代中元素的连续的不同排列。
等同于
set(permutations(iterable))
,但重复项不是 生成并丢弃。对于较大的输入序列, 更有效率。
from more_itertools import distinct_permutations
for p in distinct_permutations('1122'):
print(''.join(p))
# 2211
# 2121
# 1221
# 2112
# 1212
# 1122
安装:
pip install more-itertools
答案 4 :(得分:0)
from more_itertools import distinct_permutations
x = [p for p in distinct_permutations(['M','I','S', 'S', 'I'])]
for item in x:
print(item)
输出:
('I', 'S', 'S', 'I', 'M')
('S', 'I', 'S', 'I', 'M')
('S', 'S', 'I', 'I', 'M')
('I', 'S', 'I', 'S', 'M')
('S', 'I', 'I', 'S', 'M')
('I', 'I', 'S', 'S', 'M')
('I', 'S', 'I', 'M', 'S')
('S', 'I', 'I', 'M', 'S')
('I', 'I', 'S', 'M', 'S')
('I', 'I', 'M', 'S', 'S')
('I', 'S', 'S', 'M', 'I')
('S', 'I', 'S', 'M', 'I')
('S', 'S', 'I', 'M', 'I')
('S', 'S', 'M', 'I', 'I')
('I', 'S', 'M', 'S', 'I')
('S', 'I', 'M', 'S', 'I')
('S', 'M', 'I', 'S', 'I')
('S', 'M', 'S', 'I', 'I')
('I', 'M', 'S', 'S', 'I')
('M', 'I', 'S', 'S', 'I')
('M', 'S', 'I', 'S', 'I')
('M', 'S', 'S', 'I', 'I')
('I', 'S', 'M', 'I', 'S')
('S', 'I', 'M', 'I', 'S')
('S', 'M', 'I', 'I', 'S')
('I', 'M', 'S', 'I', 'S')
('M', 'I', 'S', 'I', 'S')
('M', 'S', 'I', 'I', 'S')
('I', 'M', 'I', 'S', 'S')
('M', 'I', 'I', 'S', 'S')
答案 5 :(得分:0)
一个非常简单的解决方案,可能类似于more_itertools
所使用的解决方案,它利用@Brayoni所建议的字典排列顺序,可以通过建立一个可迭代的索引来完成。
假设您有L = '1122'
。您可以使用以下内容构建一个非常简单的索引:
index = {x: i for i, x in enumerate(sorted(L))}
假设您有P
的排列L
。 P
有多少个元素都没有关系。字典顺序表明,如果将P
映射为使用索引,则索引必须始终增加。像这样映射P
:
mapped = tuple(index[e] for e in p) # or tuple(map(index.__getitem__, p))
现在,您可以丢弃小于或等于到目前为止可见的最大值的元素:
def perm_with_dupes(it, n=None):
it = tuple(it) # permutations will do this anyway
if n is None:
n = len(it)
index = {x: i for i, x in enumerate(it)}
maximum = (-1,) * (len(it) if n is None else n)
for perm in permutations(it, n):
key = tuple(index[e] for e in perm)
if key <= maximum: continue
maximum = key
yield perm
请注意,除了保留最后一个最大项目之外,没有其他内存开销。如果愿意,可以与''
加入元组。