簡體   English   中英

您如何僅評估 python 中方程的一部分?

[英]How do you evaluate only one part of an equation in python?

import math

term = ['math.sqrt', 'math.pi', 'math.sin', 'math.cos', 'math.tan', 
'math.log', 'math.log', 'math.pow', 'math.cosh', 'math.sinh', 
'math.tanh', 'math.sqrt', 'math.pi', 'math.radians', 
'math.e','math.radians']
replace = ['√', 'π', 'sin', 'cos', 'tan', 'log', 'ln', 'pow', 'cosh', 
'sinh', 'tanh', 'sqrt', 'pi', 'radians', 'e', 'rad']

equation = input('')

for word in replace:
    equation = equation.replace(word, term[replace.index(word)])

我試圖僅評估在“術語”中也存在的“方程式”中的計算,然后替換我們在“方程式”中找到的值

前任。 輸入:x + 5 - sqrt(4) = 9

然后我的程序將用 math.sqrt(4) 替換 sqrt(4)

然后它應該計算 math.sqrt(4); 所以 math.sqrt(4) = 2

最后在“方程式”中用 sqrt(4) 替換 2; 所以,方程 = x + 5 - 2 = 9

我可以幫助你,但使用eval語句,這通常被認為是一種不好的做法

解決方案是:

' '.join([str(eval(s)) if ('(' in s and ')' in s) else s for s in equation.split(' ')])

讓我們分解一下:

  • equation.split(' ')將方程字符串拆分為一個由空格分隔的字符串列表: ['x', '+', '5', '-', 'math.sqrt(4)', '=', '9']
  • [str(eval(s)) if ('(' in s and ')' in s) else s for s in equation.split(' ')]對列表的任何元素運行str(eval(s))滿足條件('(' in s and ')' in s) (我假設您只在 function 本身上打開和關閉括號)。
  • str(eval(s))在寫入時評估 function,然后將其轉換回字符串。
  • ' '.join([...])加入列表元素,將空格放回原處。

結果如下:

'x + 5 - 2.0 = 9'

請記住將您的空間放在輸入中的正確位置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM