PAT-1002 A+B for Polynomials (25 分) python
原题链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805526272000000
This time, you are supposed to find A+B where A and B are two polynomials.
Input Specification:
Each input file contains one test case. Each case occupies 2 lines, and each line contains the information of a polynomial:
K N1 aN1 N2 aN2 ... NK aNK
where K is the number of nonzero terms in the polynomial, Ni and aNi (,) are the exponents and coefficients, respectively. It is given that 1,0.
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
多项式加减
错了一个样例,格式错误,wq,后面回来再想
1 a1=input().split() 2 b1=input().split() 3 p=[0]*1005 4 ans=a1[1:]+b1[1:] 5 lens=len(ans) 6 7 for i in range(0,lens-1,2): 8 tmp=int(ans[i]) #次数 9 p[tmp]+=float(ans[i+1]) 10 11 # print(p[:10]) 12 numm=0 13 list1=[] 14 for i in range(1004,-1,-1): 15 if p[i]!=0.0: 16 numm+=1 17 p[i]=round(p[i],1) #保留一位小数 18 list1.append(str(i)) 19 list1.append(str(p[i])) 20 print(numm,end=' ') 21 print(" ".join(list1),end='')
菠萝换了一种写法,也是卡了一个样例
1 a1=input().split() 2 b1=input().split() 3 i=j=1 4 num=0 5 ka,kb=int(a1[0]),int(b1[0]) 6 ans=[] 7 while i<=ka and j<=kb: 8 if a1[2*i-1]==b1[2*j-1]: 9 ans.append(a1[2*i-1]) 10 ans.append(format(float(a1[2*i])+float(b1[2*j]),'.1f')) 11 i+=1 12 j+=1 13 num+=1 14 elif int(a1[2*i-1])>int(b1[2*j-1]): 15 ans.append(a1[2*i-1]) 16 ans.append(format(float(a1[2*i]),'.1f')) 17 i+=1 18 else: 19 ans.append(b1[2*j-1]) 20 ans.append(format(float(b1[2*j]),'.1f')) 21 j+=1 22 num=ka+kb-num 23 if i<=ka: 24 ans.extend(a1[2*i-1:]) 25 elif j<=kb: 26 ans.extend(b1[2*j-1:]) 27 nums=0 28 anss=[] 29 for i in range(num): 30 if float(ans[2*i+1])!=0: 31 anss.append(ans[2*i]) 32 anss.append(format(float(ans[2*i+1]),'.1f')) 33 nums+=1 34 print(str(nums),' '.join(anss))