我需要获取排列,不包括镜像序列,即(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
您的问题已经说明了...wondering whether there is simpler solution
,我认为以下一个很简单:
def permutations_no_inverse(iterable):
found_items = []
for p in it.permutations(iterable):
if p not in found_items:
found_items.extend([p, p[::-1]])
else:
yield p
基于python延迟了最新列的反向元组订购,我们可以设想将排列设置为均匀矩阵,然后对角度进行分配,以获取矩阵的未刷新部分。
。 。
k=[1, 2, 3,4]
l=itertools.permutations(k)
a=list(l)
b=np.array(a).reshape((len(k),len(a)/len(k),len(k)))
neat_list=np.flipud(b)[np.tril_indices(len(k))]
这应该有效,我猜所有数组长度。
使用k=[1,2,3,4,5,6]
此打印
array([
[6, 1, 2, 3, 4, 5],
[5, 1, 2, 3, 4, 6],
[5, 1, 2, 3, 6, 4],
[4, 1, 2, 3, 5, 6],
[4, 1, 2, 3, 6, 5],
[4, 1, 2, 5, 3, 6],
[3, 1, 2, 4, 5, 6],
[3, 1, 2, 4, 6, 5],
[3, 1, 2, 5, 4, 6],
[3, 1, 2, 5, 6, 4],
[2, 1, 3, 4, 5, 6],
[2, 1, 3, 4, 6, 5],
[2, 1, 3, 5, 4, 6],
[2, 1, 3, 5, 6, 4],
[2, 1, 3, 6, 4, 5],
[1, 2, 3, 4, 5, 6],
[1, 2, 3, 4, 6, 5],
[1, 2, 3, 5, 4, 6],
[1, 2, 3, 5, 6, 4],
[1, 2, 3, 6, 4, 5],
[1, 2, 3, 6, 5, 4]])
我尝试了:
test=[list(g) for g in neat_list]
any([(u[::-1] in test) for u in test])
这将输出false
,这意味着在那里没有反向数组的出现。