Calculate how many elements of this two-dimensional array exceed the arithmetic mean of all elements of this array

Question:

I need to calculate how many elements of a two-dimensional array exceed the arithmetic mean of all elements of this array

i need do this with this array

array = [[1, 5, 7, 3, 2], [2, 4 ,1 ,6, 8]]
Asked By: BoJJ

||

Answers:

Use :

import numpy as np

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

# convert to numpy array
a = np.array(array)

# get True for values above mean and count with sum
out = (a>a.mean()).sum()
# 5

In pure python:

from statistics import mean

avg = mean([x for l in array for x in l])
# 3.9

out = sum(1 for l in array for x in l if x>avg)
# 5
Answered By: mozway

from statistics import mean

avg = mean([x for l in array for x in l])

3.9

out = sum(1 for l in array for x in l if x>avg)

5

Answered By: POG MEE

Here’s a different interpretation of the question. The assumption is that the output should be the number of values in each sub-list that exceed the mean for that same sub-list.

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

for e in lists:
    mean = sum(e) / len(e)
    print(sum(v > mean for v in e))

Output:

2
2
Answered By: Pingu

To solve this problem, you can follow these steps:

Calculate the sum of all elements in the array and the total number of elements.
Compute the arithmetic mean by dividing the sum by the total number of elements.
Loop through each element in the array and count the number of elements that exceed the arithmetic mean.

Here’s the Python code that implements this logic:

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

# Step 1: Calculate the sum of all elements and the total number of elements
total_sum = 0
total_count = 0
for row in array:
    for element in row:
        total_sum += element
        total_count += 1

# Step 2: Compute the arithmetic mean
arithmetic_mean = total_sum / total_count

# Step 3: Loop through each element and count the number of elements that exceed the arithmetic mean
count = 0
for row in array:
    for element in row:
        if element > arithmetic_mean:
            count += 1

print(count)

When you run this code, it should output ‘4’, which is the number of elements in the array that exceed the arithmetic mean of all elements.

Answered By: Akshat Patel
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.