Matrix Elements Sum – CodeSignal Python Challenge (Easy)

preview_player
Показать описание
Solving the “Matrix Elements Sum” challenge from CodeSignal using Python.
A fun matrix traversal problem that’s great for improving your 2D array logic skills.

☕ Like the content? Support me here:

🧩 Challenge link:
Рекомендации по теме
Комментарии
Автор

Wait, the exercise says “they refuse to stay in a room below the free rooms” …shouldn’t we count these when they are above a haunted room, then stop counting once we hit a zero?

TheCALMInstitute
Автор

I did it this way and it seems to work fine

def solution(matrix):

rows = len(matrix)

# get the cols as a list to see which ones we can look in
cols = list(range(0, len(matrix[0])))


totalAmt = 0

for i in range(rows):

# cols idx start
j = 0
while j < len(cols):

if matrix[i][cols[j]] == 0:
del(cols[j])
else:
totalAmt += matrix[i][cols[j]]
j += 1

return totalAmt

lynnmarciano
Автор

The real solution: go through each row except the first, check if the number 'above' is 0. If 0, then the current number is zero. This loops and updates the whole matrix. Then just add all the numbers.

Armenhanmer
Автор

for loop: add up the first row entirely, for each next row: if the value above is 0, dont add... idk just what I was thinking

Armenhanmer
Автор

why did you define the array after the loop ( col = [ ] )why not before the loop ?

ryanmanchikanti
Автор

Very good video. You helped me understand this problem much bettter. I was trying things that were not working. I appreciate your work. Keep the content coming, please. 🤓

papadavis
Автор

hey i have a doubt they say that the elements below 0 shd also be ignored did this code do that

Sophie-dzic
Автор

Alt matrix sum
You are given a chessboard of size N x N, where the top left square is black. Each square contains a value. Find the sum of values of all black square and all white squares.

Remember that in a chessboard black and white squares alternate. Input User task: Input consists on N and the the numbers in the NxN matrix. You need to print out the sum of black squares and then white squares in the next line.

i want this in python i tired a lot but it was getting error
def sumAlternate(arr, n):

sum1 = 0
sum2 = 0

# check the alternate elements
i = 0
while i < n * n :

# count the elements at
# even places
if (i % 2 == 0):
sum1 += (arr + i)

else: # count the elements
# at odd places
sum2 += (arr + i)

i += 1

print("Sum of alternate elements : " +
str(sum1) + ", " + str(sum2))

# Driver code
if __name__ == "__main__":
mat = [[ 1, 2, 3 ],
[4, 5, 6 ],
[7, 8, 9 ]]
n = 3

# find the sum of alternate elements
sumAlternate(mat[0][0], n)

adithyabharadwaj
Автор

why transpose the matrix manually instead of using np.transpose?

nataliewagner
welcome to shbcf.ru