Click here to Skip to main content
15,895,801 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
My code is to print the sum of top left, top and top right sum of each elements in a matrix.
For example if the input is
3 3
7 5 2
3 8 3
2 4 1

my output should be
7 5 2
12 14 7
11 14 11

Since the first row as not top elements it jus prints as it.
Also the last row is printing as it is. How can i do it please help me!

What I have tried:

r,c=map(int,input().split())
arr=[list(map(int,input().split())) for row in range(r)]
for i in range(0,r-1):
    for j in range(0,c-1):
        arr[i][j]=arr[i-1][j-1]+arr[i-1][j]+arr[i-1][j+1]
print(arr)
Posted
Updated 15-Mar-22 6:58am
Comments
Maciej Los 15-Mar-22 16:14pm    
Seems your output should be:
7+5=12   7+5+2=14 5+2=7
3+8=11   3+8+3=14 8+3=11
2+4=6    2+4+1=7  4+1=5

1 solution

You cannot add the sums in place, as that will only work for the very first line of changes. You also need three separate statements for each column, as the sums are different. So first create a deepcopy[^] of the source array* and then do the calculations. Something like:
Python
import copy

r,c=map(int,input().split())
arr=[list(map(int,input().split())) for row in range(r)]
answer = copy.deepcopy(arr)
for i in range(1, r):
    answer[i][0] = arr[i-1][0] + arr[i-1][1]
    answer[i][1] = arr[i-1][0] + arr[i-1][1] + arr[i-1][2]
    answer[i][2] = arr[i-1][1] + arr[i-1][2]
print(F'{answer = }')


*this ensures you preserve row zero in the answer.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900