[英]Parse a string of a linear equation into a vector of the coefficients (Python)
我正在尋找一種采用線性方程串並輸出系數向量的Python解決方案。
為使操作簡單起見,假設我有一組方程式:
x
只出現一次 然后我想獲得矢量化表示
x
系數 x
出現一樣 我在這里給出幾個輸入輸出方程,以了解一些挑戰:
'2*x+3=2+5' => [2, -3, 2, 5]
'88/8=x' => [8, 88, 0, 0]
'74=(35+18)+3*x' => [3, 74, -35, -18]
'((4+4)*6)=x'] => [1/6, 4, 4, 0]
'-X=(91.0+88.0)' => [-1, 91, 88, 0]
'X=(30.0/10.0)' => [10, 30, 0, 0]
'0.16 + 0.41 = 2*x - 0.08' => [2, 0.16, 0.41, 0.08]
'(0.25 + 0.37)*2 = x' => [1/2, 0.25, 0.37, 0]
我開始編寫一個“嚴格”的乏味的“蠻力”解決方案,在此過程中無意中發現了幾次,並發現必須有一種更好,更聰明的方法來實現此目的...
- 我正在使用
sympy
軟件包,這使事情變得容易一些。 隨着sympify
和formula.split
和這樣的我能提取x
系數和公式的結果(雖然我真的不關心結果,但只有向量表示 )- 我看到這個和這個 ,但他們都在不同的語言,而不是完全是我所期待的。
如此,有人知道如何在Python中執行此操作嗎?
謝謝! :)
這可以使您朝正確的方向前進:
>>> def peq(s):
... from sympy import S
... l, r = t = S(s, evaluate=False)
... free = t.free_symbols
... assert len(free) == 1
... x = free.pop()
... if r.has(x):
... l, r = r, l
... assert not r.has(x)
... assert l.has(x)
... assert not l.diff(x).free_symbols
... v = []
... v.append(l.coeff(x))
... v.append(-(l.subs(x, 0)))
... if not r.is_Add:
... v.extend([r, S.Zero])
... else:
... assert r.is_Add and len(r.args) == 2
... v.extend(r.args)
... return v
>>> peq('2*x+3,-2+5/3')
[2,−3,−2,5/3]
>>> peq('2*x+3,-2')
[2,−3,−2,0]
>>> peq('x,-2')
[1,0,−2,0]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.