I've come across this post: How to generate all permutations of a list in Python
But I require something more, namely all of the permutations of a string as well as all the permutations of all the substrings. I know it's a big number, but is it possible?
To calculate permutations in Python, use the itertools. permutation() method. The itertools. permutations() method takes a list, dictionary, tuple, or other iterators as a parameter and returns the permutations of that list.
charAt(0); String st=s. substring(1); Set<String> qq=find(st); for(String str:qq) { for(int i=0;i<=str. length();i++) { ss. add(comb(str,c,i)); } } } return ss; } public static String comb(String s,char c,int i) { String start=s.
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 this is true permutations - as in, hello
will have any substring permutation that has two l
s in it twice, since the l
's will be considered "unique". If you wanted to get rid of that, you could pass it through a set()
:
all_permutations_no_dupes = set(all_permutations_substrings(a_str))
As the question you linked states, itertools.permutations is the solution for generating permutations of lists. In python, strings can be treated as lists, so itertools.permutations("text")
will work just fine. For substrings, you can pass a length into 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 one-line list comprehensions
list(itertools.chain.from_iterable([["".join(p) for p in itertools.permutations(text, l)] for l in range(1, len(text)+1)]))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With