pythonfor-loopwhile-loopwindowing

Restart windowing for loop


I have a list of strings, and I want to window them 'n' at a time. The window should re-start every time it encounters a certain string. This is the code I used:

i = 0
a = ['Abel', 'Bea', 'Clare', 'Abel', 'Ben', 'Constance', 'Dave', 'Emmet', 'Abel', 'Bice', 'Carol', 'Dennis']
n=3  
while i in range(len(a)-n+1):
  print('Window :', a[i:i+n])
  i += 1
  if a[i] == 'Abel':
      print()
      continue 

and the output I get is:

Window : ['Abel', 'Bea', 'Clare']
Window : ['Bea', 'Clare', 'Abel']
Window : ['Clare', 'Abel', 'Ben']

Window : ['Abel', 'Ben', 'Constance']
Window : ['Ben', 'Constance', 'Dave']
Window : ['Constance', 'Dave', 'Emmet']
Window : ['Dave', 'Emmet', 'Abel']
Window : ['Emmet', 'Abel', 'Bice']

Window : ['Abel', 'Bice', 'Carol']
Window : ['Bice', 'Carol', 'Dennis']

while I would like it to re-start windowing every time 'Abel' comes into a position that isn't first, like:

#Expected result
Window : ['Abel' , 'Bea', 'Clare']

Window : ['Abel', 'Ben', 'Constance']
Window : ['Ben', 'Constance', 'Dave']
Window : ['Constance', 'Dave', 'Emmet']

Window : ['Abel', 'Bice', 'Carol']
Window : ['Bice', 'Carol', 'Dennis']

What am I getting wrong?


Solution

  • This is the solution

    data = [
        "Abel",
        "Bea",
        "Clare",
        "Abel",
        "Ben",
        "Constance",
        "Dave",
        "Emmet",
        "Abel",
        "Bice",
        "Carol",
        "Dennis",
    ]
    
    data_size = len(data)
    window_size = 3
    restart_match_value = "Abel"
    
    i = 0
    j = 0
    
    while i < data_size - window_size + 1:
        window = []
        should_restart = False
        for j in range(i, i + window_size):
            window.append(data[j])
            if len(window) > 1 and data[j] == restart_match_value:
                should_restart = True
                i = j - 1
        if should_restart:
            print()
        else:
            print("Window:", window)
        i += 1