fix this code's error:"arr = [[2, 6, -1, 5],[8, 2, 7, -5],[1, 0, 4, 4]] def sumcol(arr):…
- User
fix this code's error:"arr = [[2, 6, -1, 5],[8, 2, 7, -5],[1, 0, 4, 4]]
def sum_col(arr): num_col = len(arr[0]) sum_col = [0]*num_col
for row in arr: for i in range(num_col): sum_col[i] +=row[i] for i in range(num_col): print("The sum of column"+ i +"is"+ num_col[i])
sum_col(arr) "
TypeError Traceback (most recent call last) in <cell line: 13>() 11 print("The sum of column"+ i +"is"+ num_col[i]) 12 ---> 13 sum_col(arr)
in sum_col(arr) 9 sum_col[i] +=row[i] 10 for i in range(num_col): ---> 11 print("The sum of column"+ i +"is"+ num_col[i]) 12 13 sum_col(arr)
TypeError: can only concatenate str (not "int") to str
- Assistant
The error occurs because you're trying to concatenate a string with an integer without converting the integer to a string. Additionally, in your print statement, you seem to be trying to access
num_col[i], which is not the correct variable. Instead, you should accesssum_col[i].Here is the corrected code:
arr = [[2, 6, -1, 5], [8, 2, 7, -5], [1, 0, 4, 4]] def sum_col(arr): num_col = len(arr[0]) sum_col = [0] * num_col for row in arr: for i in range(num_col): sum_col[i] += row[i] for i in range(num_col): print("The sum of column " + str(i) + " is " + str(sum_col[i])) sum_col(arr)Explanation of changes:
- I converted the integer
ito a string usingstr(i)in the print statement. - I corrected the variable being accessed in the print statement to
sum_col[i]instead ofnum_col[i].
This should now print the correct sums of each column in your 2D array.
- I converted the integer