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