Kartik Madaan
Kartik Madaan

Reputation: 85

How to print mean , median and mode in python 3

I am new to python programming and I'm getting runtime error with my code. Any help is appreciated.

import statistics

tc = int(input())

while tc > 0:
    n = int(input())
    arr = input()
    l = list(map(int, arr.split(' ')))
    print("{} {} {}".format(statistics.mean(l), statistics.median(l), statistics.mode(l)))
    tc = tc - 1

Error

StatisticsError: no unique mode; found 2 equally common values

Input Format

First line consists of a single integer T denoting the number of test cases. First line of each test case consists of a single integer N denoting the size of the array. Following line consists of N space-separated integers Ai denoting the elements in the array.

Output Format

For each test case, output a single line containing three-separated integers denoting the Mean, Median and Mode of the array

Sample Input

1
5
1 1 2 3 3

Sample Output

2 2 1

Upvotes: 0

Views: 3478

Answers (2)

Mayur Vora
Mayur Vora

Reputation: 962

Hello Kartik Madaan,

Try this code,

Using Python 3.X

import statistics
from statistics import mean,median,mode

tc = int(input())

while tc > 0:
    n = int(input())
    arr = input()
    l = list(map(int,arr.split()))
    mod = max(set(l), key=l.count)
    print(int(mean(l)),int(median(l)),mod)
    tc = tc - 1

I hope my answer is helpful.
If any query so comment please.

Upvotes: 0

depperm
depperm

Reputation: 10746

You could add a variable mode surrounded by a try...except and if statistics has an error get the mode a different way.

try:
  mode=statistics.mode(l)
except:
  mode=max(set(l),key=l.count)
print("{} {} {}".format(statistics.mean(l), statistics.median(l), mode))

Upvotes: 2

Related Questions