给定一系列正整数,请按要求对数字进行分类,并输出以下 5 个数字:
A1= 能被 5 整除的数字中所有偶数的和;
A2= 将被 5 除后余 1 的数字按给出顺序进行交错求和,即计算 n1 −n2+n3−n4 ⋯;
A3= 被 5 除后余 2 的数字的个数;
A4= 被 5 除后余 3 的数字的平均数,精确到小数点后 1 位;
A5= 被 5 除后余 4 的数字中最大数字。
输入格式:
每个输入包含 1 个测试用例。每个测试用例先给出一个不超过 1000 的正整数 N,随后给出 N 个不超过 1000 的待分类的正整数。数字间以空格分隔。
输出格式:
对给定的 N 个正整数,按题目要求计算 A1~A5并在一行中顺序输出。数字间以空格分隔,但行末不得有多余空格。
若其中某一类数字不存在,则在相应位置输出 N。
输入样例
13 1 2 3 4 5 6 7 8 9 10 20 16 18
结果
30 11 2 9.7 9
输入样例2
8 1 2 4 5 6 7 9 16
结果2
N 11 2 N 9
解决方法
import numpy as np
# 输入值,并分割成列表,第一个数是输入的数字个数
a = input().split(' ')[1:]
b = [int(x) for x in a]
a = [[], [], [], [], []]
A = [[], [], [], [], []]
# 定义函数:对每个数进行分类
def class_num(n):
if n % 10 == 0:
a[0].append(n)
elif n % 5 == 1:
a[1].append(n)
elif n % 5 == 2:
a[2].append(n)
elif n % 5 == 3:
a[3].append(n)
elif n % 5 == 4:
a[4].append(n)
return a
for i in b:
class_num(i)
# 计算各个参数
A[1] = 0
tag, tag1 = -1, -1
for i in a:
tag += 1
if i and tag == 0:
A[tag] = sum(a[0])
elif i and tag == 1:
for j in i:
tag1 += 1
A[tag] += j * (-1) ** (tag1)
elif i and tag == 2:
A[tag] = len(a[tag])
elif i and tag == 3:
A[3] = round(np.mean(a[3]), 1)
elif i and tag == 4:
A[4] = max(a[4])
else:
A[tag] = 'N'
# 打印出来
print(' '.join(str(i) for i in A))