简体   繁体   中英

Enumerate coefficients

I want to make a program to detect a correct expanding. For example: I want to expand (x + 2)*(x - 3) . The solution is x*x -x -6 But x*x +2*x -3*x -6 is a correct solution. I want to detect such correct (but unsimplified) expansions.

If you allow a user to input the expression as a string and parse the expression with evaluate=False as shown here you can compare the number of arguments in what is entered with the fully simplified version.

>>> expr = (x - 3)*(x + 2)
>>> expanded = expand(expr)
>>> ans = 'x*x +2*x -3*x -6'  # obtained from user
>>> if S(ans) == expanded:  # it's right
...     if len(parse_expr(ans, evaluate=False).args) != len(expanded.args):
...         print('right, but not simplified')

The unsimplified ans will have 4 arguments while the expanded form will have 3.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM