Me gustaría generar una lista de todas las permutaciones de 4 dígitos donde:
Me gustaría saber:
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)))
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
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