3

How do I print the sum of top left, top and top right elements

 2 years ago
source link: https://www.codeproject.com/Questions/5327578/How-do-I-print-the-sum-of-top-left-top-and-top-rig
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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:
Copy Code
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)
Comments
Seems your output should be:
Copy Code
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
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
Copy Code
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.

Add your solution here

Preview

Existing Members

Sign in to your account

...or Join us

Download, Vote, Comment, Publish.

Your Email   Password  

 

Your Email   Optional Password  

StrengthToo short

 

I have read and agree to the Terms of Service and Privacy Policy
Please subscribe me to the CodeProject newsletters
When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK