Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Second solution in Clear category for Find Sequence by colinmcnicholl
def has_sequence(a_list):
"""Input: a list of integers.
Function determines if there is a sequence of 4 or more matching digits.
Output: True or False.
"""
count = 1
for j in range(len(a_list) - 1):
if a_list[j] == a_list[j + 1]:
count += 1
if count >= 4:
return True
elif a_list[j] != a_list[j + 1]:
count = 1
return False
def checkio(matrix):
"""Input: A matrix as a list of lists with integers.
Check if there is a sequence of 4 or more matching digits.
The sequence may be positioned horizontally, vertically
or diagonally (NW-SE or NE-SW diagonals).
Output: Whether or not a sequence exists as a boolean.
"""
num_rows, num_cols = len(matrix), len(matrix[0])
rows = [[] for i in range(num_rows)]
cols = [[] for i in range(num_cols)]
ne_sw_diags = [[] for i in range(num_cols + num_rows - 1)]
nw_se_diags = [[] for i in range(len(ne_sw_diags))]
min_nw_se_diag = -num_rows + 1
for y in range(num_rows):
for x in range(num_cols):
rows[y].append(matrix[y][x])
cols[x].append(matrix[y][x])
ne_sw_diags[x + y].append(matrix[y][x])
nw_se_diags[-min_nw_se_diag + x - y].append(matrix[y][x])
row_results = [has_sequence(row) for row in rows]
col_results = [has_sequence(col) for col in cols]
bwd_diag_results = [has_sequence(diag) for diag in ne_sw_diags]
fwd_diag_results = [has_sequence(diag) for diag in nw_se_diags]
return (any(row_results) or any(col_results) or any(bwd_diag_results)
or any(fwd_diag_results))
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, "Vertical"
assert checkio([
[7, 1, 4, 1],
[1, 2, 5, 2],
[3, 4, 1, 3],
[1, 1, 8, 1]
]) == False, "Nothing here"
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, "Long Horizontal"
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, "Diagonal"
Feb. 7, 2019