Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python permutations including substrings

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?

like image 217
Anshu Dwibhashi Avatar asked Aug 25 '13 14:08

Anshu Dwibhashi


People also ask

How do you find the permutation of a number in Python?

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.

How do you make all combinations of a string?

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.


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 this is true permutations - as in, hello will have any substring permutation that has two ls 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))
like image 116
Amber Avatar answered Nov 02 '22 07:11

Amber


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)]))
like image 32
Fugiman Avatar answered Nov 02 '22 07:11

Fugiman