Code Signal_练习题_matrixElementsSum

After they became famous, the CodeBots all decided to move to a new building and live together. The building is represented by a rectangular matrix of rooms. Each cell in the matrix contains an integer that represents the price of the room. Some rooms are free(their cost is 0), but that's probably because they are haunted, so all the bots are afraid of them. That is why any room that is free or is located anywhere below a free room in the same column is not considered suitable for the bots to live in.

Help the bots calculate the total price of all the rooms that are suitable for them.

Example

  • For
matrix = [[0, 1, 1, 2], 
          [0, 5, 0, 0], 
          [2, 0, 3, 3]]

the output should be
matrixElementsSum(matrix) = 9.

Here's the rooms matrix with unsuitable rooms marked with 'x':

[[x, 1, 1, 2], 
 [x, 5, x, x], 
 [x, x, x, x]]

Thus, the answer is 1 + 5 + 1 + 2 = 9.

  • For
matrix = [[1, 1, 1, 0], 
          [0, 5, 0, 1], 
          [2, 1, 3, 10]]

the output should be
matrixElementsSum(matrix) = 9.

Here's the rooms matrix with unsuitable rooms marked with 'x':

[[1, 1, 1, x], 
 [x, 5, x, x], 
 [x, 1, x, x]]

Note that the free room in the first row make the full column unsuitable for bots.

Thus, the answer is 1 + 1 + 1 + 5 + 1 = 9.

 

我的解答:

 1 def matrixElementsSum(matrix):
 2     num = 0
 3     j = 0
 4     while j<len(matrix):
 5         num = num + sum(matrix[j])
 6         for i in range(len(matrix[j])):
 7             if matrix[j][i] == 0:
 8                 for x in range(j+1,len(matrix)):
 9                     matrix[x][i] = 0
10         j += 1
11     return num

 

膜拜大佬:

 1 def matrixElementsSum(m):
 2     r = len(m)
 3     c = len(m[0])
 4     total=0
 5     for j in range(c):
 6         for i in range(r):
 7             if m[i][j]!=0:
 8                 total+=m[i][j]
 9             else:
10                 break
11     return total
View Code

 

转载于:https://www.cnblogs.com/BlameKidd/p/9348418.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值