将表达式拆分为术语集合

Vol*_*orm 8 wolfram-mathematica

我有一个很长的表达,我想分成一组术语.比如说我有:

a + b - c + d + 4*e - 3*f
Run Code Online (Sandbox Code Playgroud)

我想通过加法/减法将表达式拆分为:

{a, b, -c, d, 4*e, -3*f}
Run Code Online (Sandbox Code Playgroud)

我的动机是我希望按术语处理原始表达术语.这可能吗?

编辑:与我在Mathematica中实际处理的内容相比,给出的示例非常简单,只是因为我不确定如何在这里编写Math.

abc*_*bcd 11

要分割表达式,您需要使用Level.Level为您提供子表达式列表,您可以指定要返回子表达式的级别.在这种情况下,您需要levelspec1.

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}
Run Code Online (Sandbox Code Playgroud)

表达稍微复杂的示例:

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]}
Run Code Online (Sandbox Code Playgroud)


Sim*_*mon 6

由于没有人提到它,相当于 Yoda 的Level[expr, 1]构造是使用Apply将表达式的头部替换为List

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
Run Code Online (Sandbox Code Playgroud)

这两种方法基本上做相同的事情并且具有相同的计时(使用我的平均计时函数版本)

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}}
Run Code Online (Sandbox Code Playgroud)