Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Get All The Contiguous Substrings Of A String In Python?

Here is my code, but I want a better solution, how do you think about the problem?

def get_all_substrings(string):   length = len(string)   alist = []   for i in xrange(length):     for j in xrange(i,length):       alist.append(string[i:j + 1])    return alist  print get_all_substring('abcde') 
like image 807
lqhcpsgbl Avatar asked Mar 18 '14 03:03

lqhcpsgbl


People also ask

How do you find all substrings in a string in Python?

Method #2 : Using itertools.combinations() This particular task can also be performed using the inbuilt function of combinations, which helps to get all the possible combinations i.e the substrings from a string.

How do I generate all subsequences of a string in Python?

A String is a subsequence of a given String, that is generated by deleting some character of a given string without changing its order. Recommended: Please try your approach on {IDE} first, before moving on to the solution. Using Pick and Don't Pick concept : Python3.

Is there a way to print all substrings of a string in O n time?

No there isn't. It is mathematically impossible. There are O(N^2) substrings of a string of length N . You cannot print O(N^2) strings in O(N) time.


1 Answers

The only improvement I could think of is, to use list comprehension like this

def get_all_substrings(input_string):   length = len(input_string)   return [input_string[i:j+1] for i in xrange(length) for j in xrange(i,length)]  print get_all_substrings('abcde') 

The timing comparison between, yours and mine

def get_all_substrings(string):   length = len(string)   alist = []   for i in xrange(length):     for j in xrange(i,length):       alist.append(string[i:j + 1])    return alist  def get_all_substrings_1(input_string):   length = len(input_string)   return [input_string[i:j + 1] for i in xrange(length) for j in xrange(i,length)]  from timeit import timeit print timeit("get_all_substrings('abcde')", "from __main__ import get_all_substrings") # 3.33308315277 print timeit("get_all_substrings_1('abcde')", "from __main__ import get_all_substrings_1") # 2.67816185951 
like image 84
thefourtheye Avatar answered Sep 21 '22 23:09

thefourtheye