0

I am trying to break an equation step by step by checking the arithmetic dependencies. I have tried using the sympy.simplify() and sympy.expand(), but I am not getting the desired output.

Input:

m = 10*((9*(x**3) + 2*(y**4))**3) + 3*(y**3 + z)

Expected Output: An array containing all the possibilities as mentioned below

output_list = ['10*((9*(x**3) + 2*(y**4))**3)',
               '(9*(x**3) + 2*(y**4))**3',
               '9*(x**3) + 2*(y**4)',
               '9*(x**3)',
               'x**3',
               'x',
               '2*(y**4)',
               'y**4',
               'y',
               '3*(y**3 + z)',
               'y**3 + z',
               'y**3',
               'y',
               'z']

I split the equation every time by observing the main dependency to get the next possible dependent equation and finally to the dependent variables.

In the above equation, 10(9(x^3) + 2(y^4))^3, 10 is multiplied after substituting the values of x and y. So, I first removed 10. Then, I have removed the cube, followed by the addition symbol, and etc. to get the output_list.

How can I get the output_list using Python?

Shikhar
  • 93
  • 7
  • Not sure I understand your description: when you say "dependency" do you mean arithmetic operator? Because if so, `ast` is built in, and you probably want to have a look at it. (see, for example, https://stackoverflow.com/questions/5049489/evaluating-mathematical-expressions-in-python) – Mike 'Pomax' Kamermans Feb 16 '23 at 21:42
  • Yes, dependency here is the arithmetic operator. In this equation, 10(9(x^3) + 2(y^4))^3, after substituting the x and y values, the whole answer is getting multiplied by 10. So, I have eliminated 10 first from the considered equation. – Shikhar Feb 16 '23 at 21:58

1 Answers1

0

This pretty closely gives your expected output by printing the args of the expression recursively:

def go(eq):
    if eq.is_Number:return
    if not eq.args:
        print(eq)
    else:
        print(eq)
        for a in eq.args:
            go(a)


>>> go(m)
10*(9*x**3 + 2*y**4)**3 + 3*(y**3 + z)
10*(9*x**3 + 2*y**4)**3
(9*x**3 + 2*y**4)**3
9*x**3 + 2*y**4
9*x**3
x**3
x
2*y**4
y**4
y
3*(y**3 + z)
y**3 + z
y**3
y
z

You might also take a look at preorder_traversal and postorder_traversal which are both in sympy.core.traversal.

smichr
  • 16,948
  • 2
  • 27
  • 34
  • It is returning some other below-mentioned values which are not expected. `'3*Y**3 + 3*Z + 10*(9*X**3 + 2*Y**4)**3','3*Z','Z','3*Y**3','Y**3','Y'` – Shikhar Feb 17 '23 at 00:34
  • Use `m=S('10*((9*(x**3) + 2*(y**4))**3) + 3*(y**3 + z)',evaluate=False)` or else the 10 will automatically be distributed. – smichr Feb 17 '23 at 16:18