Python:如何存储矩阵值的值

时间:2015-05-01 16:40:24

标签: python arrays python-2.7

所以给了我一个矩阵

---
-m-
p--

我必须找出必须采取哪些方向才能达到像左,下等一样的方式。

for i in range(n):
  for j in range(n):
    if grid[i][j] == "m":
        m = [i,j]
    elif grid[i][j] == "p":
        p = [i,j]

我能找到m和p的位置,但想比较m和p的[i,j],以便它可以移动到p。当我尝试比较它们或者添加+1时,我无法做到这一点。 我应该以任何特定的方式存储m和p的位置,以便我可以处理它们的值。

3 个答案:

答案 0 :(得分:0)

感谢您发布此问题,这是一个非常有趣的小脚本!

不完美,但您可以使用这些功能来完成我所称的"矩阵路径"。看看:

# Find the position of a character in the matrix (returns tuple)
def matrix_find( matrix, ch ):
    m_len, m_wid = (len(matrix.split('\n')[0]), len(matrix.split('\n')))
    for line_num, line in enumerate(matrix.split('\n')):
        for letter_num, letter in enumerate(line):
            if letter == ch:
                return (line_num + 1, letter_num + 1)

# Find the path from one character's location to another
def matrix_pathing(start, finish):
    if start == finish:
        print("No pathing needed.")
    else:
        print("Move {} {}"*(0 if start[0] == finish[0] else 1)).format(abs(start[0]-finish[0]), "down" if start[0] < finish[0] else "up")
        print("Move {} to the {}"*(0 if start[1] == finish[1] else 1)).format(abs(start[1]-finish[1]), "right" if start[1] < finish[1] else "left")

我为每行代码的丰富道歉,这只是一个快速实现。在将其提交给教师之前,您应该添加错误检查等。

这些功能可以这样使用:

>> matrix_str = """---
-m-
--p"""

>> matrix_pathing(matrix_find(matrix_str, 'm'), matrix_find(matrix_str, 'p'))
Move 1 down
Move 1 to the left

答案 1 :(得分:0)

我是这样做的:

for i in range(n):
    for j in range(n):
        if grid[i][j] == "m":
            mx = i
            my = j
        elif grid[i][j] == "p":
            px = i
            py = j
boolean = True

while boolean:
    if mx > px:
        mx-=1
        print "UP"
    elif mx < px:
        mx+=1
        print "DOWN"
    elif my > py:
        my-=1
        print "LEFT"
    elif my < py:
        my+=1
        print "RIGHT"

    if mx == px and my == py:
        boolean = False

答案 2 :(得分:0)

正如您已经自己解决的那样,我只是发布它以分享想法。

将矩阵创建为列表列表。 我做了几个方法,切换值,查找路径,将值插入某列和某行...

INIT_VALUE = "-"
COLUMN = 3
ROW = 3


def insert(matrix, num_row, num_col, value):
    """inserts certain value to certain row and column"""
    matrix[num_row][num_col] = value

def find(matrix, value):
    """iterates matrix and find coordinate of target value, return valid
    coordinate if found, return invalid if not"""
    target_row, target_column = 0, 0
    found = False
    for row in matrix:
        if value in row:
            found = True
            target_column = row.index(value)
            break
        target_row += 1

    if found:
        # returns tuple. the order is row number, column number, and value
        return (target_row, target_column, value)
    else:
        return (-1,-1, "x")  # return invalid if not found


def switch(matrix, c1, c2):
    """switch two characters coordinates"""
    matrix[c1[0]][c1[1]] = c2[2]
    matrix[c2[0]][c2[1]] = c1[2] 


def find_path(c1, c2):
    """finds path from coordinate 1 to coordinate 2"""
    row_diff = c1[0] - c2[0]
    column_diff = c1[1] - c2[1]

    row_direction = "Up" if row_diff > 0 else "Down"
    column_direction = "Left" if column_diff > 0  else "Right"

    print "move {} to {}, we need to move {} {} and move {} {}".format(c1[2],c2[2], abs(row_diff), row_direction, abs(column_diff), column_direction)

if __name__ == "__main__":
    # initialize matrix
    matrix= [[INIT_VALUE for column in range(COLUMN)] for row in range(ROW)] 

    # insert m
    insert(matrix, 1, 1, "m")
    # insert p
    insert(matrix, 2, 0 , "p")
    print matrix

    m = find(matrix, "m")
    p = find(matrix, "p")

    # try to find a value that does not exist
    unknow = find(matrix, "unknow")
    print m
    print p
    print unknow

    # switches postion of m and p
    switch(matrix, m, p)   
    print matrix

    # finds path from m to p
    find_path(m, p)

运行脚本并获取:

hzhang@dell-work ~ $ python test.py 
[['-', '-', '-'], ['-', 'm', '-'], ['p', '-', '-']]
(1, 1, 'm')
(2, 0, 'p')
(-1, -1, 'x')
[['-', '-', '-'], ['-', 'p', '-'], ['m', '-', '-']]
move m to p, we need to move 1 Down and move 1 Left