在python中交换元素

2024-05-16 20:57:39 发布

您现在位置:Python中文网/ 问答频道 /正文

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 []

我的程序应该移动用“*”表示的peg,然后跳转到空位(“.”)并移除其间的peg。你知道吗

对于上面的docstring:r1将变成

 ["*", "*", ".", "."]

我的代码适用于显示的docstring,但是如果r1 = ["*", "*", ".", "*"]r3 = ["*", ".", "*", "*"]。你知道吗

它应该交换r3元素,但它不起作用(我知道我没有遍历每个空位置,但我找不到方法)

还有一个更好的方法是在指数超出范围内做。我在做try和except block,因为如果空的位置在第3列,它会给我索引超出范围,因为我在寻找它旁边的销钉


Tags: andthenewtypecolumnleftmarkerlist
2条回答

我将使循环范围变小,以避免索引超出范围。 因为你不能在最右边的两个地方插上钉子,所以没有必要检查它们。这样你就不用担心超出范围了。你知道吗

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()

结果:

* . . *
* * . .
* * . *
* * * .

当前,您的代码将只跳转到左侧。它也不会垂直跳跃。你知道吗

你还需要能够做到自我标记[r] [c-{1,2}]和自我标记[r+-{1,2}[c]变换。你知道吗

实际上,“跳转”操作应该是它自己的函数,以便稍微简化代码。你知道吗

相关问题 更多 >