用Python写一个一元多项式计算器
时间: 2023-06-09 18:03:03 浏览: 166
好的,下面是用Python编写一个简单的一元多项式计算器的代码:
```python
import re
def calculate(expression, x):
# 将表达式中的系数和指数分离出来,存入字典中
terms = {}
pattern = r'([-+]?\d*)(?:x(?:\^(\d+))?)?'
for coefficient, exponent in re.findall(pattern, expression):
if coefficient == '':
coefficient = '+1'
elif coefficient == '-':
coefficient = '-1'
exponent = int(exponent) if exponent else 0
terms[exponent] = int(coefficient)
# 计算多项式在给定的x处的值
result = 0
for exponent, coefficient in terms.items():
result += coefficient * x ** exponent
return result
expression = input("请输入一个一元多项式(如3x^2+2x-1):")
x = float(input("请输入x的值:"))
print("该多项式在x={}处的结果为:{}".format(x, calculate(expression, x)))
```
这个代码可以读入一个一元多项式的表达式和$x$的值,然后计算该多项式在给定的$x$处的值。例如,输入"3x^2+2x-1"和$x=2$,则输出结果为$3\times2^2+2\times2-1=11$。注意,这个代码没有对输入的表达式进行严格的语法检查,使用时需要保证输入的表达式是一个合法的一元多项式。
阅读全文
相关推荐
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)