python-checkio/ElectronicStation/find-sequence.py

93 lines
2.3 KiB
Python
Raw Normal View History

2019-12-18 17:30:47 +01:00
def checkio(matr):
"""
Given the matrix NxN (4<=N<=10). Check if 4 numbers in sequence in a column or in a row or diagonally exist.
"""
for r in matr: # horizontal
if checkline(r):
return True
for r in zip(*matr): # vertical
if checkline(r):
return True
print(matr)
for r in range(0, len(matr)): # diagonal
for c in range(0, len(matr[0])):
ret = []
rx = r
cx = c
while True:
print('r = ', str(rx))
print('c = ', str(cx))
ret.append(matr[rx][cx])
rx = rx + 1
cx = cx + 1
if cx >= len(matr[0]) or rx >= len(matr):
break
if checkline(ret):
return True
return False
def checkline(l):
c = 0
p = ''
for x in l:
if p == '':
p = x
c = 1
continue
if p == x:
c += 1
if c >= 4:
return True
else:
c = 0
p = x
return False
# len([x for x in l if l.count(x) == 4]) > 0
if __name__ == '__main__':
assert checkio([
[1, 1, 1, 1],
[1, 2, 3, 4],
[5, 4, 3, 1],
[6, 1, 3, 2]
]) == True, "First, horizontal"
assert checkio([
[7, 6, 5, 7, 9],
[8, 7, 3, 6, 5],
[4, 0, 6, 5, 4],
[9, 8, 4, 0, 5],
[2, 10, 7, 2, 10]
]) == False, "Second"
assert checkio([
[10, 1, 9, 6, 4, 1],
[2, 5, 4, 2, 2, 7],
[2, 2, 1, 2, 6, 4],
[3, 2, 2, 1, 0, 2],
[7, 9, 6, 2, 5, 7],
[7, 3, 10, 5, 6, 2]
]) == True, "Third"
assert checkio([
[6, 6, 7, 7, 7],
[1, 7, 3, 6, 5],
[4, 1, 2, 3, 2],
[9, 0, 4, 0, 5],
[2, 0, 7, 5, 10]
]) == False, "fourth"
assert checkio([
[1, 1, 1, 6, 1, 1, 1],
[2, 5, 4, 2, 2, 7, 2],
[2, 6, 1, 2, 6, 4, 3],
[3, 2, 2, 1, 0, 2, 4],
[7, 9, 6, 2, 5, 7, 5],
[7, 3, 10, 5, 6, 2, 5],
[7, 3, 10, 5, 6, 2, 5]
]) == False, "Fifth"
assert checkio([
[1, 1, 3, 1],
[1, 2, 3, 4],
[5, 4, 3, 1],
[6, 1, 3, 2]
]) == True, "Six, vertircal"