我有一个用户输入的字符串,我需要使用它构建一个图表。有没有办法将字符串转换为表达式?类似“x**2+x*2+12”的字符串。这只是一个示例;代码本身包含 Try 和 Expect。示例代码:
import numpy as np
import matplotlib.pyplot as plt
a = input()
x = np.arange(-10, 10.01, 0.01)
plt.plot(x,a)
plt.show()
我有一个用户输入的字符串,我需要使用它构建一个图表。有没有办法将字符串转换为表达式?类似“x**2+x*2+12”的字符串。这只是一个示例;代码本身包含 Try 和 Expect。示例代码:
import numpy as np
import matplotlib.pyplot as plt
a = input()
x = np.arange(-10, 10.01, 0.01)
plt.plot(x,a)
plt.show()
我有一个用于解方程的电报机器人代码,它工作得很好,但如果您在其中输入方程以外的其他内容,它就会停止工作,并且需要重新启动代码。如何修复它?
import json
from sympy import symbols, solve, parse_expr, simplify
from collections.abc import Mapping
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
tok= ''
bot = telebot.TeleBot(tok)
transformations = (standard_transformations + (implicit_multiplication_application,))
def add_user(message,name):
file = open('id{}.json'.format(message.from_user.id), 'w')
file.write(str(message))
file.close()
@bot.message_handler(commands=['start'])
def intro(message):
name =message.from_user.first_name
str = f'Привет,{name} , этот бот решает уравнения и строит графикиヽ(´ー`)人(´∇`)人(`Д´)ノ'
bot.send_message(message.from_user.id, str)
add_user(message,message.from_user.id)
def map_operations(formula_str):
return formula_str.replace("^", "**").replace("=", "-")
def solving(formula):
f = parse_expr(map_operations(formula), transformations=transformations)
roots = solve(f)
string = 'x='
for el in roots:
string += str(el)
string += ';'
return string
@bot.message_handler(content_types=["text"])
def handle_text(message):
ur = str(message.text)
root= solving(ur)
bot.send_message(message.from_user.id,root)
print(ur, root)
@bot.message_handler(commands=['graph'])
def graph(message):
bot.send_message(message.from_user.id, 'Функция пока не работает T_T')
bot.polling(non_stop='True')```