• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

384
Views
Permutaciones sin secuencias invertidas en Python

Me gustaría generar una lista de todas las permutaciones de 4 dígitos donde:

  • Los 4 dígitos están siempre presentes
  • Dos secuencias invertidas son la misma solución. Por ejemplo. (1,2,3,4) = (4,3,2,1)

Me gustaría saber:

  • ¿Cómo se llama este tipo de permutaciones?
  • Si es posible generar esta lista en un solo paso. A continuación hay un ejemplo que lo genera en dos pasos.
 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 answers
Answer question

0

Para simplificar su código y hacerlo más eficiente, podría:

1- use un conjunto de python como contenedor (comprobar la presencia de un elemento es mucho más rápido)

2- agregue la salida final directamente

3- evita crear una lista temporal con las permutaciones, mantenla como generador

 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

producción:

 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 Report

0

Podrías usar el más pequeño de cada par de inversión:

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

Producción:

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error