Sympy check whether there's constants in the expression before simplification

Viewed 59

I'm trying to simplify some expressions with Sympy. However, I wanna filter out some expressions with Add/Sub with constants "before" simplification.

For instance,

parse_expr("abc_mmw * 2 * 5", evaluate=False) => valid
parse_expr("abc_mmw * 2 * 5 + 5", evaluate=False) => invalid (Adding 5, which is a constant)
parse_expr("abc_mmw * 2 * 5 + 5 - 5", evaluate=False) => invalid (Even though it's the same as "abc_mmw * 2 * 5" after simplificaton)

Without evalute=True, it is quite confusing me how to check whether there is an addition/a subtraction with constants or how to get the constants in the expression.

Is there any way to deal with the condition with built-in Sympy functions? Thanks!

2 Answers

By constant I assume you mean number. You can check if the expression is an addition and whether any of its argument is a number. Something like this:

def is_valid(expr):
    if expr.is_Add and any(not t.is_number for t in expr.args):
        return False
    return True

expr1 = parse_expr("abc_mmw * 2 * 5", evaluate=False)
expr2 = parse_expr("abc_mmw * 2 * 5 + 5", evaluate=False)
expr3 = parse_expr("abc_mmw * 2 * 5 + 5 - 5", evaluate=False)

print(is_valid(expr1))
# out: True
print(is_valid(expr2))
# out: False
print(is_valid(expr3))
# out: False

After few days with the idea provided by @Davide_sd, I came up with this solution.

This solution will also deal with expr = sympy.parse_expr("(abc_mmw + 1 * 5) * (cde_sub6)", evaluate=False)

def is_valid(expr):
    parent_is_add = expr.func.is_Add
    for arg in expr.args:
        if(arg.is_Add):
            return is_valid(arg)
        elif(arg.is_number and parent_is_add):
            return False
    return True
Related