• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

369
Vistas
Permutations without reversed sequences in Python

I would like to generate a list of all permutations of 4 digits where :

  • All 4 digits are always present
  • Two reversed sequences are the same solution. For example. (1,2,3,4) = (4,3,2,1)

I would like to know:

  • What do you call this kind of permutations.
  • If it is possible to generate this list in one step. Below there is an example that generates it in two steps.
import itertools
inp_list = range(1, 5)

# 1. Create the list of all permutations.
permutations = list(itertools.permutations(inp_list))

# 2. Remove sequences that are the reverse of another.
for _p in permutations[::-1]:
    if _p[::-1] in permutations:
        permutations.remove(_p)

for _p in permutations:
    print("\t".join(map(str, _p)))
over 3 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

To simplify your code and make it more efficient you could:

1- use a python set as the container (checking the presence of an element is much faster)

2- add the final output directly

3- avoid to create a temporary list with the permutations, keep it as a generator

from itertools import permutations
inp_list = range(1, 5)

out = set()
for p in permutations(inp_list): # loop over generator output
    p = '\t'.join(map(str,p))    # craft the desired output format
    if not p[::-1] in out:       # is the reverse not already in the set?
        out.add(p)               # then add the item
        print(p)                 # and print it

output:

1   2   3   4
1   2   4   3
1   3   2   4
1   3   4   2
1   4   2   3
1   4   3   2
2   1   3   4
2   1   4   3
2   3   1   4
2   4   1   3
3   1   2   4
3   2   1   4
over 3 years ago · Santiago Trujillo Denunciar

0

You could just use the smaller one of each reversal pair:

from itertools import permutations

for p in permutations(range(1, 5)):
    if p < p[::-1]:
        print(*p)

Output:

1 2 3 4
1 2 4 3
1 3 2 4
1 3 4 2
1 4 2 3
1 4 3 2
2 1 3 4
2 1 4 3
2 3 1 4
2 4 1 3
3 1 2 4
3 2 1 4
over 3 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda