Search code examples
pythonsubstringpermutationn-gram

Generate all possible substrings in sequence


I'm searching for a library or an efficient way to implement the following in Python

Input: 
"He was hungry"

Desired Output:
[["He","was","hungry"]
["He was","hungry"]
["He","was hungry"]
["He was hungry"]]

Solution

  • def f(a):
        if(len(a) == 0):
            yield []
        for i in range(len(a)):
            for c in f(a[i+1:]):
                yield [" ".join(a[:i+1]), *c]
    
    
    s = "He was hungry"
    print(list(f(s.split())))
    
    [['He', 'was', 'hungry'], ['He', 'was hungry'], ['He was', 'hungry'], ['He was hungry']]