Calculating the substrings of a string in Python -


i have simple string "abc". have write python code creating possible unique substrings, except empty string, string.

the answer should follows: b c ab ac bc abc

i wrote :

def getsubstrings(str):     sub = []     length = len(str)     in range(length):         j in range(i,length):             sub.append(str[i:j+1])     sub.sort()     return sub  str = "abc" print (getsubstrings(str)) 

but wrong way , since not giving expected results.

can please me efficient solution.

thanks in advance.

the build-in itertools library (https://docs.python.org/3.6/library/itertools.html) has wonderful functions can use. want possible combinations of letters, different length of strings.

so code sample below loops on size of string: (1,2,3), gets possible combinations particular size, , "chains", or appends them. functions itertools use iterators, means final answer isn't stored in memory, created when need values. larger strings use less ram.

from itertools import chain, combinations s='abc' list(chain(*[combinations(s,x) x in range(1,len(s)+1)]))  >>> [('a',), ('b',), ('c',), ('a', 'b'), ('a', 'c'), ('b', 'c'), ('a', 'b', 'c')] 

Comments

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -