目錄
多項式
多項式是數學中相當重要的表達方式,如果使用計算機來處理多項式的各種相關運算,通常可以使用列表、鏈表和字典等數據結構來存儲多項式。
假如一個多項式 ,P(x)就爲一個n次多項式。
使用列表存儲多項式
使用一個二維列表來存儲多項式。二維列表中的每個元素均爲一個列表,存儲多項式中某一項的指數和係數。例如多項式 可以用二維列表表示爲:
[[5, 2], [4, 3], [2, 5], [1, 4], [0, 1]]
使用字典存儲多項式
字典也可以存儲一個多項式。字典中以多項式指數爲key,指數對應的係數和爲value。例如多項式 可以用字典存儲爲:
{5: 2, 4: 3, 2: 5, 1: 4, 0: 1}
解決方案
本文采用字典的數據結構來存儲多項式。當多項式相加時,指數相同(即Key相同),係數相加(即Value相加合併),最後得到的字典就是兩個多項式相加的結果。
代碼
class PolyException(Exception):
def __init__(self, message, code):
self.message = message
self.code = code
def parse_poly(poly):
"""
parse poly
:param poly: string
:return: dict
"""
poly_list = poly.split("+")
poly_dict = {}
for pos in range(len(poly_list)):
poly_list[pos] = poly_list[pos].strip()
if "X" not in poly_list[pos]:
if not poly_list[pos].isdigit():
raise PolyException("poly format error.", 1001)
temp_list = poly_list[pos].split("X^")
if len(temp_list) != 2 and len(temp_list) != 1:
raise PolyException("poly format error.", 1002)
if len(temp_list) == 2:
key = temp_list[1]
value = temp_list[0]
else:
key = 0
value = temp_list[0]
if key in poly_dict:
poly_dict[key] += value
else:
poly_dict[key] = value
return poly_dict
# 1. 輸入兩個多項式
try:
poly_a = input("Input polynomial A: ")
# poly_a = "3X^4+1"
poly_a_dict = parse_poly(poly_a)
poly_b = input("Input polynomial B: ")
# poly_b = "3X^4+5"
poly_b_dict = parse_poly(poly_b)
except PolyException as e:
print("errcode: %s" % e.code)
print("errmsg: %s" % e.message)
exit(e.code)
# 2. 多項式相加
for key in poly_b_dict:
if key in poly_a_dict:
poly_a_dict[key] = int(poly_a_dict[key]) + int(poly_b_dict[key])
else:
poly_a_dict[key] = int(poly_b_dict[key])
# 3. 輸出結果
print("result is: ")
message = ""
for key in poly_a_dict:
if key == 0:
message += str(poly_a_dict[key]) + " + "
else:
message += str(poly_a_dict[key]) + "X^" + str(key) + " + "
message = message[:-3]
print(message)
代碼走讀
# 自定義異常
class PolyException(Exception):
def __init__(self, message, code):
self.message = message
self.code = code
# 解析多項式字符串,將多項式轉換成一個字典
def parse_poly(poly):
"""
parse poly
:param poly: string
:return: dict
"""
# 通過‘+’將多項式分割成每個子項
poly_list = poly.split("+")
poly_dict = {}
for pos in range(len(poly_list)):
poly_list[pos] = poly_list[pos].strip()
if "X" not in poly_list[pos]:
if not poly_list[pos].isdigit():
raise PolyException("poly format error.", 1001)
temp_list = poly_list[pos].split("X^")
if len(temp_list) != 2 and len(temp_list) != 1:
raise PolyException("poly format error.", 1002)
if len(temp_list) == 2:
key = temp_list[1]
value = temp_list[0]
else:
key = 0
value = temp_list[0]
if key in poly_dict:
poly_dict[key] += value
else:
poly_dict[key] = value
return poly_dict
# 1. 輸入兩個多項式
try:
poly_a = input("Input polynomial A: ")
# poly_a = "3X^4+1"
poly_a_dict = parse_poly(poly_a)
poly_b = input("Input polynomial B: ")
# poly_b = "3X^4+5"
poly_b_dict = parse_poly(poly_b)
except PolyException as e:
print("errcode: %s" % e.code)
print("errmsg: %s" % e.message)
exit(e.code)
# 2. 多項式相加
for key in poly_b_dict:
if key in poly_a_dict:
poly_a_dict[key] = int(poly_a_dict[key]) + int(poly_b_dict[key])
else:
poly_a_dict[key] = int(poly_b_dict[key])
# 3. 輸出結果
print("result is: ")
message = ""
for key in poly_a_dict:
if key == 0:
message += str(poly_a_dict[key]) + " + "
else:
message += str(poly_a_dict[key]) + "X^" + str(key) + " + "
message = message[:-3]
print(message)