PAT 1009 Product of Polynomials python解法


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 ​ a​N​1 N2 ​ a​N2 … NK ​ 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 product 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 up to 1 decimal place.
Sample Input: 2 1 2.4 0 3.2 2 2 1.5 1 0.5
Sample Output: 3 3 3.6 2 6.0 1 1.6
問題を解く構想.
テーマは多項式の乗算を求めることです.各多項式のべき乗は一意であり、多項式は辞書で格納することができ、keyはべき乗、valueは係数である.2.2つの辞書をループし、keyを加算し、valueを乗算し、keyが存在するかどうかを判断することを覚えています.3.結果を得た後、valueが0のキー値ペアを削除します.そうしないと、テストポイント0が過ぎません.4.結果辞書をリストに変換して降順に並べ替えます.最初の要素は辞書の長さです.5.リストを文字列に変換して結果を出力します.
list_a = input().split(' ')
list_b = input().split(' ')
dict_a = dict(zip([int(_) for _ in list_a[1:][::2]],[float(_) for _ in list_a[2:][::2]])) #{1: 2.4, 0: 3.2}
dict_b = dict(zip([int(_) for _ in list_b[1:][::2]],[float(_) for _ in list_b[2:][::2]])) #{2: 1.5, 1: 0.5}

dict_c = {}
for k1,v1 in dict_a.items():
    for k2,v2 in dict_b.items():
        if k1+k2 in dict_c.keys():
            dict_c[k1+k2] += round(v1*v2, 1)
        else:
            dict_c.update({k1+k2:round(v1*v2, 1)})
            
#     :dict_c.items()             
#for k,v in dict_c.items():
#    if v == 0.0:
#        del dict_c[k]

for k,v in list(dict_c.items()):
    if v == 0.0:
        del dict_c[k]
        
list_c = [len(dict_c)]    
temp_c = list(dict_c.items())
temp_c.sort(reverse=True)

for item in temp_c:
    list_c.extend(item)
    
print(' '.join([str(_) for _ in list_c]))