Skip to content

Instantly share code, notes, and snippets.

@tyler-austin
Last active May 31, 2017 21:37
Show Gist options
  • Save tyler-austin/f119362980f98d45790a762fa5620eb6 to your computer and use it in GitHub Desktop.
Save tyler-austin/f119362980f98d45790a762fa5620eb6 to your computer and use it in GitHub Desktop.
Code Fights - matrixElementsSum

After becoming famous, CodeBots decided to move to a new building and live together. The building is represented by a rectangular matrix of rooms, each cell containing an integer - 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.

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.

Input/Output:

  • time limit: 4000ms (py3)

  • input: array.array.integer matrix

    • 2-dimensional array of integers representing a rectangular matrix of the building.

Guaranteed constraints:

1 ≤ matrix.length ≤ 5,
1 ≤ matrix[i].length ≤ 5,
0 ≤ matrix[i][j] ≤ 10.
  • output: integer
def matrix_elements_sum(in_matrix: list):
result = 0
for c in range(len(in_matrix[0])):
for r in range(len(in_matrix)):
price = in_matrix[r][c]
if price == 0:
break
else:
result += price
return result
if __name__ == '__main__':
matrix = [[0, 1, 1, 2],
[0, 5, 0, 0],
[2, 0, 3, 3]]
total_price = matrix_elements_sum(matrix)
print('Total Price:', total_price)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment