0

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

Christian Dean
  • 22,138
  • 7
  • 54
  • 87
Kartik Madaan
  • 85
  • 2
  • 9

2 Answers2

2

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))
depperm
  • 10,606
  • 4
  • 43
  • 67
  • 1
    @KartikMadaan ....you put the try...except in the `while` loop, `l` isn't defined outside of the loop otherwise – depperm Jul 13 '17 at 12:09
0

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.

Mayur Vora
  • 922
  • 2
  • 14
  • 25