PAT 1054平均値pythonを求める

6154 ワード

1054平均値(20点)を求める
本題の基本的な要求は非常に簡単である:N個の実数を与え、それらの平均値を計算する.しかし、複雑なのは、一部の入力データが不正である可能性があることです.「正当」の入力は[−10000000]区間の実数であり、小数点以下2桁まで正確である.平均値を計算するときは、不正なデータを含めてはいけません.
入力形式:
1行目に正の整数N(≦100)を入力します.その後、1行にN個の実数が与えられ、数字間は1つのスペースで区切られる.
出力フォーマット:
各不正入力に対して、1行にERROR:X is not a legal numberを出力し、ここでXは入力である.最後に1行に結果を出力します:The average of K numbers is Y、ここでKは合法的に入力された個数で、Yはそれらの平均値で、小数点以下の2桁まで正確です.平均値が計算できない場合は、YをUndefinedで置き換えます.Kが1の場合、The average of 1 number is Yが出力される.
サンプル1を入力:
7 5 -3.2 aaa 9999 2.3.4 7.123 2.35
出力サンプル1:
ERROR: aaa is not a legal number ERROR: 9999 is not a legal number ERROR: 2.3.4 is not a legal number ERROR: 7.123 is not a legal number The average of 3 numbers is 1.38
入力サンプル2:
2 aaa -9999
出力サンプル2:
ERROR: aaa is not a legal number ERROR: -9999 is not a legal number The average of 0 numbers is Undefined
作者:CHEN,Yee単位:浙江大学時間制限:400 msメモリ制限:64 MBコード長制限:16 KB
問題解析:出力時の3つの場合、len=0、len=1、len>1平均数は2桁の小数を保持する
コード:
input()
num = input().split()
rst = []
for i in num:
    try:
        float(i)
        if '.' in i:
            s = i.split('.')
            if len(s[-1]) > 2:
                raise Exception
        if not -1000 <= float(i) <= 1000:
            raise Exception
        rst.append(float(i))

    except:
        print('ERROR: {} is not a legal number'.format(i))

if len(rst) == 0:
    print('The average of 0 numbers is Undefined')
elif len(rst) == 1:
    print('The average of 1 number is {:.2f}'.format(rst[0]))
else:
    print('The average of {} numbers is {:.2f}'.format(len(rst), sum(rst)/len(rst)))