PAT 1108 Finding Average python解法

1108 Finding Average (20 分)
The basic task is simple: given N real numbers, you are supposed to calculate their average. But what makes it complicated is that some of the input numbers might not be legal. A legal input is a real number in [−1000,1000] and is accurate up to no more than 2 decimal places. When you calculate the average, those illegal numbers must not be counted in.

Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤100). Then N numbers are given in the next line, separated by one space.

Output Specification:
For each illegal input number, print in a line ERROR: X is not a legal number where X is the input. Then finally print in a line the result: The average of K numbers is Y where K is the number of legal inputs and Y is their average, accurate to 2 decimal places. In case the average cannot be calculated, output Undefined instead of Y. In case K is only 1, output The average of 1 number is Y instead.

Sample Input 1:
7
5 -3.2 aaa 9999 2.3.4 7.123 2.35
Sample Output 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
Sample Input 2:
2
aaa -9999
Sample Output 2:
ERROR: aaa is not a legal number
ERROR: -9999 is not a legal number
The average of 0 numbers is Undefined

题意:给出N个实数,其中可能有非法值(①超出[−1000,1000] ②非实数③小数点后位数大于2位),按格式输出非法值,并计算合法实数的平均值。

解题思路:
1.用列表l存储输入的用空格分割的数据。
2.用列表legal来存储合法值、illegal来存储非法值。
3.使用try…except语句,在try中将l中的每个元素i转为float,记为j,如果出现异常,说明i非实数,将i放入illegal,否则继续判断。
4.如果j在[−1000,1000]范围中,看是否为小数,非小数放入legal,小数继续判断小数位数是否小于等于2,满足则放入legal,否则放入illegal。
5.循环完成后,看illegal中是否有数据,有则全部按格式输出。
6.再看legal中是否有数据,计算平均值,以及判断legal中有一个还是多个数据,按照相应的格式输出,注意平均值要保留2位小数。

n = int(input())
l = input().split()
#n = 7
#l = ['5', '-3.2', 'aaa', '9999', '2.3.4', '7.123', '2.35']
legal = []
illegal = []
for i in l:
    try:
        j = float(i)
        if -1000 <= j <= 1000:
            if '.' in i:
                if len(i)-i.index('.')-1 <= 2:
                    legal.append(j)
                else:
                    illegal.append(i)
            else:
                legal.append(j)
        else:
            illegal.append(i)
    except:
        illegal.append(i)

if len(illegal):
    for i in illegal:
        print('ERROR: %s is not a legal number'%i)
if len(legal):
    average = sum(legal)/len(legal)
    if len(legal) == 1:
        print('The average of 1 number is %.2f'%(average))
    else:
        print('The average of %d numbers is %.2f'%(len(legal),average))
else:
    print('The average of 0 numbers is Undefined')

你可能感兴趣的:(python,用Python刷PAT,(Advanced,Level),Practice)