简体   繁体   中英

How to generate increasing permutations of a list in Python without itertools.combinations

How to generate increasing permutations of a list in Python without itertools.combinations:

I'm trying to create a function that will produce all permutations of a list but limited to only sets of len(n) and only increasing from left to right. For instance, if I have list l = [2,4,5,7,9] and n=4, the results should include [2,4,5,7], [2,4,7,9], [2,5,7,9] but not [9,7,4,2], [9,4,7,2]. This is what I have done so far:

def permutation(lst):

    if len(lst) == 0:
        return []

    if len(lst) == 1:
        return [lst]

    l = []

    for i in range(0, len(lst)):
       m = lst[i]

       new = lst[:i] + lst[i+1:]

       for p in permutation(new):
           l.append([m] + p)
    return l

test:

data = list([1,2,3,4,5,6])
for p in permutation(data):
    print p

What you're describing is exactly what itertools.combinations does:

from itertools import combinations
l = [2,4,5,7,9]
n = 4
for c in combinations(l, n):
    print(list(c))

This outputs:

[2, 4, 5, 7]
[2, 4, 5, 9]
[2, 4, 7, 9]
[2, 5, 7, 9]
[4, 5, 7, 9]

But if you do not want to actually use itertools.combinations , you can refer to how it can be implemented in Python in the documentation :

def combinations(iterable, r):
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = list(range(r))
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)

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