The function sum_rows should add all the values in each row of data and return a
ID: 3778461 • Letter: T
Question
The function sum_rows should add all the values in each row of data and return a new list containing those sums. The data parameter is a 2D list, or more specifically, a list of lists. You must use the len() function to determine how many rows there are, and for each row, how many columns there are. Look at the following example. This list represents the data parameter. sum_rows should return the following list of row sums: Complete your implementation of s um_rows below. Use loops. You may not use recursion or the built-in sum function. def sum_rows(data):Explanation / Answer
def sum_rows(data):
sum_list=[] #initialise the list of sums to empty
s=0
for i in range(len(data)): #caluclate the sum of each list 's'
s=0
for j in data[i]:
s=s+j
sum_list.append(s) #append the each list sum 's' to 'sum_list'
return sum_list #return sum_list
dt=[[3,-8,2,34],[9,-19],[-27,30,45],[-2,5]] #list of lists in the question
slist=sum_rows(dt)
print(slist) #print the list
#save the above code and run it.
#example output
#[31, -10, 48, 3]
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.