-->

# 编程题：一元多项式的加法运算

Luz2年前 (2022-12-13)题库2043

### 输入格式:

（1）每行输入两个数字，第一个表示幂次，第二个表示该幂次的系数，遇到-1 -1表示一个多项式输入结束；

（2）所有的系数都是整数，不输入系数为0的数据项；

（3）每个多项式的幂值不超过100，且不重复。

### 输出格式:

2x6+3x5+12x3-6x+20

### 输入样例1:

in
6 2
5 3
3 12
1 6
0 20
-1 -1
6 2
5 3
2 12
1 6
0 20
-1 -1

### 输出样例1:

out
4x6+6x5+12x3+12x2+12x+40

### 输入样例2:

in
6 1
1 1
-1 -1
5 -1
0 -1
-1 -1

### 输出样例2:

out
x6-x5+x-1

### 输入样例3:

in
1 1
-1 -1
1 -1
-1 -1

### 输出样例3:

out
0

#### 评论列表

6个月前 (01-24)

poly = {}
while True:
exp, coeff = map(int, input().split())
if exp == -1 and coeff == -1:
break
poly[exp] = coeff
return poly
result = {}
# Combine the keys from both polynomials
for exp in set(poly1.keys()).union(poly2.keys()):
# Sum the coefficients if they exist in both, else just take the existing one
result[exp] = poly1.get(exp, 0) + poly2.get(exp, 0)
return result
def format_polynomial(poly):
# Sort the terms by descending exponent
terms = sorted(poly.items(), reverse=True)
# Skip terms with a coefficient of 0
terms = [(exp, coeff) for exp, coeff in terms if coeff != 0]
# Format each term based on exponent and coefficient
result_terms = []
for exp, coeff in terms:
if exp == 0:
term = f"{coeff}"
else:
coeff_str = f"{coeff}" if abs(coeff) != 1 else '' if coeff ˃ 0 else '-'

#### 发表评论

◎欢迎参与讨论，请在这里发表您的看法和观点。