Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
numpy.diag + itertools.groupby solution in 3rd party category for Find Sequence by slchangtw
from typing import List
from itertools import groupby
import numpy as np
def _is_sequence(l, n_consecutive=4):
return any(len(list(group)) >= n_consecutive for _, group in groupby(l))
def _get_diags(matrix):
size = matrix.shape[0]
diags = [matrix.diagonal(i) for i in range(-(size - 1), size)]
diags.extend(matrix[::-1].diagonal(i) for i in range(-(size - 1), size))
return diags
def checkio(matrix: List[List[int]]) -> bool:
matrix = np.array(matrix)
return (
any(_is_sequence(row) for row in matrix)
or any(_is_sequence(row) for row in matrix.T)
or any(_is_sequence(diag) for diag in _get_diags(matrix))
)
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert checkio([
[1, 2, 1, 1],
[1, 1, 4, 1],
[1, 3, 1, 6],
[1, 7, 2, 5]
]) == True
assert checkio([
[7, 1, 4, 1],
[1, 2, 5, 2],
[3, 4, 1, 3],
[1, 1, 8, 1]
]) == False
assert checkio([
[2, 1, 1, 6, 1],
[1, 3, 2, 1, 1],
[4, 1, 1, 3, 1],
[5, 5, 5, 5, 5],
[1, 1, 3, 1, 1]
]) == True
assert checkio([
[7, 1, 1, 8, 1, 1],
[1, 1, 7, 3, 1, 5],
[2, 3, 1, 2, 5, 1],
[1, 1, 1, 5, 1, 4],
[4, 6, 5, 1, 3, 1],
[1, 1, 9, 1, 2, 1]
]) == True
print('All Done! Time to check!')
July 31, 2022