Simple expression cleanup

Updated TrustyTony 0 Tallied Votes 409 Views Share

Because of C++ code snippets not dealing with multiple +- in sequence (or even negative number) in expressions, I post this, as it is so much easier for me than C/C++.

EDIT: Fixed signs together with '(' issues and '+' at beginning removing without lstrip, removed separate now unused '(' branch from if. Changed name of prev to plusminus.

""" Expression cleanup from spaces and multiple +- """

expr = "--4-+--4--  - - ++-++ ( ++  +-- 4* 6.5 / 4.3e6 )- -  -6"
plusminus = new_expr = ''
for c in expr:
    if c.isdigit() or c == '(':
        # do not put + in front of expression or inside ( in front of first expression
        new_expr += c if plusminus == '+' and  (not new_expr or new_expr.endswith('(')) else plusminus + c
        plusminus = ''
    elif c in '+-':
        plusminus = '-' if (c == '-' and plusminus != '-') or (c=='+' and plusminus =='-') else '+'
    elif c != ' ':
        new_expr += c
        if plusminus:
            raise ValueError("+- not in front of number or '('!")
                    
if plusminus:
    raise ValueError("Sign at end of expression!")
else:
    print("%s\n%s" % (expr, new_expr))
    assert eval(expr) == eval(new_expr)

"""Output:
--4-+--4--  - - ++-++ ( ++  +-- 4* 6.5 / 4.3e6 )- -  -6
4-4-(4*6.5/4.3e6)-6
"""