Drucken Sie bestimmte Permutationen einer Liste in Python

Sep 28 2020

Für alle Permutationen einer Liste möchte ich nur die Permutationen drucken, bei denen der Wert an einem bestimmten Index größer ist als die Werte an vorherigen Indizes. Ein solcher Index würde als "großer Index" bezeichnet, z. B.: Wenn die Liste ist [1,2,3], sind ihre Permutationen

(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)

Ich möchte nur solche Permutationen drucken, in denen es nur n "große Indizes" gibt. Sagen wir n = 2, dann wäre die Ausgabe:

[1,3,2],[2,1,3] and [2,3,1]

In [1,3,2]sind die Indizes 0 und 1 großartige Indizes, da 1 (bei Index 0) keine vorherigen Elemente enthält und 3 (bei Index 1) größer als sein vorheriges Element ist, dh 1. 2 (bei Index 2) ist kein "großartiger Index" "weil es nicht größer als sein vorheriges Element 3 ist. In ähnlicher Weise sind In [2,1,3], Indizes 0 und 2 große Indizes. In [2,3,1]sind die Indizes 0 und 1 großartige Indizes. Ich verwende die Permutationsbibliothek in Python, um die Permutationen zu generieren. Eine einfache, leicht verständliche Lösung wäre wünschenswert.

Antworten

1 IoaTzimas Sep 27 2020 at 23:38

Das sollte funktionieren:

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)

Ausgabe:

[(1, 3, 2), (2, 1, 3), (2, 3, 1)]