我需要获得排列,排除镜像序列,即应包含 (1, 0, 4),但之后应排除 (4, 0, 1)。 我想出了以下功能,但想知道是否有更简单的解决方案。
该函数根据逆元的最后一个元素与相应序列的第一个元素相同的事实跳过逆元,该序列已经按照给定的字典顺序进行了处理。
def permutations_no_inverse(iterable):
"""Return the half of permutations, treating mirrored sequences as the same,
e.g. (0, 1, 2) and (2, 1, 0) are the same.
Assume itertools.permutations returns tuples
"""
all_perm = it.permutations(iterable)
cur_start = None
starts_processed = set()
for perm in all_perm:
new_start = perm[0]
if new_start != cur_start:
if cur_start != None:
starts_processed.add(cur_start)
cur_start = new_start
if perm[-1] in starts_processed:
continue
else:
yield perm
最佳答案
假设iterable
中的条目是唯一且可排序的,我将简单地比较排列的任意两个元素(例如第一个和最后一个),并且仅包括第一个元素较少的那些排列或等于最后一个元素。这样,您就不需要存储已经看到的内容,也不必关心 itertools.permutations()
返回排列的顺序。
示例代码:
def permutations_no_inverse(iterable):
for p in itertools.permutations(iterable):
if p[0] <= p[-1]:
yield p
关于python - 不包括逆的排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46342793/