寻找更好的解决方案,以顺时针方向检索2D数组中的值,检索值并添加到一维数组中。
board = [[1, 4, 0, 5, 0],
[0, 7, 3, 0, 0],
[0, 6, 0, 9, 0],
[0, 0, 0, 2, 0]]
函数corkscrew()
,给定一个二维整数列表,
显示每个方格中的当前玩家
左上方到中心,顺时针方向:
"""
+------------------+
|
+--------------+ |
| | |
| +------> | |
| | | |
| +----------+ |
| |
+------------------+
"""
For example, given the board array the function should return the following list:
[1, 4, 0, 5, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 7, 3, 0, 9, 0, 6]
当前解决方案:
def get_row(board, index):
"""Generator to return the row value at the specified
index(i.e column value)."""
try:
for v in board.pop(index):
yield v
except IndexError:
raise StopIteration
def get_column(board, index):
for row in board:
try:
yield row.pop(index)
except IndexError:
raise StopIteration
def get_values(board):
"""Generator to return the values in a specific row."""
start = 0
operations = ['right', 'down', 'left', 'up'] * 2 + ['right']
for operation in operations:
row = []
if operation == 'right':
row = list(get_row(board, start))
start = len(row) - 1
elif operation == 'down':
row = list(get_column(board, start))
start = len(row)
elif operation == 'left':
row = list(reversed(list(get_row(board, start - 1))))
elif operation == 'up':
if board and board[0]:
start = start + 1 - len(board[0])
row = get_column(board, start)
for v in row:
yield v
def corkscrew(board):
"""Returns one dimensional array in going clockwise."""
new_board = []
# Clockwise pattern
values = get_values(board)
new_board.extend(values)
return new_board