多项式相加 分数 15 全屏浏览题目 切换布局 作者 陈春晖 单位 浙江大学 编写程序实现两个多项式相加。例如: p(x)=5x 10 +8x 5 -x+10 g(x)=3x 8 +x-3 f(x)+g(x)=5x 10 +8x 5 +3x 8 +7 输入格式: 在第一行输入第一个多项式。如p(x)=5x 10 +8x 5 -x+10输入是: 5 10, 8 5, -1 1, 10 0 在第二行输入第二个多项式。如g(x)=3x 8 +x-3输入是:3 8, 1 1, -3 0 在第三行输入x指数值,如x指数值是1,x 2 指数值是2。 输出格式: 对应输入的x指数值,输出多项式和中这项的系数。
时间: 2023-11-12 10:09:38 浏览: 345
以下为 Python3 代码实现:
```python
# 定义多项式类
class Polynomial:
def __init__(self, coeffs):
self.coeffs = coeffs
# 多项式相加
def __add__(self, other):
# 计算两个多项式的系数和
coeffs_sum = {}
for exp, coeff in self.coeffs.items():
coeffs_sum[exp] = coeff + coeffs_sum.get(exp, 0)
for exp, coeff in other.coeffs.items():
coeffs_sum[exp] = coeff + coeffs_sum.get(exp, 0)
# 返回新的多项式对象
return Polynomial(coeffs_sum)
# 计算多项式在 x 指数值处的值
def value_at(self, x):
value = 0
for exp, coeff in self.coeffs.items():
value += coeff * x ** exp
return value
# 读取第一个多项式
p_coeffs = {}
for term in input().split(', '):
coeff, exp = map(int, term.split())
p_coeffs[exp] = coeff
p = Polynomial(p_coeffs)
# 读取第二个多项式
g_coeffs = {}
for term in input().split(', '):
coeff, exp = map(int, term.split())
g_coeffs[exp] = coeff
g = Polynomial(g_coeffs)
# 读取 x 指数值
x = int(input())
# 计算多项式和
f = p + g
# 输出在 x 指数值处的值
print(f.value_at(x))
```
输入样例:
```
5 10, 8 5, -1 1, 10 0
3 8, 1 1, -3 0
1
```
输出样例:
```
7
```
阅读全文