Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Count Elements Greater Than Average

Count values strictly above a list's average. Students compute the mean first, scan again for matches, and identify empty input as an undefined case here.

AdvancedPhase 4 - Level 5: Logical & AppliedExample 8 of 14
count-elements-greater-than-average.py
1# Take array
2n = int(input("Enter array size: "))
3arr = []
4for i in range(n):
5 arr.append(int(input(f"Element {i+1}: ")))
6
7# Calculate average
8average = sum(arr) / len(arr)
9
10# Count greater than average
11count = 0
12for element in arr:
13 if element > average:
14 count += 1
15
16print(f"Elements greater than average ({average}): {count}")

Output

Enter array size: 5
Element 1: 10
Element 2: 20
Element 3: 30
Element 4: 40
Element 5: 50
Elements greater than average (30.0): 2

In this one

  • Compute a shared benchmark
  • Count strict exceedances
  • Recognize zero-length failure

How it works

  1. 1

    Calculate sum(arr) divided by len(arr).

  2. 2

    Scan the entries after the mean is known.

  3. 3

    Increment count only for values strictly above it.

Edge cases

Do values equal to the average count?

Do values equal to the average count?

No. The comparison is strict.

What happens for empty input?

What happens for empty input?

The mean calculation raises ZeroDivisionError.

What's going on

The mean is sum(arr) / len(arr). A second traversal compares each value with that shared benchmark.

Only element > average increases count. Equal-to-average entries do not count, and repeated larger values count separately. Two passes keep the logic simple because the completed mean is needed before classifying entries. An empty list causes division by zero.

Do values equal to the average count? No. The comparison is strict.

What happens for empty input? The mean calculation raises ZeroDivisionError.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Why calculate the mean before counting?

Pick an answer to check it.

Question 2

Do values equal to the average count?

Pick an answer to check it.

Questions people ask

Do values equal to the average count?

No. The comparison is strict.

What happens for empty input?

The mean calculation raises ZeroDivisionError.

Why calculate the mean before counting?

Every comparison needs the completed mean.