Electric Station問題3 Find Sequence
正方形のMatrixの中で4つ以上連続するものがあればTrue、なければFalseを返す関数を作ります。
行内か右下がりの方向で探して、次にMatrixを90度回転させてもう一回探すという方向性でプログラムを書いてみました。
def checkio1(test): for i in range(len(test)): for j in range(len(test)): if j <= len(test)-4: if test[i][j] == test[i][j+1] == test[i][j+2] == test[i][j+3]: return True if i <= len(test)-4 and j <= len(test)-4: if test[i][j] == test[i+1][j+1] == test[i+2][j+2] == test[i+3][j+3]: return True else: return False def checkio(test): return checkio1(test) or checkio1(list(map(list, zip(*test)))[::-1])
結構すっきりいった気がするが、最も人気の高かったものは、takapt0226さんのコードでrecursionの使い方がとても上手*1。こういう風に使えるようになりたい。
def checkio(matrix): N = len(matrix) def seq_len(x, y, dx, dy, num): if 0 <= x < N and 0 <= y < N and matrix[y][x] == num: return 1 + seq_len(x + dx, y + dy, dx, dy, num) else: return 0 DIR = [(0,1), (1,-1), (1,0), (1,1)] for y in range(N): for x in range(N-3): for dx, dy in DIR: if seq_len(x, y, dx, dy, matrix[y][x]) >= 4: return True return False
*1:好みで微変更してます