currently I am trying to solve the following problem:
After becoming famous, the CodeBots decided to move into a new building together. Each of the rooms has a different cost, and some of them are free, but there's a rumour that all the free rooms are haunted! Since the CodeBots are quite superstitious, they refuse to stay in any of the free rooms, or any of the rooms below any of the free rooms.
Given matrix, a rectangular matrix of integers, where each value represents the cost of the room, your task is to return the total sum of all rooms that are suitable for the CodeBots (ie: add up all the values that don't appear below a 0).
Example
For
matrix = [[0, 1, 1, 2],
[0, 5, 0, 0],
[2, 0, 3, 3]]
the output should be
solution(matrix) = 9.
Below is the code I have written up so far:
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
Now I know that I have not begun to solve to solve for the issue of the rooms below a haunted one being off limits, but I first want to figure out the correct way to iterate through the entire 2d list, as I am simply getting zero for every input. I would like to know how you can successfully add every elements in the 2d list together. If someone could point me in the right direction for this I'd appreciate it.
CodePudding user response:
There's three issues with your code:
=
isn't correct syntax. Use=
instead.len(matrix[i:0])
isn't quite right. Perhaps you were trying to iterate over the row backwards, but as I'll describe in the next point, that's not necessary.- Once you see a zero in a column, you know that all of the rooms below it can't be counted, per the problem statement. So, break out of the inner loop once you see a zero.
Here is a code snippet that resolves all of these issues:
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
CodePudding user response:
I personally prefer avoiding using range
if not needed, if you want the extra "index" information, user enumerate
. You also have the useful sum
function you can use for your "base case" aka the top stage.
Since we can suppose that the top stage are all valid and the free room doesn't impact the sum of the stage.
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