2
## yacinechaouche@yahoo.com
3
## http://ychaouche.wikispot.org
8
This is the engine that calculates the expressions generated by the generator (generator.py).
9
Its main function is evaluate, which takes an expression s and returns its value.
10
It may return None when any part of the expression divides by 0.
11
Expressions must be surrounded by parenthesis because the evaluate function does only operations with
12
two operands. An expression surrounded by parenthesis is considered one operand.
13
So you may call evaluate("(5+3) + (3+((9+10)/2))") but not evaluate("(10-3)/2+(8-3)")
14
The function is not defensive at all, it does not check the validity of its input.
20
evaluate("6+(3*2)") => 12
21
where : first = 6; second = + and third = (3*2).
23
symmetrically, evaluate("(8*2) - 10") => 6
24
where first = (8*2); second = -; and third = 10.
26
first and third are either numbers or expression between parentheses
27
second is always an operator, otherwise the application may crash (not tested)
29
first,second,third = tokenize(s)
31
#print "%s is a number -> put in var1" % first
34
#print "%s is not a number -> eval" % first
35
# if it's not a number, evalute it.
36
left = evaluate(first[1:-1])
37
# if division by zero or if the division returned a fraction,
38
# consider the whole expression wrong.
42
if is_operand(second):
43
#print "%s is an operation -> put in operation" % second
47
print "%s is not an operation, skipping (this will crash)" % second
51
#print "%s is a number -> put in var2" % third
54
#print "%s is not a number -> eval" % third
55
right = evaluate(third[1:-1])
59
# now that we have our two operands and our operation, we can calculate the result.
60
result = do_op(left,operation,right)
61
#print "we return the value of %s %s %s which is %s" % (left,operation,right,result)
66
if s[0] not in ('(',')') :
67
first = read_number(s)
68
second = s[len(first)]
69
third = s[len(first)+1:]
84
#print "tokenization : %s, %s , %s" % (first,second,third)
85
return first,second,third
94
def do_op(left,operation,right):
96
# we may have None in one of those,
97
# for example when dividing by 0
99
if not (left and right) :
102
if operation == "+" :
105
elif operation == "*" :
108
elif operation == "/" :
110
result = left / right
111
# we may only allow net divisions
112
if not left % right :
115
elif operation == "-" :
122
return s in ["+","/","*","-"]
127
print evaluate(sys.argv[1])
129
if __name__ == "__main__":