1002 A+B for Polynomials (25 分)
This time, you are supposed to find A+B where A and B are two polynomials.
Iutput Specification:
Output Specification:
For each test case you should output the sum of A and B in one line, with the same format as the input. Notice that there must be NO extra space at the end of each line. Please be accurate to 1 decimal place.
Sample Input:
2 1 2.4 0 3.2
2 2 1.5 1 0.5
(结尾无空行)
Sample Output:
3 2 1.5 1 2.9 0 3.2
(结尾无空行)
解答
说明:
- eval()函数是计算值
- 字典的get()函数,第二个参数是未查到时获得的默认值
- 打算删除字典里的项的话,枚举keys时必须用list(d.keys())
- sorted()排序字典得到的是tuple的list
a = [eval(i) for i in (input().split()[1:])] # 去掉第一个字符
b = [eval(i) for i in (input().split()[1:])]
d = {
}
for i in range(0, len(a), 2):
d[a[i]] = d.get(a[i], 0) + a[i+1]
for i in range(0, len(b), 2):
d[b[i]] = d.get(b[i], 0) + b[i+1]
# 去掉coefficient为0的
for i in list(d.keys()):
if d[i] == 0:
del d[i]
ans = sorted(d.items(), key=lambda i:i[0], reverse=True)
res = str(len(ans))
for k,v in ans:
res += " " + str(k) + " " + "{:.1f}".format(v)
print(res)