用Python做PAT甲级1002-A+B for Polynomials

This time, you are supposed to find A+B where A and B are two polynomials.

输入格式:在这里插入图片描述

输出格式:
在一行中按照“s = 对应的和”的格式输出。

输入样例:

2 1 2.4 0 3.2
2 2 1.5 1 0.5

输出样例:

3 2 1.5 1 2.9 0 3.2

代码

a_dict, b_dict, c_dict ={}, {}, {} # 创建字典
# 读取输入
a = list(map(float,input().split()))
b = list(map(float,input().split()))
# print(a)
# print(b)
#位置供参考
# 0   1   2   3
#-4  -3  -2  -1
# 1  2.4  0  3.2
dishu = -1
for i in range(int(a[0])):
    xishu = dishu - 1
    if a_dict.get(xishu,0) == 0: # 如果没有对应的系数就给它赋值,有就加上
        a_dict[int(a[xishu])] = a[dishu]
    else:
        a_dict[int(a[xishu])] += a[dishu]
    dishu = xishu - 1
# print(a_dict)
dishu = -1
for i in range(int(b[0])):
    xishu = dishu - 1
    if b_dict.get(xishu,0) == 0:# b也同理
        b_dict[int(b[xishu])] = b[dishu]
    else:
        b_dict[int(b[xishu])] += b[dishu]
    dishu = xishu - 1
# print(b_dict)
for i in range(max(max(a_dict.keys()),max(b_dict.keys()))+1):# 确定下最高系数
    if a_dict.get(i,0) or b_dict.get(i,0):
        c_dict[i] = round(a_dict.get(i,0) + b_dict.get(i,0),1)
    if c_dict.get(i) == 0: # 如果加起来是0就去掉
        del c_dict[i]
#         if c_dict[i] == int(c_dict[i]):
#             c_dict[i] = int(c_dict[i])
print(len(c_dict),end='')
key_list = sorted(c_dict.keys())
key_list.reverse() # 从最高到最低
# print(key_list)
for i in key_list:
    print(' {:} {:}'.format(i,c_dict[i]),end='') # 格式化输出
exit(0)

不定期更新

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值