输入为两行,分别表示两个多项式。表示每项的整数对按照次数大小降序给出。(次数绝对值小于1000,系数绝对值小于10000)
按照降次顺序输出表示和多项式的整数对(系数为0的整数对不用输出,整数对由空格分隔,最后一个整数对后不添加空格)
3 3 5 -2 1 4 0 4 2 3 -1 2 1 1 3 0
3 5 2 3 -1 2 -1 1 7 0
import traceback import sys def AddPoly(lst1,lst2): result_lst = [] result = [] dic1 = {} dic2 = {} lst1.pop(0) lst2.pop(0) # 将两个poly的系数和node作为两个dic的key和value for i in range(0,len(lst1),2): dic1[lst1[i+1]]= lst1[i] for i in range(0,len(lst2),2): dic2[lst2[i+1]]= lst2[i] # 若两个dic的key相同,将value相加 for i,j in dic2.items(): if i in dic1.keys(): dic1[i] = dic1[i] + dic2[i] # 将两个dic的内容更新都一个dic中 dic2.update(dic1) # 查找更新后的dic中是否有系数为0的项,删除 for i in list(dic2.keys()): if not dic2.get(i): del dic2[i] # 将dic内容按照key排序,升序排列,存为list result_lst = sorted(dic2.items(), reverse=True) # 将list中的pair拆开 按照输出要求顺序摆放 for i in range(len(result_lst)): result.append(result_lst[i][1]) result.append(result_lst[i][0]) return result try: digitList1 =input().strip().strip('\n').split(' ') digitList2 =input().strip().split(' ') digitList1 = list(map(lambda x:int(x), digitList1)) digitList2 = list(map(lambda x:int(x), digitList2)) num1 = int(digitList1[0]) num2 = int(digitList2[0]) addpoly = [] addpoly = AddPoly(digitList1, digitList2) for x in addpoly: print(x, end=' ') except Exception as e: pass
#Python解释不多,致力于推广Python,所以给出Python实现 while True: try: digitList1 = list(map(int, input().split())) digitList2 = list(map(int, input().split())) num1 = digitList1[0] num2 = digitList2[0] temp = [] #保存整数对 for i in range(num1): temp.append([digitList1[i * 2 + 1], digitList1[i * 2 + 2]]) for i in range(num2): temp.append([digitList2[i * 2 + 1], digitList2[i * 2 + 2]]) temp.sort(key=lambda x: x[1],reverse=True) #对整数对进行排序,以次数为关键字排序,默认为升序,所以反转为降序 result = [] #保存结果整数对 lastNum = temp[0][1] modulus = temp[0][0] temp.pop(0) for i in temp: if i[1] == lastNum: modulus += i[0] else: if modulus != 0: #序数不为0才加入到结果中 result.append(modulus) result.append(lastNum) lastNum = i[1] modulus = i[0] if modulus != 0: #结尾还剩余最后项未在循环中处理,所以在结束后增加处理 result.append(modulus) result.append(lastNum) print(' '.join(map(str,result))) except Exception: break