16

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.

3 Answers 3

9

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))
3
  • @ asmeurer thanks but this has the same issue as @Bjoern as I added in a comment below. It collects like terms.
    – harish
    Commented Jun 3, 2016 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
    Commented Jun 3, 2016 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.
    – harish
    Commented Jun 4, 2016 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.

0
2

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⎠
4
  • Thanks @Bjoern but if there are like terms, args collects them. (eg. 1/(x+1)+4*x/(x-1)+3-4*x2+10*x2). Is it possible to stop this?
    – harish
    Commented Jun 1, 2016 at 12:25
  • @FermiparadoxSO yes it is without quotes. Sorry about confusion.
    – harish
    Commented Jun 1, 2016 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
    Commented Jun 1, 2016 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) Commented Jun 1, 2016 at 20:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.