简体   繁体   中英

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 ie 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.

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)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM