gpt4 book ai didi

python - 生成具有重复元素的列表排列

转载 作者:IT老高 更新时间:2023-10-28 21:03:05 26 4
gpt4 key购买 nike

在 Python 中,使用 itertools 模块生成列表的所有排列非常简单。我有一种情况,我使用的序列只有两个字符(即 '1122')。我想生成所有独特的排列。

对于字符串'1122',有6个唯一排列(112212121221、等),但 itertools.permutations 将产生 24 个项目。只记录唯一的排列很简单,但由于考虑了所有 720 项,因此收集它们所需的时间比必要的要长得多。

在生成排列时是否有一个函数或模块可以解释重复元素,这样我就不必自己编写了?

最佳答案

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-08-12

七年后,这里有一个更好的算法(为了清晰起见):

from itertools import permutations

def unique_perms(series):
return {"".join(p) for p in permutations(series)}

print(sorted(unique_perms('1122')))

关于python - 生成具有重复元素的列表排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4250125/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com