Andrew553
Andrew553

Reputation: 17

How to sum each row and append the sum into the same list?

def row_sums(square):
    """takes such a (possibly magic) square as a parameter and returns a list of the row sums"""
    total_each_row = 0
    combine_each_total = []    
    for row in square: #row is an entire row
        for cell in row: #cell is an element of row
            total_each_row += cell  #possible error 


        combine_each_total.append(total_each_row) #possible error 
    return combine_each_total



magic_square = [
    [2, 7, 6],
    [9, 5, 1],
    [4, 3, 8]
]
print(row_sums(magic_square))

This program running out as [15, 30, 45] but what I want to get is [15, 15, 15] as the sum of each row and allocate the sums in the same list.

After the first row finished its sum calculation, how to make a new total for the second and the following rows for each one and append each sum into the same list?

The square would be containing all the integers from 1 up to n**2 inclusive.

In the end, returns a list of the row sums

Are there any other ways to achieve the result without using the built-in sum function in this case? (Sorry I should emphasize this point)

Upvotes: 0

Views: 918

Answers (3)

Victor
Victor

Reputation: 2919

magic_square = [
    [2, 7, 6],
    [9, 5, 1],
    [4, 3, 8]
]

# functional/pythonic way
sums = [sum(row) for row in magic_square]  # [15, 15, 15]


# if you want to make it longer
def row_sums(square):
   return [sum(row) for row in square]
row_sums(magic_square)  # [15, 15, 15]


#if you want to make it even longer
def row_sums(square):
   sums = []
   for row in square:
      row_total = 0
      for number in row:
          row_total += number
      sums.append(row_total)    
   return sums
row_sums(magic_square)  # [15, 15, 15]

Upvotes: 0

Poojan
Poojan

Reputation: 3519

  • You need to reinitialize combine_each_total to 0 before summing again for new row.


def row_sums(square):
    """takes such a (possibly magic) square as a parameter and returns a list of the row sums"""

    combine_each_total = []    
    for row in square: #row is an entire row
        total_each_row = 0
        for cell in row: #cell is an element of row
            total_each_row += cell  #possible error 


        combine_each_total.append(total_each_row) #possible error 
    return combine_each_total



magic_square = [
    [2, 7, 6],
    [9, 5, 1],
    [4, 3, 8]
]
print(row_sums(magic_square))

output:

[15,15,15]

Upvotes: 0

dahan raz
dahan raz

Reputation: 392

Just use pythons sum function for each row.

Arr=[]
for row in square:
    Arr.append(sum(row))
return Arr

If you want to use your code the problem with it is that you dont make sure that your sum row var equals to 0 so its keeping the count from last row.

Upvotes: 2

Related Questions