validate string is valid maths

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Mon Jan 28 16:43:10 CET 2008


On Mon, 28 Jan 2008 15:10:54 +0000, Matthew_WARREN wrote:

> Hi pythoners.
> 
> I am generating strings of length n, randomly from the symbols
> 
> +-/*0123456789
> 
> What would be the 'sensible' way of transforming the string, for example
> changing '3++++++8' into 3+8

That's easy: replace pairs of + into a single +, repeatedly until there's 
nothing left to replace. And so forth. Here's an untested function. It's 
probably not even close to optimal, but for playing around it is probably 
fine.

def rationalise_signs(s):
    while "++" in s or "+-" in s or "-+" in s or "--" in s:
        s = s.replace("++", "+")
        s = s.replace("--", "+")
        s = s.replace("+-", "-")
        s = s.replace("-+", "-")
    return s




> or '3++--*-9' into '3+-9' such that  eval(string) will always return a
> number?
> 
> in cases where multiple symbols conflict in meaning (as '3++--*-9' the
> earliest valid symbols in the sequence should be preserved

You have four symbols, so there are just 4*4=16 sets of two symbols. 
Probably the easiest way is to just list them and their replacements out 
in a table:

table = {"++": "+", "+-": "-", "+*": "+", "+/": "+", 
    "-+": "-", "--": "+", "-*": "-", "-/": "-", 
    "*+": "*", "**": "*", "*/": "*", 
    "/+": "/", "/*": "/", "//": "/", }

Notice that both *- and /- don't get changed.



# Untested.
def rationalise_signs(s):
    prev = ''
    while s != prev:
        prev = s
        for key, value in table.items():
            s = s.replace(key, value)
    return s



-- 
Steven



More information about the Python-list mailing list