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​​ <⋯<N​2​​ <N​​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

解題思路

題目是求多項式相乘
1.每個多項式中冪次是唯一的,可以將多項式使用字典進行儲存,key是冪次,value是係數。
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]))
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章