Hi guys, i’m trying to solve this problem but for some reason it’s returning list out of index…

the problem is

A 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. That is why any room that is free or is located anywhere below a free room in the same column is not considered suitable.

Calculate the total price of all the rooms that are suitable.

Example

matrix=`[[0, 1, 1, 2], ----- [0, 5, 0, 0], ----- [2, 0, 3, 3]]`

the output should be

matrixElementsSum(matrix) = 9.

My code is:

`def matrixElementsSum(matrix): floors = len(matrix) current_floor = floors current_tower = 0 apartments = len(matrix[0]) total = 0 #while we have floors above and apartments in the array... while(current_floor-1>=0 and current_tower+1<=apartments): #if this apartment = 0, we go to the next tower if(matrix[current_floor-1][current_tower]==0): current_tower = current_tower+1 current_floor = floors #if not, we sum it to total price and go up else: total = total + (matrix[current_floor][current_tower]) current_floor = current_floor-1 return total`

result: index out of range

i do not know , way are you choose do use while.

but first solved the problem without calculate run time programming

after fix it with run time.

now we know:

```
double sum = 0;
for(int i=0;i<`floors.length;i++) //run on the rows {
for(int j =0;j<floors[0].length;j++) // run on the columns
{
sum += floors[i][j];
}
}
```

The previous poster tried to mix in some other language with your existing Python code, but I will just tell you why you are getting **list out of index** error message when you try to run your code. If you insert a **print(current_floor, current_tower)** in the else statement, you will see on the first iteration, you are trying to reference **matrix[3][0]** and arrays in Python are 0-indexed, so the highest index for a row in a 3 x 4 two-dimensional array is 2. There is no row index of 3 in the matrix, just 0, 1, 2 row indices.

```
def matrixElementsSum(matrix):
floors = len(matrix)
current_floor = floors
current_tower = 0
apartments = len(matrix[0])
total = 0
#while we have floors above and apartments in the array...
while(current_floor-1>=0 and current_tower+1<=apartments):
#if this apartment = 0, we go to the next tower
if(matrix[current_floor-1][current_tower]==0):
current_tower = current_tower+1
current_floor = floors
#if not, we sum it to total price and go up
else:
print(current_floor, current_tower)
total = total + (matrix[current_floor][current_tower])
current_floor = current_floor-1
return total
```

1 Like