Python permutations, including substrings

I came across this post: How to generate all list permutations in Python

But I need something more, namely all permutations of the string, as well as all permutations of all substrings. I know this a lot, but is it possible?

+4
source share
2 answers
import itertools def all_permutations_substrings(a_str): return ( ''.join(item) for length in xrange(1, len(a_str)+1) for item in itertools.permutations(a_str, length)) 

Note, however, that these are true permutations - as in, hello will have any substring that has two l in it twice, since l will be considered "unique". If you want to get rid of this, you can pass it through set() :

 all_permutations_no_dupes = set(all_permutations_substrings(a_str)) 
+3
source

As a status issue related to you, itertools.permutations is a solution for generating list permutations. In python, strings can be thought of as lists, so itertools.permutations("text") will work fine. For substrings, you can pass the length to itertools.permutations as an optional second argument.

 def permutate_all_substrings(text): permutations = [] # All possible substring lengths for length in range(1, len(text)+1): # All permutations of a given length for permutation in itertools.permutations(text, length): # itertools.permutations returns a tuple, so join it back into a string permutations.append("".join(permutation)) return permutations 

Or if you prefer single-line lists

 list(itertools.chain.from_iterable([["".join(p) for p in itertools.permutations(text, l)] for l in range(1, len(text)+1)])) 
+1
source

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


All Articles