Pythonでリストの特定の順列を出力する
Sep 28 2020
リストのすべての順列について、特定のインデックスの値が前のインデックスの値よりも大きい順列のみを出力したいと思います。このようなインデックスは「グレートインデックス」と呼ばれます。例:リストがの場合[1,2,3]、その順列は次のとおりです。
(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)
「素晴らしいインデックス」がn個しかないような順列だけを印刷したいと思います。n = 2とすると、出力は次のようになります。
[1,3,2],[2,1,3] and [2,3,1]
では[1,3,2]、1(インデックス0)には前の要素がなく、3(インデックス1)は前の要素よりも大きいため、インデックス0と1は優れたインデックスです。つまり、1。2(インデックス2)は「優れたインデックス」ではありません。 "それは前の要素3より大きくないからです。同様に、では[2,1,3]、インデックス0と2は素晴らしいインデックスです。では[2,3,1]、インデックス0と1は優れたインデックスです。Pythonの順列ライブラリを使用して順列を生成しています。シンプルでわかりやすいソリューションをいただければ幸いです。
回答
1 IoaTzimas Sep 27 2020 at 23:38
これは機能するはずです:
import itertools
def great(l, n): #function that counts the permutations of list l with n great indices
def count_of_great(k): #function that counts the great indices of list k
c=1 #because first element is always great
for i in range(1,len(k)):
if k[i]>max(k[:i]): #if the value is greater than all previous values we increase c
c+=1
return c #this is the count of great indices in k
return [p for p in itertools.permutations(l) if count_of_great(p)==n] #this is a list of permutations of l that have a count_of_great eual with n
great([1,2,3], 2)
出力:
[(1, 3, 2), (2, 1, 3), (2, 3, 1)]