Get list of all overlapping matches of 3 consecutive digits

Viewed 63

From '123456789' I want to find all (overlapping) matches of 3 consecutive numbers:

ListIWant = [123,234,345,456,567,678,789]

I tried:

print(re.compile(r"(\d){3}").findall('123456789'))

Output I currently get:

['3', '6', '9']

And also I want to know if there is something more efficient to count the number of matches instead of using len(ListIWant)

I'm learning English also, It will be grateful if you correct or suggest me better words/ways to express myself in this place.

2 Answers

Use a comprehension to build your list:

s = '123456789'
w = 3  # window size
l = [int(s[i:i+3]) for i in range(len(s) - w + 1)]
>>> l
[123, 234, 345, 456, 567, 678, 789]
a= '123456789'
ListIWant = []
for i, ele in enumerate(a):
    if i < len(a)-3:
        if (int(a[i+1]) == int(ele)+1) and (int(a[i+2]) == int(ele) + 2):
            ListIWant.append(int(ele+a[i+1]+a[i+2]))

    else:
        if (int(a[i+1]) == int(ele)+1) and (int(a[i+2]) == int(ele) + 2):
            ListIWant.append(int(ele+a[i+1]+a[i+2]))
        break

Output:

[123, 234, 345, 456, 567, 678, 789]
Related