Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def validate_expr(expr):
- # This function validates the user-suplied expression
- # It returns a validity status (True or False)
- # and also it returns a revised version of the input expression, where references to
- # variable x0 thru x9 are replaced by references to dictionary items xd['x1'] to xd['x9']
- outexpr = ""
- # check there are the same number of closing brackets as there are opening brackets
- if (expr.count("(") - expr.count(")")):
- return (False, outexpr)
- work = expr # make a copy of the input expression for working on
- work = work.replace("(", " ")
- work = work.replace(")", " ")
- esplit = work.split() # split the expression on white space
- for item in esplit:
- # check for a valid variable x0 thru x9
- if item[0].lower() == 'x' and item[1].isdigit() and len(item) == 2:
- continue
- # if not a variable, only "and" and "or" are valid
- if item.lower() in ("and", "or"):
- continue
- return (False, outexpr)
- # Process the expression changing all variables x0 to x9 to dictionary references
- j = 0
- while j < len(expr):
- ch = expr[j].lower()
- if ch == 'x':
- outexpr += "xd['x" + expr[j+1] + "']" # x2 => xd['x2'] etc.
- j += 1
- else:
- outexpr += expr[j]
- j += 1
- return True, outexpr
- # Define a dictionary with keys 'x0' thru 'x9' (initially with dummy zero values)
- xd = {"x0": 0, "x1": 0, "x2": 0, "x3": 0, "x4": 0, "x5": 0, "x6": 0, "x7": 0, "x8": 0, "x9": 0}
- # a is a list of values to be assigned to xo thru x9
- a = [0, 1, 1, -1, -2, 2, 3, -4, 4, 3]
- # elist is a list of expression for testing this script
- elist = ["x1 or x2", # OK
- "(x1 and x2) or (x3 and x4) or x5", # OK
- "X1 and (x2 or x3) or (x4 and x5)", # OK
- "x1 but not x2", # BAD
- "x1 and x2 or (x3", # BAD
- "x21 or x9"] # BAD
- for e in elist:
- flag, newexpr = validate_expr(e)
- if not flag:
- print(e, "==> False")
- else:
- # the expression was syntactically valid
- # Assign values to the dictionary entries 'x0', 'x1' etc.
- for j, v in enumerate(a):
- xd["x" + str(j)] = v
- # Evaluate the expression using the values assigned to the dictionary entries
- result = eval(newexpr)
- print(e, " ==> ", newexpr, " ==> ", result)
- # Results from test data
- # x1 or x2 ==> xd['x1'] or xd['x2'] ==> 1
- # (x1 and x2) or (x3 and x4) or x5 ==> (xd['x1'] and xd['x2']) or (xd['x3'] and xd['x4']) or xd['x5'] ==> 1
- # X1 and (x2 or x3) or (x4 and x5) ==> xd['x1'] and (xd['x2'] or xd['x3']) or (xd['x4'] and xd['x5']) ==> 1
- # x1 but not x2 ==> False
- # x1 and x2 or (x3 ==> False
- # x21 or x9 ==> False
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement