Python all data combinations

So, I have a file structure like this (data on each line):

A B C ... 

I want to read every line of this file and combine them into all possible combinations, the result I'm looking for will be like that (which I would put in the list):

 A AB AC ABC ACB B BA BC BCA BAC C CA CB CBA CAB 

Obviously, I would like to deal not only with these three lines ...

thanks

+4
source share
1 answer

You should use the itertools library. You want to generate all the unique permutations of each element in the force set. Some code may look like

 from itertools import permutations, combinations, chain # Taken from itertools page, but edited slightly to not return empty set def powerset(iterable): "powerset([1,2,3]) --> (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" s = list(iterable) return chain.from_iterable(combinations(s, r) for r in range(1, len(s)+1)) 

Then

 In [1]: s = ('A', 'B', 'C') In [2]: [j for i in powerset(s) for j in permutations(i)] Out[2]: [('A',), ('B',), ('C',), ('A', 'B'), ('B', 'A'), ('A', 'C'), ('C', 'A'), ('B', 'C'), ('C', 'B'), ('A', 'B', 'C'), ('A', 'C', 'B'), ('B', 'A', 'C'), ('B', 'C', 'A'), ('C', 'A', 'B'), ('C', 'B', 'A')] 
+5
source

Source: https://habr.com/ru/post/1498857/


All Articles