14

I have an expression as: 1/(x+1)+4*x/(x-1)+3-4*x**2+10*x**2

What I need is a list that contain the terms in this expression.
i.e. [1/(x+1), 4*x/(x-1), 3, -4*x**2 , 10*x**2]

update: It should not collect like terms. Therefore the list should have -4*x** 2 and 10*x** 2 separately and not 6*x**2 after collecting like terms.

harsh
  • 2,399
  • 9
  • 29
  • 47

3 Answers3

8

The right way to do this is Add.make_args. This is the same things as expr.args from Bjoern's answer, except if the expression is not an Add (a single term), it still gives that term, instead of traversing into that expression.

In [20]: expr = 1/(x+1)+4*x/(x-1)+3-4*x**2

In [21]: print(Add.make_args(expr))
(3, 1/(x + 1), -4*x**2, 4*x/(x - 1))
asmeurer
  • 86,894
  • 26
  • 169
  • 240
  • @ asmeurer thanks but this has the same issue as @Bjoern as I added in a comment below. It collects like terms. – harsh Jun 03 '16 at 15:13
  • @harsh the list in my answer is the same as the list you indicated you wanted in your question (except for re-ordering). If the re-ordering is a problem, I'm afraid you're out of luck, as SymPy doesn't keep track of the order that an expression is made from. If it is some other issue, please edit your question and clarify. – asmeurer Jun 03 '16 at 20:02
  • I am sorry if it was not clear. I wanted not to collect like terms. I updated the question. Sorry if I confused you. Taking it as a string worked. – harsh Jun 04 '16 at 10:51
2

Based on the question and comments, if you can get the expression as a string, you can do something like this if you want to avoid term collection.

(sympify("1/(x+1)+4*x/(x-1)+3-4*x**2+10*x**2", evaluate=False)).args

this will return all the terms without collecting like terms.

1

In this case it is very easy:

>>> expr = 1/(x+1)+4*x/(x-1)+3-4*x**2
>>> expr.args
⎛     1        2   4⋅x ⎞
⎜3, ─────, -4⋅x , ─────⎟
⎝   x + 1         x - 1⎠
Bjoern Dahlgren
  • 931
  • 8
  • 18
  • Thanks @Bjoern but if there are like terms, args collects them. (eg. 1/(x+1)+4*x/(x-1)+3-4*x**2+10*x**2). Is it possible to stop this? – harsh Jun 01 '16 at 12:25
  • @FermiparadoxSO yes it is without quotes. Sorry about confusion. – harsh Jun 01 '16 at 13:05
  • @harsh Offtopic: Do you mean `1/(x+1)+4*x/(x-1)+3-4*x**2+10*x**2`? (text between double * is converted to bold, unless you place it inside code format ``) – user Jun 01 '16 at 13:06
  • @harsh it is actually not `.args` that collects them, it happens on construction, try: `Add(1/(x+1), 4*x/(x-1), 3, -4*x**2, 10*x**2, evaluate=False)` – Bjoern Dahlgren Jun 01 '16 at 20:48