2011-10-08 58 views
6

我有一個很長的表達式,我想將其分解爲一組術語。例如說我有:將表達式拆分爲術語集合

a + b - c + d + 4*e - 3*f 

我想加法/減法分割表達式爲:

{a, b, -c, d, 4*e, -3*f} 

我對這種動機是,我要處理的項原始表達式項。這可能嗎?

編輯:給出的例子與我在Mathematica中處理的相比非常簡單,只是我不確定如何在這裏寫數學。

回答

9

要拆分表達式,您需要使用LevelLevel爲您提供了子表達式的列表,您可以指定您希望返回子表達式的級別。在這種情況下,你需要levelspec 1.

In[1]:= expr = a + b - c + d + 4 e - 3 f; 
In[2]:= Level[expr, 1] 

Out[2]= {a, b, -c, d, 4 e, -3 f} 

一個稍微更復雜的表達一個例子:

In[3]:= expr2 = a^2 + 5 bc/ef - Sqrt[g - h] - Cos[i]/Sin[j + k]; 
In[4]:= Level[expr2, 1] 

Out[4]= {a^2, (5 bc)/ef, -Sqrt[g - h], -Cos[i] Csc[j + k]} 
4

您可能還可以使用MonomialList,如果你的表達是多項式:

In[56]:= MonomialList[a + b - c + d + 4*e - 3*f] 

Out[56]= {a, b, -c, d, 4 e, -3 f} 

(非多項式,如Yoda的expr2不工作)。

4

由於沒有人提到它,相當於Yoda的Level[expr, 1]建設是使用ApplyList更換一個表達式的頭部:

In[1]:= expr = a + b - c + d + 4 e - 3 f; 

In[2]:= List @@ expr 
     Level[expr, 1] == % 

Out[2]= {a, b, -c, d, 4 e, -3 f} 
Out[3]= True 


In[4]:= expr2 = a^2 + 5 bc/ef - Sqrt[g - h] - Cos[i]/Sin[j + k]; 

In[5]:= List @@ expr2 
     Level[expr2, 1] == % 

Out[5]= {a^2, (5 bc)/ef, -Sqrt[g - h], -Cos[i] Csc[j + k]} 
Out[6]= True 

這兩種方法基本上做同樣的事情,並具有相同的時序(使用我的版本average timing function的)

In[1]:= SetOptions[TimeAv, Method -> {"MinNum", 80000}, "BlockSize" -> 20000]; 

In[7]:= List @@ expr // TimeAv 

Total wall time is 0.244517, total cpu time is 0.13 
and total time spent evaluating the expression is 0.13 

The expression was evaluated 80000 times, in blocks of 20000 runs. This yields 
a mean timing of 1.625*10^-6 with a blocked standard deviation of 2.16506*10^-7. 

Out[7]= {1.625*10^-6, {a, b, -c, d, 4 e, -3 f}} 

In[8]:= Level[expr, 1] // TimeAv 

Total wall time is 0.336927, total cpu time is 0.16 
and total time spent evaluating the expression is 0.16 

The expression was evaluated 80000 times, in blocks of 20000 runs. This yields 
a mean timing of 2.*10^-6 with a blocked standard deviation of 3.53553*10^-7. 

Out[8]= {2.*10^-6, {a, b, -c, d, 4 e, -3 f}} 
3

您還可以使用Replace

In[65]:= Replace[a + b - c + d + 4*e - 3*f, HoldPattern[Plus[a___]] :> {a}] 

Out[65]= {a, b, -c, d, 4 e, -3 f} 

您需要使用HoldPattern(或等同的一些技巧),以防止Plus[a__]從評估到a__,其中有隻包裹在一個列表中的第一個參數,而不是創建的參數列表Plus結果。

+3

規則的另一種可能性是'Plus [a_,b___]:> {a,b}' – Simon

+1

如果有人贊成'Replace',則可以將其與'Apply'組合爲另一個選項:'Replace [a + b - c + d + 4 * e - 3 * f,a_Plus:> List @@ a]'或者,也許:'替換[a + b - c + d + 4 * e - 3 * f,Plus - > List,1 ,頭 - >真]' –