-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathparse.py
More file actions
97 lines (81 loc) · 2.4 KB
/
parse.py
File metadata and controls
97 lines (81 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#!/usr/bin/python3
from gi.repository import Gtk
import locale
import ast
import operator
import re
import logging
from gettext import gettext as _
from sugar3.graphics.alert import Alert
from sugar3.graphics.icon import Icon
def evaluate(value):
try:
result = locale.atof(value)
return result
except ValueError:
pass
if isinstance(value, str):
binOps = {
ast.Add: operator.add,
ast.Sub: operator.sub,
ast.Mult: operator.mul,
ast.Div: operator.truediv,
}
unOps = {
ast.USub: operator.neg
}
try:
node = ast.parse(value, mode='eval')
except SyntaxError:
return None
def _eval(node):
if isinstance(node, ast.Expression):
return _eval(node.body)
elif isinstance(node, ast.BinOp):
left = _eval(node.left)
right = _eval(node.right)
if not left or not right:
return None
return binOps[type(node.op)](left, right)
elif isinstance(node, ast.UnaryOp):
return unOps[type(node.op)](_eval(node.operand))
elif isinstance(node, ast.Num):
return node.n
else:
return None
return _eval(node.body)
value = _eval(node)
return value
def invalid_value_alert(activity):
alert = Alert()
alert.props.title = _('Invalid Value')
alert.props.msg = _('The expression must be a number (integer or decimal)')
ok_icon = Icon(icon_name='dialog-ok')
alert.add_button(Gtk.ResponseType.OK, _('Ok'), ok_icon)
ok_icon.show()
alert.connect('response', lambda a, r: activity.remove_alert(a))
activity.add_alert(alert)
alert.show()
if __name__ == "__main__":
tests = [
['0', 0.0],
['0.55', 0.55],
['1', 1.0],
['2', 2.0],
['-2', -2.0],
['2+2', 4.0],
['4-2', 2.0],
['4*2', 8.0],
['4/2', 2.0],
['4*-4', -16.0],
['4/2-1', 1.0],
['1.5', 1.5],
['-1.7', -1.7],
]
for test in tests:
text, expected = test
observed = evaluate(text)
if observed != expected:
print('fail; %r -> %r instead of %r' % (text, observed, expected))
else:
print('pass; %r -> %r' % (text, observed))