The following code tries all the divisors of the array length and then checks whether all sub-arrays are equal. Providing -1
as parameter in reshape(-1, k)
automatically calculates the correct dimension. (Note that the loop to get the divisors is quite simplistic, it could be sped up e.g. as in this post.)
import numpy as np
def find_repeat_length(num_array):
n = num_array.size
for k in range(1, n + 1):
if n % k == 0: # if k is a divisor of n
arr = num_array.reshape(-1, k)
if (arr == arr[0]).all(): # check wether all rows are equal to each other
return k
num_array_1 = np.array([1, 2, 3, 1, 2, 3, 1, 2, 3, 3, 2, 1, 3, 2, 1, 3, 2, 1, 1, 2, 3, 1, 2, 3, 1, 2, 3, 3, 2, 1, 3, 2, 1, 3, 2, 1, 1, 2, 3, 1, 2, 3, 1, 2, 3, 3, 2, 1, 3, 2, 1, 3, 2, 1, 1, 2, 3, 1, 2, 3, 1, 2, 3, 3, 2, 1, 3, 2, 1, 3, 2, 1, 1, 2, 3, 1, 2, 3, 1, 2, 3, 3, 2, 1, 3, 2, 1, 3, 2, 1, 1, 2, 3, 1, 2, 3, 1, 2, 3, 3, 2, 1, 3, 2, 1, 3, 2, 1, 1, 2, 3, 1, 2, 3, 1, 2, 3, 3, 2, 1, 3, 2, 1, 3, 2, 1, 1, 2, 3, 1, 2, 3, 1, 2, 3, 3, 2, 1, 3, 2, 1, 3, 2, 1, 1, 2, 3, 1, 2, 3, 1, 2, 3, 3, 2, 1, 3, 2, 1, 3, 2, 1])
num_array_2 = np.array([1, 2, 3, 3, 2, 1, 1, 5, 1, 2, 3, 3, 2, 1, 1, 5, 1, 2, 3, 3, 2, 1, 1, 5])
for num_array in (num_array_1, num_array_2):
rep_len = find_repeat_length(num_array)
print(f'repeat length is {rep_len}: {num_array[:rep_len]} repeated {len(num_array) // rep_len} times')
Result:
repeat length is 18: [1 2 3 1 2 3 1 2 3 3 2 1 3 2 1 3 2 1] repeated 9 times
repeat length is 8: [1 2 3 3 2 1 1 5] repeated 3 times