[英]Correct way to iterate though a 2d list
目前我正在嘗試解決以下問題:
成名后,CodeBots 決定一起搬進新大樓。 每個房間都有不同的費用,其中一些是免費的,但有傳言說所有免費房間都鬧鬼,因為CodeBots非常迷信,他們拒絕入住任何免費房間。 或任何免費房間下方的任何房間。
給定矩陣,一個整數的矩形矩陣,其中每個值代表房間的成本,你的任務是返回適合 CodeBots 的所有房間的總和(即:將下面沒有出現的所有值相加一個 0)。
例子
為了
matrix = [[0, 1, 1, 2],
[0, 5, 0, 0],
[2, 0, 3, 3]]
output 應該是
solution(matrix) = 9.
以下是我到目前為止編寫的代碼:
def solution(matrix):
rooms = 0
for i in range(len(matrix[0])):
for j in range(len(matrix[i:0])):
if matrix[i][j] > 0:
rooms=+matrix[i][j]
return rooms
現在我知道我還沒有開始解決鬧鬼房間下面的房間被禁止進入的問題,但我首先想找出遍歷整個 2d 列表的正確方法,因為我只是得到零對於每個輸入。 我想知道如何成功地將 2d 列表中的每個元素添加在一起。 如果有人能為此指出正確的方向,我將不勝感激。
您的代碼存在三個問題:
=+
語法不正確。 使用+=
代替。len(matrix[i:0])
不太正確。 也許您正在嘗試向后迭代該行,但正如我將在下一點中描述的那樣,這不是必需的。這是解決所有這些問題的代碼片段:
def solution(matrix):
rooms = 0
for col in range(len(matrix[0])):
for row in range(len(matrix)):
if matrix[row][col] > 0:
rooms += matrix[row][col]
else:
break
return rooms
如果不需要,我個人更喜歡避免使用range
,如果你想要額外的“索引”信息,用戶enumerate
。 您還有有用的sum
function 可用於您的“基本案例”,也就是頂級階段。
因為我們可以假設頂層都是有效的並且空閑空間不會影響階段的總和。
def solution(matrix):
# Top stage
above_stage = matrix[0]
# Since this is the top stage, we know all rooms respect the rules
cost = sum(above_stage)
# for each other stage
for stage in matrix[1:]:
for i, room in enumerate(stage):
# We check the above stage for the same index
# To ensure we're not below a free room
if above_stage[i] != 0:
# Add the cost of the valid rooms
cost += room
# Update the above stage for the next iteration
above_stage = stage
return cost
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.