Answer to Question #145964 in Python for b.

Question #145964
For this exercise, use the following 2D array, which is already declared and initialized in your programming environment below.

34 38 50 44 39
42 36 40 43 44
24 31 46 40 45
43 47 35 31 26
37 28 20 36 50
Your task is to find the average of all values in the 2D array.

Note: Be sure that your program accounts for arrays of any size, not just arrays that are 5 x 5. Your program will be tested against arrays of size n by n. It should work for any square array, not just the one shown. You should also use for loops in your program, not while loops.
1
Expert's answer
2020-11-22T23:42:09-0500
# We define array simple_arr as a list whose elements are lists
simple_arr = [[34, 38, 50, 44, 39],
              [42, 36, 40, 43, 44],
              [24, 31 ,46 ,40 ,45],
              [43, 47, 35, 31, 26],
              [37, 28, 20, 36, 50]]

# Create a function to calculate the average
def mean_arr(arr_arg):
    count_arr = 0
    sum_arr = 0
# Loop through all array elements with counting the number and sum of elements
    for row in arr_arg:
        for elem in row:
            count_arr += 1
            sum_arr + = elem
    res = sum_arr / count_arr
    return res
print(mean_arr(simple_arr))


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

Assignment Expert
31.03.21, 09:00

Dear Robert please try sum_arr += elem

robert
31.03.21, 07:07

uh yeah its wrong. fix it

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS