Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading