Safiya Hamid
Safiya Hamid

Reputation: 53

Print specific Permutations of a list in Python

For all the permutations of a list, I want to print only those permutations in which the value at a particular index is greater than the values at previous indexes. Such an index would be called a "great index" ex: If the list is [1,2,3], its permutations are

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

I would like to print only such permutations in which there are only n "great indices". Let's say n=2, then the output would be:

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

In [1,3,2], indices 0 and 1 are great indices because 1(at index 0) does not have any previous elements and 3(at index 1) is greater than its previous element i.e 1. 2(at index 2) is not a "great index" because it is not greater than its previous element 3. Similarly, In [2,1,3], indices 0 and 2 are great indices. In [2,3,1], indices 0 and 1 are great indices. I'm using the permutations library in Python to generate the permutations. A simple, easy to understand solution would be appreciated.

Upvotes: 2

Views: 381

Answers (1)

IoaTzimas
IoaTzimas

Reputation: 10624

This should work:

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)

Output:

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

Upvotes: 1

Related Questions