我有一个按升序排列的具有以下值的列表。
l1 = 1,3,9
有6个可能的排列,每个置换的长度是l1的长度。
(1, 3, 9)
(1, 9, 3)
(3, 1, 9)
(3, 9, 1)
(9, 1, 3)
(9, 3, 1)我需要删除所有按照l1命令排列的排列。
1,3,9,3与l1中的顺序匹配。
9,1,3,3与l1中的顺序匹配。
3,9,1,3,9与l1中的顺序匹配。
答案应该是6-3 =3 Mycode:
from itertools import permutations
l = [1,3,9]
perm = permutations(l, len(l))
res = []
for i in list(perm):
res.append(i)
for i in res:
for j in range(0,len(i)):
if i[j] and i[j+1] in l[j]:
res.remove(i)
print(len(res))我发现输入错误。如何修复这个问题,以及如何修复if语句
发布于 2019-06-14 15:46:43
您可以根据原始数据创建相邻元组,并检查您的排列中是否有任何元组位于原始数据的列表中--只有在没有的情况下:添加到结果:
from itertools import permutations
l = [1,3,9]
# create all neighbor-tuples
tups = set(zip(l,l[1:]))
perm = list(permutations(l, len(l)))
print("perm: ", perm)
res = []
print("tups: ", list(tups))
for i in perm:
itups = zip(i,i[1:]) # create neighbor tuples from this permutation
if any( t in tups for t in itups):
continue
res.append(i)
print(len(res))
print(res)输出:
perm: [(1, 3, 9), (1, 9, 3), (3, 1, 9), (3, 9, 1), (9, 1, 3), (9, 3, 1)]
tups: [(3, 9), (1, 3)]
3
[(1, 9, 3), (3, 1, 9), (9, 3, 1)]文档:
https://stackoverflow.com/questions/56601365
复制相似问题