How to find repeated patterns of numbers in the rows of a matrix with Python

1 Answer

0 votes
def find_repeating_patterns(matrix, pattern_size):
    pattern_map = {}
 
    for row_index, row in enumerate(matrix):
        for col in range(len(row) - pattern_size + 1):
            pattern = "-".join(map(str, row[col:col + pattern_size]))
 
            if pattern not in pattern_map:
                pattern_map[pattern] = set()
            pattern_map[pattern].add(row_index)
 
    print("Repeated Patterns Found:")
    for pattern, rows in pattern_map.items():
        if len(rows) > 1:
            print(f"{pattern} appears {len(rows)} times in rows: {' '.join(map(str, rows))}")
 
 
matrix = [
    [1, 2, 3, 8, 9, 7, 4, 9, 6],
    [1, 3, 2, 7, 8, 9, 4, 5, 6],
    [1, 2, 3, 8, 6, 1, 4, 9, 8],
    [1, 2, 3, 0, 8, 8, 4, 5, 9],
    [1, 2, 3, 4, 5, 6, 7, 8, 9],
    [1, 2, 3, 7, 0, 9, 4, 5, 7],
    [1, 3, 2, 4, 5, 6, 7, 8, 9]
]
 
pattern_size = 3  # Looking for sequences of 3 numbers
 
find_repeating_patterns(matrix, pattern_size)
 
 
 
'''
run:
 
Repeated Patterns Found:
1-2-3 appears 5 times in rows: 0 2 3 4 5
2-3-8 appears 2 times in rows: 0 2
1-3-2 appears 2 times in rows: 1 6
7-8-9 appears 3 times in rows: 1 4 6
9-4-5 appears 2 times in rows: 1 5
4-5-6 appears 3 times in rows: 1 4 6
5-6-7 appears 2 times in rows: 4 6
6-7-8 appears 2 times in rows: 4 6
 
'''

 



answered May 25, 2025 by avibootz
edited May 25, 2025 by avibootz
...