Welcome to the forums. This is not a ‘do my work’ forum, so you’ll usually get better responses if you show what you’ve attempted so far so that other users can guide you on ways to improve your script.
In this case, I think it’ll be of immediate benefit to start thinking of terms and phrases to use in the search tool.
This thread should be what you are looking to do, I came across it by looking up “Grouping”, “Consecutive”, “Repeated”, and “Sequential” until something that matched the problem was found.
Same script as the link, but with nodes grouped and explained