Muhamed Al Khalil
Muhamed Al Khalil

Reputation: 357

Getting all possible list slices that include a specific item

I am trying to find all the list slices that includes a specific item. Let's say I have a list w made of five morphemes, one of which is the stem stem for which I would like to find every possible slice that includes it. Here is the code I wrote for that:

stem = 'stm'
w = ['a', 'b', stem, 'c', 'd']
w2 = w
stem_index = w.index(stem)
stem_slice1 = w[stem_index:]
stem_slice2 = w[:stem_index + 1]
slices = []

while len(w) > 0:
    w = w[:-1] # chops the last item
    if stem in w and w not in slices:
        slices.append(w)

    w_ = w[1:] # then chops the first item
    if stem in w_ and w_ not in slices:
        slices.append(w_)

    w2 = w2[1:] # chops the first item
    if stem in w2 and w2 not in slices:
        slices.append(w2)

    w2_ = w2[:-1] # then chops the last item
    if stem in w2_ and w2_ not in slices:
        slices.append(w2_)

while len(stem_slice1) > 0:
    stem_slice1 = stem_slice1[:-1]
    if stem in stem_slice1 and stem_slice1 not in slices:
        slices.append(stem_slice1)

while len(stem_slice2) > 0:
    stem_slice2 = stem_slice2[1:]
    if stem in stem_slice2 and stem_slice2 not in slices:
        slices.append(stem_slice2)

print (slices)

When run, this code prints:

[['a', 'b', 'stm', 'c'], ['b', 'stm', 'c'], ['b', 'stm', 'c', 'd'], ['a', 'b', 'stm'], ['b', 'stm'], ['stm', 'c', 'd'], ['stm', 'c'], ['stm']]

It seems to work fine, but I am wondering if there is a more Pythonic way to do the same.

Upvotes: 0

Views: 59

Answers (1)

Kevin
Kevin

Reputation: 76234

Just getting the Cartesian product of all valid start and end indices should do it. In other words, two for loops are sufficient.

stem = 'stm'
w = ['a', 'b', stem, 'c', 'd']
idx = w.index(stem)
slices = []
for start in range(idx+1):
    for end in range(idx+1, len(w)+1):
        slices.append(w[start:end])
print(slices)

Result:

[['a', 'b', 'stm'], ['a', 'b', 'stm', 'c'], ['a', 'b', 'stm', 'c', 'd'], ['b', 'stm'], ['b', 'stm', 'c'], ['b', 'stm', 'c', 'd'], ['stm'], ['stm', 'c'], ['stm', 'c', 'd']]

Upvotes: 4

Related Questions