Restart windowing for loop

Question:

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?

Asked By: zazzylele

||

Answers:

First of all you shouldn’t check if a[i] is 'Abel', you should check if the next element after the window is Abel, i.e. a[i+n].

Also you should increase i after you check for your condition.

Last, when you do encounter 'Abel', you should increase your iterator i by 3, to skip the window by 3 positions as you expect.

I hope this helps:

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])
  
  # Notice how I check a[i+n] does not get out of bounds.
  if i+n+1 < len(a) and a[i+n] == 'Abel':
      print()
      i += 3
      continue 
  i += 1
Answered By: Aristotelis V

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