def jump_left(markers, row, column):
"""
Returns the grid that results after the marker at (row, column) jumps left
@type markers: list[list[str]]
@type row: int
@type column: int
@rtype: list[GridPegSolitairePuzzle]
>>> grid = [["*", "*", "*", "*", "*"]]
>>> grid.append(["*", "*", "*", "*", "*"])
>>> grid.append(["*", "*", "*", "*", "*"])
>>> grid.append(["*", "*", ".", "*", "*"])
>>> grid.append(["*", "*", "*", "*", "*"])
>>> gpsp1 = GridPegSolitairePuzzle(grid, {"*", ".", "#"})
>>> L1 = jump_left(gpsp1._marker, 3, 4)
>>> grid[3][2] = "*"
>>> grid[3][3] = "."
>>> grid[3][4] = "."
>>> L2 = [GridPegSolitairePuzzle(grid, {"*", ".", "#"})]
>>> L1 == L2
True
"""
# Checking bounds and whether the right pieces are in the positions needed
if (column - 2) >= 0 and (markers[row][column - 2] == ".") and\
(markers[row][column - 1] == "*"):
# Each row must be copied individually (since they are all lists)
m_copy = []
for i in range(len(markers)):
m_copy.append(markers[i].copy())
new_grid = GridPegSolitairePuzzle(m_copy, {"*", ".", "#"})
# Performs the jump
new_grid._marker[row][column] = "."
new_grid._marker[row][column - 1] = "."
new_grid._marker[row][column - 2] = "*"
return [new_grid]
else:
return []
我的程序应该移动由' *'表示的挂钩。然后跳到空位('。')并移除它们之间的挂钩。
所以对于上面的docstring:r1会变成
["*", "*", ".", "."]
我的代码适用于显示的文档字符串但是r1 = ["*", "*", ".", "*"]
和r3 = ["*", ".", "*", "*"]
。
它应该交换r3元素,但它不起作用(我知道我不会遍历每个空位,但我无法找到一种方法)
还有一种更好的方法可以在索引范围之外做。我正在尝试,除了阻止,因为如果空位置在第3列,它会给我索引超出范围,因为我正在寻找它旁边的钉子
答案 0 :(得分:0)
目前,您的代码只会向左跳转。它也不会垂直跳跃。
你还需要能够做self.marker [r] [c - {1,2}]和self.marker [r + - {1,2} [c]转换。
实际上,“跳转”操作可能应该是它自己的功能,以便稍微简化这段代码。
答案 1 :(得分:0)
我会使循环范围变小,以避免索引超出范围。 因为你不能将任何挂钩跳到最右边的两个地方,所以不需要检查那些。通过这种方式,您不必担心超出范围。
mysql.allow_persistent = On
mysql.max_persistent = -1
mysql.max_links = -1
mysql.default_port =
mysql.default_socket =
mysql.default_host =
mysql.default_user =
mysql.default_password =
mysql.connect_timeout = 60
mysql.trace_mode = Off
结果:
class Sol(object):
def __init__(self):
self._marker = [
['.', '*', '*', '*'],
['*', '.', '*', '*'],
['*', '*', '.', '*'],
['*', '*', '*', '.'],
]
def move_left(self):
for row in self._marker:
for idx, cell in enumerate(row):
# No need to check the right-most and 2nd right-most cells
# because you can't move left to those cells.
if idx >= len(row) - 2:
break
if cell == '.' and row[idx + 1] == '*' and row[idx + 2] == '*':
row[idx] = '*'
row[idx + 1] = '.'
row[idx + 2] = '.'
def print_board(self):
for row in self._marker:
print(' '.join(row))
sol = Sol()
sol.move_left()
sol.print_board()