'How do I split a list of words into all possible sub sentences? Python

For example, if i had a list of words: ["Hi", "my", "name" "is"] How would i get the output: [ "Hi", "Hi my", "Hi my name", "Hi my name is", "my", "my name", "my name is", "name", "name is", "is" ]

I understand it would use some sort of for loop but cannot figure how to iterate through it to get exactly this output.



Solution 1:[1]

This is an example of a possible algorithm in JS.

array = ["Hi", "my", "name", "is"]
arrayFinal = []

for (let i = 0; i < array.length; i++) {
    for (let j = i; j < array.length; j++) {
        arrayFinal.push(array.slice(i, j+1).toString().replace(/,/g, " "))
    }
}

console.log(arrayFinal)
return arrayFinal
// output: ['Hi', 'Hi my', 'Hi my name', 'Hi my name is', 'my', 'my name', 'my name is', 'name', 'name is', 'is']

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Zedki