-2

I have a list with values:

i_have = [1,1,1,4,4,4,4,4,4,4,1,1,1,1,4,4,4,4,3,3,4,3]

and I need to find the start and end indices for every chunk of the list with the value 4. If there's a 4 alone, like the second to last value of this list, its start and end indices should be the same.

i_need = [(3, 9), (14, 17), (20, 20)]

Can you help me with this?

Paca
  • 69
  • 7
  • 1
    We can only help you if you show us what you have coded so far. We will help you with what you have written; we will not write your code for you. You are toe only one who can write your own code. – rossum Oct 23 '22 at 20:53

2 Answers2

0
l = [1,1,1,4,4,4,4,4,4,4,1,1,1,1,4,4,4,4,3,3,4,3]
u = []
c = 0
start = None
end = None
for num, item in enumerate(l):
    if item == 4:
        if c == 0:
            start = num
        c +=1
        if num == len(l)-1:
            end = num
    else:
        if c != 0:
            end = num- 1
        c=0
    if start != None and end != None:
        u.append((start, end))
        start = None
        end = None
print(u)
Nick
  • 154
  • 4
0

Alternatively, you could try to leverage the power of re module like this:

Then you can try to put all into the final answer format.

# First - you need to convert the List to String:
S = ''.join(str(x) for x in L)

# '1114444444111144443343'

for m in re.finditer(r"4+", S): 
    print('%02d-%02d' % (m.start(), m.end()))

Output:

                       
03-10
14-18
20-21

final answer will be:

outs = [] 
for m in re.finditer('4+', S):
    outs.append((m.start(), m.end()-1))
[(3, 9), (14, 17), (20, 20)]
Daniel Hao
  • 4,922
  • 3
  • 10
  • 23