To obtain all possible permutations from a list

Asked 2 years ago, Updated 2 years ago, 46 views

How do we find all possible permutations as elements of the list?

For example,

permutations([1, 2]) -> [1, 2] [2, 1]

permutations([1, 2, 3]) -> [1, 2, 3] [1, 3, 2] [2, 1, 3] [2, 3, 1] [3, 1, 2] [3, 2, 1]

What should I do to save him like this?

algorithm python permutation combinatorics python-2.5

2022-09-22 22:27

1 Answers

Python 2.6 and later supports this feature with itertools.permutations() and above.

itertools.permutations(iterable[,r]) returns a permutation of r that can be made available.
If r is not specified, r is set to the length of enable.

import itertools
mylist = [1,2,3]
mypermuatation =  itertools.permutations(mylist)
for i in mypermuatation:
    print i

Result:

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

If it's below 2.6, you have no choice but to make it yourself. The method I recommend is

def all_perms(elements):
    if len(elements) <=1:
        yield elements
    else:
        for perm in all_perms(elements[1:]):
            for i in range(len(elements)):
                # # nb elements[0:1] works in both string and list contexts
                yield perm[:i] + elements[0:1] + perm[i:]

Or

#2.7.11 documentation - https://docs.python.org/2.7/library/itertools.html?highlight=permutations#itertools.permutations

def permutations(iterable, r=None):
    # # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
    # # permutations(range(3)) --> 012 021 102 120 201 210
    pool = tuple(iterable)
    n = len(pool)
    r = n if r is None else r
    if r > n:
        return
    indices = range(n)
    cycles = range(n, n-r, -1)
    yield tuple(pool[i] for i in indices[:r])
    while n:
        for i in reversed(range(r)):
            cycles[i] -= 1
            if cycles[i] == 0:
                indices[i:] = indices[i+1:] + indices[i:i+1]
                cycles[i] = n - i
            else:
                j = cycles[i]
                indices[i], indices[-j] = indices[-j], indices[i]
                yield tuple(pool[i] for i in indices[:r])
                break
        else:
            return

Or

def permutations(iterable, r=None):
    pool = tuple(iterable)
    n = len(pool)
    r = n if r is None else r
    for indices in product(range(n), repeat=r):
        if len(set(indices)) == r:
            yield tuple(pool[i] for i in indices)


2022-09-22 22:27

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.