Home > Backend Development > Python Tutorial > How Can I Generate Permutations in Python?

How Can I Generate Permutations in Python?

Linda Hamilton
Release: 2024-12-24 04:58:31
Original
849 people have browsed it

How Can I Generate Permutations in Python?

Generating Permutations Using Python Libraries

To generate all permutations of a list in Python, a convenient approach involves utilizing the itertools.permutations function from the standard library. For instance:

import itertools
list(itertools.permutations([1, 2, 3]))
Copy after login

Custom Implementation of Permutations

Alternatively, you can create a custom implementation to calculate permutations:

def permutations(elements):
    if len(elements) <= 1:
        yield elements
        return
    for perm in permutations(elements[1:]):
        for i in range(len(elements)):
            yield perm[:i] + elements[0:1] + perm[i:]
Copy after login

Other Approaches

If you prefer, you can also explore the following approaches:

# Using reversed indices
def permutations(iterable, r=None):
    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

# Using product
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)
Copy after login

The above is the detailed content of How Can I Generate Permutations in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template