一个代码,读入两个多项式,个数不确定,最后按照幂次从高到低输出

下午好🌅🌅🌅
本答案参考ChatGPT-3.5
针对这个问题,我们可以分为以下几个步骤来解决:
读取输入的两个多项式,将每个多项式存储为一个字典,字典的键为幂次,值为系数。我们可以使用一个循环来逐行读取输入,并将幂次和系数分别存储在字典中。
对两个多项式的幂次进行合并,可以通过将两个字典的键合并为一个新的集合,并进行升序排序,以确保从高到低输出。
遍历排序后的幂次集合,根据字典获取对应的系数。如果系数为0,则不输出该项。
将幂次和系数拼接成字符串,并根据幂次添加指数符号。
将所有幂次和系数拼接成最终的结果字符串。可以使用一个列表来存储拼接好的字符串项,然后使用字符串的.join方法来连接所有项。
下面是修改后的代码示例:
# 读取第一个多项式
poly1 = {}
while True:
power, coefficient = input().split()
power = int(power)
coefficient = int(coefficient)
if power == 0:
break
poly1[power] = coefficient
# 读取第二个多项式
poly2 = {}
while True:
power, coefficient = input().split()
power = int(power)
coefficient = int(coefficient)
if power == 0:
break
poly2[power] = coefficient
# 合并幂次集合并排序
powers = sorted(set(poly1.keys()) | set(poly2.keys()), reverse=True)
# 拼接最终结果字符串
result = []
for power in powers:
if power in poly1:
coefficient = poly1[power]
if coefficient != 0:
term = str(coefficient) + 'x' + str(power)
result.append(term)
if power in poly2:
coefficient = poly2[power]
if coefficient != 0:
term = str(coefficient) + 'x' + str(power)
result.append(term)
output = '+'.join(result)
print(output)
希望能对你有帮助!