简体   繁体   中英

The sum of a 2D arrays' specific rows - Python

Trying to get this program to print the sum of each row, then the total sum of all the elements, it's fine with the grand total but I can't see why the individual sums of the rows aren't outputting correctly

rows = len(numbers)
cols = len(numbers[0])
total=0

The variables are set as above (each column is of the same length, and the array is entirely integers)

I want it to run through each row, add each column within that row and print it, then print the total of the whole array.

for x in range(0, rows):
  rowtotal=0
  for y in range(0, cols):
    rowtotal=rowtotal+int(numbers[x-1][y-1])
  print(rowtotal)
  total=total+rowtotal
print(total)

The array is imported through import sys numbers= sys.argv[1:] for i in range(0,len(numbers)): numbers[i]= numbers[i].split(',')

I'm coding through an online software which may be the problem. Currently it returns

Program Failed for Input: 1,1,-2 -1,-2,-3 1,1,1 Expected Output: 0 -6 3 -3 Your Program Output: 3 0 -6 -3

Any other code, including numbers[x][y] seems to always return an error

You should have numbers[x][y] instead of numbers[x-1][y-1] .

So if you do:

numbers=[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
rows = len(numbers)
cols = len(numbers[0])
total=0
for x in range(0, rows):
    rowtotal=0
    for y in range(0, cols):
        rowtotal=rowtotal+int(numbers[x][y])
    print(rowtotal)
    total=total+rowtotal
print(total)

the output is

6
15
24
33
78

Also if the array numbers consists only of integers, you can remove the int from int(numbers[x][y]) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM