DEV Community

Lakshyaraj Dash
Lakshyaraj Dash

Posted on

How to find mean, median & mode of the elements of a tuple or list (no statistics module used) ?

Today we will learn the easiest way to find the mean, median and mode of the elements of a tuple using normal concepts.

Note: No statistics module has been used

t = ()
n = int(input("Enter the number of elements: "))

for i in range(n):
    num = int(input("Enter the element: "))
    t += (num,)

mean = 0
median = 0
mode = 0

length = len(t)
s = sum(t)
mean = s / length

st = sorted(t)

if (len(st)%2 != 0):
    medInd = int(len(st)/2)
    median = st[medInd]
else:
    medInd1 = int(len(st)/2)
    medInd2 = int(len(st)/2) - 1
    median = (st[medInd1] + st[medInd2])/2

d = {}
for i in t:
    d[i] = t.count(i)

max_occur = max(list(d.values()))

for i in t:
    if t.count(i) == max_occur:
        mode = i

print(f'Mean: {mean}')
print(f'Median: {median}')
print(f'Mode: {mode}')
Enter fullscreen mode Exit fullscreen mode

Top comments (0)