我正在解決一個涉及以鋸齒形方式遍歷a的問題,其中可以是相同的數字或不同的數字,即我們將有一個正方形或矩形矩陣。n x m matrixn and m
為了解決這個問題,我有一個主要的方法來遍歷矩陣;這主要方法中,我創建和呼叫上moveDiagonallyUpwards和moveDiagonallyDownwards方法,在曲折的方式移動。
我遇到的問題是,當我將main 方法中的row和col作為引數傳遞給這兩個其他方法時,在這些方法中,我更新行和列,例如 =1 或 -= 1。這些更改不會反映在主方法中方法,當我回傳到主方法。我明白為什么會這樣。
所以我的挑戰是,我怎樣才能將更新的row和col主要方法傳回?我想到了使用aglobal class來實作上述目的。我的想法是創建一個單獨的類來保存這些變數,如下所示,但是我global row and col在main 方法中呼叫和使用這些變數時遇到問題。
任何想法如何調整row and colin main 方法以實作上述目標?謝謝!
array = [
[1, 3, 4, 10],
[2, 5, 9, 11],
[6, 8, 12, 15],
[7, 13, 14, 16]
]
class matrixMovement:
def __init__(self,row=0,col=0,output=[]):
self.row = row
self.col = col
self.output = output
#Main Method
def zigzagTraverse(array):
output.append(array[row][col])
while array.row<= len(array)-1 or array.col<= len(array[0])-1:
if array.row< len(array)-1:
array.row = 1
output.append(array[row][col])
diagonalUp(row,col,array,output)
if col < len(array[0])-1:
col = 1
output.append(array[row][col])
diagonalDown(row,col,array,output)
return output
def diagonalUp(row,col,array,output):
while row > 0 and col< len(array[0])-1:
row -= 1
col = 1
output.append(array[row][col])
return matrixMovemenet(row,col,output)
def diagonalDown(row,col,array,output):
while row<len(array)-1 and col > 0:
col-= 1
row = 1
output.append(array[row][col])
return matrixMovemenet(row,col,output)
uj5u.com熱心網友回復:
你有幾個問題。一是區域范圍。另一個是使用該return陳述句,但對回傳的物件不做任何處理。
有幾種方法可以解決這個問題。一種是忽略區域變數,只是從matrixMovement它創建一個物件并利用它可變的事實。
class MatrixMovement:
def __init__(self, row=0, col=0, output=None):
# I modified this to avoid the mutable default
if output is None:
output = []
self.row = row
self.col = col
self.output = output
# Main Method
def zigzag_traverse(array):
# this is the object we will be mutating
obj = MatrixMovement()
obj.output.append(array[obj.row][obj.col])
while obj.row <= len(array) - 1 or obj.col <= len(array[0]) - 1:
if obj.row < len(array) - 1:
obj.row = 1
obj.output.append(array[obj.row][obj.col])
diagonal_up(obj, array)
if obj.col < len(array[0]) - 1:
obj.col = 1
obj.output.append(array[obj.row][obj.col])
diagonal_down(obj, array)
# without this condition the loop will never break
if obj.row == len(array) - 1 and obj.col == len(array[0]) - 1:
break
return obj.output
def diagonal_up(obj, array):
# since we are passing in a mutable object
# anything attribute we change on it
# will be reflected on the object from the call site
while obj.row > 0 and obj.col < len(array[0]) - 1:
obj.row -= 1
obj.col = 1
obj.output.append(array[obj.row][obj.col])
def diagonal_down(obj, array):
# the same rules as diagonal_up
while obj.row < len(array) - 1 and obj.col > 0:
obj.col -= 1
obj.row = 1
obj.output.append(array[obj.row][obj.col])
uj5u.com熱心網友回復:
在解決了我在您的遍歷中發現的一些錯誤之后,我選擇使用檔案、邊界檢查來撰寫此代碼。
解釋寫在評論中。有什么不明白的歡迎提問。
from typing import TypeVar, Sequence, TypeAlias
from dataclasses import dataclass
_T = TypeVar("_T")
MatrixType = Sequence[Sequence[_T]]
@dataclass
class Point:
row: int
col: int
def zigzag_traverse(matrix: MatrixType[_T]) -> list[_T]:
output: list[_T] = []
row_length = len(matrix[0])
if any(len(row) != row_length for row in matrix):
raise ValueError("Matrix is not rectangular.")
# Initialize.
boundry = Point(len(matrix) - 1, row_length - 1)
if boundry.row < 0 or boundry.col < 0:
return output # Matrix is empty.
pointer = Point(0, 0)
# Start traversing.
output.append(matrix[pointer.row][pointer.col])
while pointer != boundry:
# Go right until edge, then start moving down.
if pointer.col < boundry.col:
pointer.col = 1
else:
pointer.row = 1
output.extend(_diagonal_left_down(pointer, matrix))
# We reached the boundry, stop traversing.
if pointer == boundry:
break
# Go down until edge, then start moving right.
if pointer.row < boundry.row:
pointer.row = 1
else:
pointer.col = 1
output.extend(_diagonal_right_up(pointer, matrix))
return output
def _diagonal_left_down(pointer: Point, matrix: MatrixType[_T]) -> list[_T]:
"""Traverse left-down diagonal.
Args:
pointer: The current position. Will be modified.
matrix: The matrix to move over.
Returns:
The list of elements traversed.
"""
row, col = pointer.row, pointer.col
output = []
while row < len(matrix) - 1 and col > 0:
output.append(matrix[row][col])
row = 1
col -= 1
# Reached the edge
output.append(matrix[row][col])
pointer.row, pointer.col = row, col
return output
def _diagonal_right_up(pointer: Point, matrix: MatrixType[_T]) -> list[_T]:
"""Traverse right-up diagonal.
Args:
pointer: The current position. Will be modified.
matrix: The matrix to move over.
Returns:
The list of elements traversed.
"""
row, col = pointer.row, pointer.col
output = []
while row > 0 and col < len(matrix[0]) - 1:
output.append(matrix[row][col])
row -= 1
col = 1
# Reached the edge
output.append(matrix[row][col])
pointer.row, pointer.col = row, col
return output
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/396929.html
上一篇:在類中如何從檔案中讀取引數?
