[Python]PAT 甲级 1002 A+B for Polynomials

[Python]PAT 甲级 1002 A+B for Polynomials

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 N
​1
​​ a
​N
​1
​​
​​ N
​2
​​ a
​N
​2
​​
​​ … N
​K
​​ a
​N
​K
​​
​​

where K is the number of nonzero terms in the polynomial, N
​i
​​ and a
​N
​i
​​
​​ (i=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that 1≤K≤10,0≤N
​K
​​ <⋯ ​2
​​ ​1
​​ ≤1000.

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

group1 = list(map(float, input().split()))
group2 = list(map(float, input().split()))
# for i in group1:
#     if i % 1 == 0:
#         i = int(i)
#     if i != group1[-1]:
#         print(i,end=" ")
# else:
#     print(i,end="")
# print()
len_group1 = int(group1[0]) * 2
len_group2 = int(group2[0]) * 2
group1 = group1[1: ]
group2 = group2[1: ]
dict_group1 = {}
dict_group2 = {}
i, j = 0, 0
while i < len_group1:
    dict_group1[group1[i]] = group1[i+1]
    i += 2
while j < len_group2:
    if group2[j] not in dict_group1:
        dict_group1[group2[j]] = group2[j+1]
    else:
        dict_group1[group2[j]] += group2[j+1]
    j += 2
result = []
for m in sorted(dict_group1, reverse=True):
    if dict_group1[m] != 0:
        result.append((int(m), round(dict_group1[m], 1)))
print(len(result),end="")
if len(result) !=0:
    print(" ",end="")
num = 0
for x in result:
    print(x[0],end=" ")
    if num != len(result)-1:
        print(x[1],end=" ")
    else:
        print(x[1],end="")
    num += 1

你可能感兴趣的:(PAT)