timeit

Програмиране с Python

Курс във Факултета по Математика и Информатика към СУ

Решение на Аритметични изрази от Николай Мантаров

Обратно към всички решения

Към профила на Николай Мантаров

Резултати

  • 9 точки от тестове
  • 0 бонус точки
  • 9 точки общо
  • 18 успешни тест(а)
  • 1 неуспешни тест(а)

Код

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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
class Interface:
    def __add__(self, other):
        plus = create_operator('+', lambda lhs, rhs: lhs + rhs)
        return Expression((self, plus, other))

    def __radd__(self, other):
        plus = create_operator('+', lambda lhs, rhs: lhs + rhs)
        return Expression((self, plus, other))

    def __sub__(self, other):
        minus = create_operator('-', lambda lhs, rhs: lhs - rhs)
        return Expression((self, minus, other))

    def __rsub__(self, other):
        minus = create_operator('-', lambda lhs, rhs: lhs - rhs)
        return Expression((other, minus, self))

    def __mul__(self, other):
        times = create_operator('*', lambda lhs, rhs: lhs * rhs)
        return Expression((self, times, other))

    def __rmul__(self, other):
        times = create_operator('*', lambda lhs, rhs: lhs * rhs)
        return Expression((self, times, other))

    def __truediv__(self, other):
        div = create_operator('/', lambda lhs, rhs: lhs / rhs)
        return Expression((self, div, other))

    def __rtruediv__(self, other):
        div = create_operator('/', lambda lhs, rhs: lhs / rhs)
        return Expression((other, div, self))

    def __floordiv__(self, other):
        floor_div = create_operator('//', lambda lhs, rhs: lhs // rhs)
        return Expression((self, floor_div, other))

    def __rfloordiv__(self, other):
        floor_div = create_operator('//', lambda lhs, rhs: lhs // rhs)
        return Expression((other, floor_div, self))

    def __mod__(self, other):
        mod = create_operator('%', lambda lhs, rhs: lhs % rhs)
        return Expression((self, mod, other))

    def __rmod__(self, other):
        mod = create_operator('%', lambda lhs, rhs: lhs % rhs)
        return Expression((other, mod, self))

    def __pow__(self, other):
        power = create_operator('**', lambda lhs, rhs: lhs ** rhs)
        return Expression((self, power, other))

    def __rpow__(self, other):
        power = create_operator('**', lambda lhs, rhs: lhs ** rhs)
        return Expression((other, power, self))

    def __lshift__(self, other):
        lshift = create_operator('<<', lambda lhs, rhs: lhs << rhs)
        return Expression((self, lshift, other))

    def __rlshift__(self, other):
        lshift = create_operator('<<', lambda lhs, rhs: lhs << rhs)
        return Expression((other, lshift, self))

    def __rshift__(self, other):
        rshift = create_operator('>>', lambda lhs, rhs: lhs >> rhs)
        return Expression((self, rshift, other))

    def __rrshift__(self, other):
        rshift = create_operator('>>', lambda lhs, rhs: lhs >> rhs)
        return Expression((other, rshift, self))

    def __xor__(self, other):
        xor = create_operator('^', lambda lhs, rhs: lhs ^ rhs)
        return Expression((self, xor, other))

    def __or__(self, other):
        or_operator = create_operator('|', lambda lhs, rhs: lhs or rhs)
        return Expression((self, or_operator, other))

    def __and__(self, other):
        and_operator = create_operator('&', lambda lhs, rhs: lhs and rhs)
        return Expression((self, and_operator, other))


class Constant(Interface):
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return str(self.value)

    def evaluate(self, **kwargs):
        return self.value


def create_constant(value):
    return Constant(value)


class Variable(Interface):
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return self.name

    def evaluate(self, **kwargs):
        return kwargs[self.name]


def create_variable(name):
    return Variable(name)


class BinaryOperator:
    def __init__(self, symbol, function):
        self.symbol = symbol
        self.function = function

    def __str__(self):
        return str(self.symbol)


def create_operator(symbol, function):
    return BinaryOperator(symbol, function)


def create_expression(expression):
    return Expression(expression)


def variable_name(expression_structure, names):
    for expression in expression_structure:
        if isinstance(expression, Variable) and expression.name not in names:
            names.append(expression.name)
        elif isinstance(expression, tuple) or isinstance(expression, list):
            variable_name(expression, names)


def print_expression(expression_structure, container):
    container.append('(')
    for expression in expression_structure:
        if isinstance(expression, Variable):
            container.append(expression.name)
        elif isinstance(expression, Constant):
            container.append(str(expression.value))
        elif isinstance(expression, BinaryOperator):
            container.append(' ')
            container.append(expression.symbol)
            container.append(' ')
        elif isinstance(expression, Expression):
            container.append(str(expression))
        elif isinstance(expression, int) or isinstance(expression, float):
            container.append(str(expression))
        else:
            print_expression(expression, container)
    container.append(')')


def expression_evaluate(expression, **variables):
    if isinstance(expression, int) or isinstance(expression, float):
        return expression
    if isinstance(expression, list) or isinstance(expression, tuple):
        lhs = expression_evaluate(expression[0], **variables)
        rhs = expression_evaluate(expression[2], **variables)
        operation = expression[1].function
        return operation(lhs, rhs)
    else:
        return expression.evaluate(**variables)


class Expression(Interface):
    def __init__(self, expression_structure):
        self.expression = expression_structure
        self.variable_names = []
        variable_name(expression_structure, self.variable_names)
        self.variable_names = tuple(self.variable_names)

    def __str__(self):
        container = []
        print_expression(self.expression, container)
        return "".join(container)

    def evaluate(self, **variables):
        lhs = expression_evaluate(self.expression[0], **variables)
        operation = self.expression[1].function
        rhs = expression_evaluate(self.expression[2], **variables)
        return operation(lhs, rhs)

Лог от изпълнението

....F..............
======================================================================
FAIL: test_string_conversion_with_literals (test.TestArithmeticsWithLiterals)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/data/rails/pyfmi-2016/releases/20160307095126/lib/language/python/runner.py", line 67, in thread
    raise result
AssertionError: '((x + 5) - ((y * 4) * 3))' != '((x + 5) - ((4 * y) * 3))'
- ((x + 5) - ((y * 4) * 3))
?                 -----
+ ((x + 5) - ((4 * y) * 3))
?              ++++ +


----------------------------------------------------------------------
Ran 19 tests in 0.117s

FAILED (failures=1)

История (4 версии и 1 коментар)

Николай обнови решението на 20.03.2016 02:30 (преди над 1 година)

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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
class interface:
    def __add__(self, other):
        plus = create_operator('+', lambda lhs, rhs: lhs + rhs)
        return Expression((self, plus, other))

    def __radd__(self, other):
        plus = create_operator('+', lambda lhs, rhs: lhs + rhs)
        return Expression((self, plus, other))

    def __sub__(self, other):
        minus = create_operator('-', lambda lhs, rhs: lhs - rhs)
        return Expression((self, minus, other))

    def __rsub__(self, other):
        minus = create_operator('-', lambda lhs, rhs: lhs - rhs)
        return Expression((other, minus, self))

    def __mul__(self, other):
        times = create_operator('*', lambda lhs, rhs: lhs * rhs)
        return Expression((self, times, other))

    def __rmul__(self, other):
        times = create_operator('*', lambda lhs, rhs: lhs * rhs)
        return Expression((self, times, other))

    def __truediv__(self, other):
        div = create_operator('/', lambda lhs, rhs: lhs / rhs)
        return Expression((self, div, other))

    def __rtruediv__(self, other):
        div = create_operator('/', lambda lhs, rhs: lhs / rhs)
        return Expression((other, div, self))

    def __floordiv__(self, other):
        floor_div = create_operator('//', lambda lhs, rhs: lhs // rhs)
        return Expression((self, floor_div, other))

    def __rfloordiv__(self, other):
        floor_div = create_operator('//', lambda lhs, rhs: lhs // rhs)
        return Expression((other, floor_div, self))

    def __mod__(self, other):
        mod = create_operator('%', lambda lhs, rhs: lhs % rhs)
        return Expression((self, mod, other))

    def __rmod__(self, other):
        mod = create_operator('%', lambda lhs, rhs: lhs % rhs)
        return Expression((other, mod, self))

    def __pow__(self, other):
        power = create_operator('**', lambda lhs, rhs: lhs ** rhs)
        return Expression((self, power, other))

    def __rpow__(self, other):
        power = create_operator('**', lambda lhs, rhs: lhs ** rhs)
        return Expression((other, power, self))

    def __lshift__(self, other):
        lshift = create_operator('<<', lambda lhs, rhs: lhs << rhs)
        return Expression((self, lshift, other))

    def __rlshift__(self, other):
        lshift = create_operator('<<', lambda lhs, rhs: lhs << rhs)
        return Expression((other, lshift, self))

    def __rshift__(self, other):
        rshift = create_operator('>>', lambda lhs, rhs: lhs >> rhs)
        return Expression((self, rshift, other))

    def __rrshift__(self, other):
        rshift = create_operator('>>', lambda lhs, rhs: lhs >> rhs)
        return Expression((other, rshift, self))

    def __xor__(self, other):
        xor = create_operator('^', lambda lhs, rhs: lhs ^ rhs)
        return Expression((self, xor, other))

    def __or__(self, other):
        or_operator = create_operator('|', lambda lhs, rhs: lhs or rhs)
        return Expression((self, or_operator, other))

    def __and__(self, other):
        and_operator = create_operator('&', lambda lhs, rhs: lhs and rhs)
        return Expression((self, and_operator, other))


class Constant(interface):
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return str(self.value)

    def evaluate(self):
        return self.value


def create_constant(value):
    return Constant(value)


class Variable(interface):
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return self.name

    def evaluate(self, **kwargs):
        if self.name in kwargs:
            return kwargs[self.name]


def create_variable(name):
    return Variable(name)


class Binary_operator:
    def __init__(self, symbol, function):
        self.symbol = symbol
        self.function = function

    def __str__(self):
        return str(self.symbol)


def create_operator(symbol, function):
    return Binary_operator(symbol, function)


def create_expression(expression):
    return Expression(expression)


def variable_name(expression_structure, names):
    for expression in expression_structure:
        if isinstance(expression, Variable) and expression.name not in names:
            names.append(expression.name)
        elif isinstance(expression, tuple) or isinstance(expression, list):
            variable_name(expression, names)


def print_expression(expression_structure, container):
    container.append('(')
    for expression in expression_structure:
        if isinstance(expression, Variable):
            container.append(expression.name)
        elif isinstance(expression, Constant):
            container.append(str(expression.value))
        elif isinstance(expression, Binary_operator):
            container.append(' ')
            container.append(expression.symbol)
            container.append(' ')
        else:
            print_expression(expression, container)
    container.append(')')


class Expression(interface):
    def __init__(self, expression_structure):
        self.expression = expression_structure
        self.__subexpression = expression_structure
        self.variable_names = []
        variable_name(expression_structure, self.variable_names)
        self.variable_names = tuple(self.variable_names)

    def __str__(self):
        container = []
        print_expression(self.expression, container)
        return "".join(container)

    def evaluate(self, **variables):
        a = self.__subexpression[0]
        operation = self.expression[1].function
        b = self.__subexpression[2]
        if isinstance(a, int) or isinstance(a, float):
            left_argument = a
        elif isinstance(a, Constant):
            left_argument = a.evaluate()
        elif isinstance(a, Variable):
            left_argument = a.evaluate(**variables)
        elif isinstance(a, Expression):
            left_argument = a.evaluate(**variables)
        else:
            self.__subexpression_1 = self.__subexpression
            self.__subexpression = self.__subexpression[0]
            a = create_expression(self.__subexpression)
            left_argument = a.evaluate(**variables)
            self.__subexpression = self.__subexpression_1

        if isinstance(b, int) or isinstance(b, float):
            right_argument = b
        elif isinstance(b, Constant):
            right_argument = b.evaluate()
        elif isinstance(b, Variable):
            right_argument = b.evaluate(**variables)
        elif isinstance(b, Expression):
            right_argument = b.evaluate(**variables)
        else:
            self.__subexpression_1 = self.__subexpression
            self.__subexpression = self.__subexpression[2]
            b = create_expression(self.__subexpression)
            right_argument = b.evaluate(**variables)
            self.__subexpression = self.__subexpression_1
        return operation(left_argument, right_argument)

Николай обнови решението на 20.03.2016 14:42 (преди над 1 година)

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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
class interface:
    def __add__(self, other):
        plus = create_operator('+', lambda lhs, rhs: lhs + rhs)
        return Expression((self, plus, other))

    def __radd__(self, other):
        plus = create_operator('+', lambda lhs, rhs: lhs + rhs)
        return Expression((self, plus, other))

    def __sub__(self, other):
        minus = create_operator('-', lambda lhs, rhs: lhs - rhs)
        return Expression((self, minus, other))

    def __rsub__(self, other):
        minus = create_operator('-', lambda lhs, rhs: lhs - rhs)
        return Expression((other, minus, self))

    def __mul__(self, other):
        times = create_operator('*', lambda lhs, rhs: lhs * rhs)
        return Expression((self, times, other))

    def __rmul__(self, other):
        times = create_operator('*', lambda lhs, rhs: lhs * rhs)
        return Expression((self, times, other))

    def __truediv__(self, other):
        div = create_operator('/', lambda lhs, rhs: lhs / rhs)
        return Expression((self, div, other))

    def __rtruediv__(self, other):
        div = create_operator('/', lambda lhs, rhs: lhs / rhs)
        return Expression((other, div, self))

    def __floordiv__(self, other):
        floor_div = create_operator('//', lambda lhs, rhs: lhs // rhs)
        return Expression((self, floor_div, other))

    def __rfloordiv__(self, other):
        floor_div = create_operator('//', lambda lhs, rhs: lhs // rhs)
        return Expression((other, floor_div, self))

    def __mod__(self, other):
        mod = create_operator('%', lambda lhs, rhs: lhs % rhs)
        return Expression((self, mod, other))

    def __rmod__(self, other):
        mod = create_operator('%', lambda lhs, rhs: lhs % rhs)
        return Expression((other, mod, self))

    def __pow__(self, other):
        power = create_operator('**', lambda lhs, rhs: lhs ** rhs)
        return Expression((self, power, other))

    def __rpow__(self, other):
        power = create_operator('**', lambda lhs, rhs: lhs ** rhs)
        return Expression((other, power, self))

    def __lshift__(self, other):
        lshift = create_operator('<<', lambda lhs, rhs: lhs << rhs)
        return Expression((self, lshift, other))

    def __rlshift__(self, other):
        lshift = create_operator('<<', lambda lhs, rhs: lhs << rhs)
        return Expression((other, lshift, self))

    def __rshift__(self, other):
        rshift = create_operator('>>', lambda lhs, rhs: lhs >> rhs)
        return Expression((self, rshift, other))

    def __rrshift__(self, other):
        rshift = create_operator('>>', lambda lhs, rhs: lhs >> rhs)
        return Expression((other, rshift, self))

    def __xor__(self, other):
        xor = create_operator('^', lambda lhs, rhs: lhs ^ rhs)
        return Expression((self, xor, other))

    def __or__(self, other):
        or_operator = create_operator('|', lambda lhs, rhs: lhs or rhs)
        return Expression((self, or_operator, other))

    def __and__(self, other):
        and_operator = create_operator('&', lambda lhs, rhs: lhs and rhs)
        return Expression((self, and_operator, other))


class Constant(interface):
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return str(self.value)

    def evaluate(self):
        return self.value


def create_constant(value):
    return Constant(value)


class Variable(interface):
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return self.name

    def evaluate(self, **kwargs):
        if self.name in kwargs:
            return kwargs[self.name]


def create_variable(name):
    return Variable(name)


class Binary_operator:
    def __init__(self, symbol, function):
        self.symbol = symbol
        self.function = function

    def __str__(self):
        return str(self.symbol)


def create_operator(symbol, function):
    return Binary_operator(symbol, function)


def create_expression(expression):
    return Expression(expression)


def variable_name(expression_structure, names):
    for expression in expression_structure:
        if isinstance(expression, Variable) and expression.name not in names:
            names.append(expression.name)
        elif isinstance(expression, tuple) or isinstance(expression, list):
            variable_name(expression, names)


def print_expression(expression_structure, container):
    container.append('(')
    for expression in expression_structure:
        if isinstance(expression, Variable):
            container.append(expression.name)
        elif isinstance(expression, Constant):
            container.append(str(expression.value))
        elif isinstance(expression, Binary_operator):
            container.append(' ')
            container.append(expression.symbol)
            container.append(' ')
        elif isinstance(expression, Expression):
            container.append(str(expression))
        else:
            print_expression(expression, container)
    container.append(')')


class Expression(interface):
    def __init__(self, expression_structure):
        self.expression = expression_structure
        self.__subexpression = expression_structure
        self.variable_names = []
        variable_name(expression_structure, self.variable_names)
        self.variable_names = tuple(self.variable_names)

    def __str__(self):
        container = []
        print_expression(self.expression, container)
        return "".join(container)

    def evaluate(self, **variables):
        a = self.__subexpression[0]
        operation = self.expression[1].function
        b = self.__subexpression[2]
        if isinstance(a, int) or isinstance(a, float):
            left_argument = a
        elif isinstance(a, Constant):
            left_argument = a.evaluate()
        elif isinstance(a, Variable):
            left_argument = a.evaluate(**variables)
        elif isinstance(a, Expression):
            left_argument = a.evaluate(**variables)
        else:
            self.__subexpression_1 = self.__subexpression
            self.__subexpression = self.__subexpression[0]
            a = create_expression(self.__subexpression)
            left_argument = a.evaluate(**variables)
            self.__subexpression = self.__subexpression_1

        if isinstance(b, int) or isinstance(b, float):
            right_argument = b
        elif isinstance(b, Constant):
            right_argument = b.evaluate()
        elif isinstance(b, Variable):
            right_argument = b.evaluate(**variables)
        elif isinstance(b, Expression):
            right_argument = b.evaluate(**variables)
        else:
            self.__subexpression_1 = self.__subexpression
            self.__subexpression = self.__subexpression[2]
            b = create_expression(self.__subexpression)
            right_argument = b.evaluate(**variables)
            self.__subexpression = self.__subexpression_1
        return operation(left_argument, right_argument)

Николай обнови решението на 20.03.2016 14:57 (преди над 1 година)

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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
class interface:
    def __add__(self, other):
        plus = create_operator('+', lambda lhs, rhs: lhs + rhs)
        return Expression((self, plus, other))

    def __radd__(self, other):
        plus = create_operator('+', lambda lhs, rhs: lhs + rhs)
        return Expression((self, plus, other))

    def __sub__(self, other):
        minus = create_operator('-', lambda lhs, rhs: lhs - rhs)
        return Expression((self, minus, other))

    def __rsub__(self, other):
        minus = create_operator('-', lambda lhs, rhs: lhs - rhs)
        return Expression((other, minus, self))

    def __mul__(self, other):
        times = create_operator('*', lambda lhs, rhs: lhs * rhs)
        return Expression((self, times, other))

    def __rmul__(self, other):
        times = create_operator('*', lambda lhs, rhs: lhs * rhs)
        return Expression((self, times, other))

    def __truediv__(self, other):
        div = create_operator('/', lambda lhs, rhs: lhs / rhs)
        return Expression((self, div, other))

    def __rtruediv__(self, other):
        div = create_operator('/', lambda lhs, rhs: lhs / rhs)
        return Expression((other, div, self))

    def __floordiv__(self, other):
        floor_div = create_operator('//', lambda lhs, rhs: lhs // rhs)
        return Expression((self, floor_div, other))

    def __rfloordiv__(self, other):
        floor_div = create_operator('//', lambda lhs, rhs: lhs // rhs)
        return Expression((other, floor_div, self))

    def __mod__(self, other):
        mod = create_operator('%', lambda lhs, rhs: lhs % rhs)
        return Expression((self, mod, other))

    def __rmod__(self, other):
        mod = create_operator('%', lambda lhs, rhs: lhs % rhs)
        return Expression((other, mod, self))

    def __pow__(self, other):
        power = create_operator('**', lambda lhs, rhs: lhs ** rhs)
        return Expression((self, power, other))

    def __rpow__(self, other):
        power = create_operator('**', lambda lhs, rhs: lhs ** rhs)
        return Expression((other, power, self))

    def __lshift__(self, other):
        lshift = create_operator('<<', lambda lhs, rhs: lhs << rhs)
        return Expression((self, lshift, other))

    def __rlshift__(self, other):
        lshift = create_operator('<<', lambda lhs, rhs: lhs << rhs)
        return Expression((other, lshift, self))

    def __rshift__(self, other):
        rshift = create_operator('>>', lambda lhs, rhs: lhs >> rhs)
        return Expression((self, rshift, other))

    def __rrshift__(self, other):
        rshift = create_operator('>>', lambda lhs, rhs: lhs >> rhs)
        return Expression((other, rshift, self))

    def __xor__(self, other):
        xor = create_operator('^', lambda lhs, rhs: lhs ^ rhs)
        return Expression((self, xor, other))

    def __or__(self, other):
        or_operator = create_operator('|', lambda lhs, rhs: lhs or rhs)
        return Expression((self, or_operator, other))

    def __and__(self, other):
        and_operator = create_operator('&', lambda lhs, rhs: lhs and rhs)
        return Expression((self, and_operator, other))


class Constant(interface):
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return str(self.value)

    def evaluate(self):
        return self.value


def create_constant(value):
    return Constant(value)


class Variable(interface):
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return self.name

    def evaluate(self, **kwargs):
        if self.name in kwargs:
            return kwargs[self.name]


def create_variable(name):
    return Variable(name)


class Binary_operator:
    def __init__(self, symbol, function):
        self.symbol = symbol
        self.function = function

    def __str__(self):
        return str(self.symbol)


def create_operator(symbol, function):
    return Binary_operator(symbol, function)


def create_expression(expression):
    return Expression(expression)


def variable_name(expression_structure, names):
    for expression in expression_structure:
        if isinstance(expression, Variable) and expression.name not in names:
            names.append(expression.name)
        elif isinstance(expression, tuple) or isinstance(expression, list):
            variable_name(expression, names)


def print_expression(expression_structure, container):
    container.append('(')
    for expression in expression_structure:
        if isinstance(expression, Variable):
            container.append(expression.name)
        elif isinstance(expression, Constant):
            container.append(str(expression.value))
        elif isinstance(expression, Binary_operator):
            container.append(' ')
            container.append(expression.symbol)
            container.append(' ')
        elif isinstance(expression, Expression):
            container.append(str(expression))
        elif isinstance(expression, int) or isinstance(expression, float):
            container.append(str(expression))
        else:
            print_expression(expression, container)
    container.append(')')


class Expression(interface):
    def __init__(self, expression_structure):
        self.expression = expression_structure
        self.__subexpression = expression_structure
        self.variable_names = []
        variable_name(expression_structure, self.variable_names)
        self.variable_names = tuple(self.variable_names)

    def __str__(self):
        container = []
        print_expression(self.expression, container)
        return "".join(container)

    def evaluate(self, **variables):
        current_left = self.__subexpression[0]
        operation = self.expression[1].function
        current_right = self.__subexpression[2]
        if isinstance(current_left, int) or isinstance(current_left, float):
            left_argument = current_left
        elif isinstance(current_left, Constant):
            left_argument = current_left.evaluate()
        elif isinstance(current_left, Variable):
            left_argument = current_left.evaluate(**variables)
        elif isinstance(current_left, Expression):
            left_argument = current_left.evaluate(**variables)
        else:
            self.__subexpression_1 = self.__subexpression
            self.__subexpression = self.__subexpression[0]
            current_left = create_expression(self.__subexpression)
            left_argument = current_left.evaluate(**variables)
            self.__subexpression = self.__subexpression_1

        if isinstance(current_right, int) or isinstance(current_right, float):
            right_argument = current_right
        elif isinstance(current_right, Constant):
            right_argument = current_right.evaluate()
        elif isinstance(current_right, Variable):
            right_argument = current_right.evaluate(**variables)
        elif isinstance(current_right, Expression):
            right_argument = current_right.evaluate(**variables)
        else:
            self.__subexpression_1 = self.__subexpression
            self.__subexpression = self.__subexpression[2]
            current_right = create_expression(self.__subexpression)
            right_argument = current_right.evaluate(**variables)
            self.__subexpression = self.__subexpression_1
        return operation(left_argument, right_argument)
  • Имената на класовете в python винаги трябва да бъдат UpperCamelCase.
  • Нямаш нужда от проверката в evaluate на Variable, винаги ще подаваме коректни аргументи на функциите/методите ви.
  • Binary_operator не е нито UpperCamelCase, нито lowerCamelCase, нито snake_case. :)
  • evaluate на Expression е изключително сложен. Има очевидно повторение за левия и десния операнд. Проверяването на класове в случая изглежда безсмислено, нали всичките имат evaluate?

Николай обнови решението на 20.03.2016 23:53 (преди над 1 година)

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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
class Interface:
    def __add__(self, other):
        plus = create_operator('+', lambda lhs, rhs: lhs + rhs)
        return Expression((self, plus, other))

    def __radd__(self, other):
        plus = create_operator('+', lambda lhs, rhs: lhs + rhs)
        return Expression((self, plus, other))

    def __sub__(self, other):
        minus = create_operator('-', lambda lhs, rhs: lhs - rhs)
        return Expression((self, minus, other))

    def __rsub__(self, other):
        minus = create_operator('-', lambda lhs, rhs: lhs - rhs)
        return Expression((other, minus, self))

    def __mul__(self, other):
        times = create_operator('*', lambda lhs, rhs: lhs * rhs)
        return Expression((self, times, other))

    def __rmul__(self, other):
        times = create_operator('*', lambda lhs, rhs: lhs * rhs)
        return Expression((self, times, other))

    def __truediv__(self, other):
        div = create_operator('/', lambda lhs, rhs: lhs / rhs)
        return Expression((self, div, other))

    def __rtruediv__(self, other):
        div = create_operator('/', lambda lhs, rhs: lhs / rhs)
        return Expression((other, div, self))

    def __floordiv__(self, other):
        floor_div = create_operator('//', lambda lhs, rhs: lhs // rhs)
        return Expression((self, floor_div, other))

    def __rfloordiv__(self, other):
        floor_div = create_operator('//', lambda lhs, rhs: lhs // rhs)
        return Expression((other, floor_div, self))

    def __mod__(self, other):
        mod = create_operator('%', lambda lhs, rhs: lhs % rhs)
        return Expression((self, mod, other))

    def __rmod__(self, other):
        mod = create_operator('%', lambda lhs, rhs: lhs % rhs)
        return Expression((other, mod, self))

    def __pow__(self, other):
        power = create_operator('**', lambda lhs, rhs: lhs ** rhs)
        return Expression((self, power, other))

    def __rpow__(self, other):
        power = create_operator('**', lambda lhs, rhs: lhs ** rhs)
        return Expression((other, power, self))

    def __lshift__(self, other):
        lshift = create_operator('<<', lambda lhs, rhs: lhs << rhs)
        return Expression((self, lshift, other))

    def __rlshift__(self, other):
        lshift = create_operator('<<', lambda lhs, rhs: lhs << rhs)
        return Expression((other, lshift, self))

    def __rshift__(self, other):
        rshift = create_operator('>>', lambda lhs, rhs: lhs >> rhs)
        return Expression((self, rshift, other))

    def __rrshift__(self, other):
        rshift = create_operator('>>', lambda lhs, rhs: lhs >> rhs)
        return Expression((other, rshift, self))

    def __xor__(self, other):
        xor = create_operator('^', lambda lhs, rhs: lhs ^ rhs)
        return Expression((self, xor, other))

    def __or__(self, other):
        or_operator = create_operator('|', lambda lhs, rhs: lhs or rhs)
        return Expression((self, or_operator, other))

    def __and__(self, other):
        and_operator = create_operator('&', lambda lhs, rhs: lhs and rhs)
        return Expression((self, and_operator, other))


class Constant(Interface):
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return str(self.value)

    def evaluate(self, **kwargs):
        return self.value


def create_constant(value):
    return Constant(value)


class Variable(Interface):
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return self.name

    def evaluate(self, **kwargs):
        return kwargs[self.name]


def create_variable(name):
    return Variable(name)


class BinaryOperator:
    def __init__(self, symbol, function):
        self.symbol = symbol
        self.function = function

    def __str__(self):
        return str(self.symbol)


def create_operator(symbol, function):
    return BinaryOperator(symbol, function)


def create_expression(expression):
    return Expression(expression)


def variable_name(expression_structure, names):
    for expression in expression_structure:
        if isinstance(expression, Variable) and expression.name not in names:
            names.append(expression.name)
        elif isinstance(expression, tuple) or isinstance(expression, list):
            variable_name(expression, names)


def print_expression(expression_structure, container):
    container.append('(')
    for expression in expression_structure:
        if isinstance(expression, Variable):
            container.append(expression.name)
        elif isinstance(expression, Constant):
            container.append(str(expression.value))
        elif isinstance(expression, BinaryOperator):
            container.append(' ')
            container.append(expression.symbol)
            container.append(' ')
        elif isinstance(expression, Expression):
            container.append(str(expression))
        elif isinstance(expression, int) or isinstance(expression, float):
            container.append(str(expression))
        else:
            print_expression(expression, container)
    container.append(')')


def expression_evaluate(expression, **variables):
    if isinstance(expression, int) or isinstance(expression, float):
        return expression
    if isinstance(expression, list) or isinstance(expression, tuple):
        lhs = expression_evaluate(expression[0], **variables)
        rhs = expression_evaluate(expression[2], **variables)
        operation = expression[1].function
        return operation(lhs, rhs)
    else:
        return expression.evaluate(**variables)


class Expression(Interface):
    def __init__(self, expression_structure):
        self.expression = expression_structure
        self.variable_names = []
        variable_name(expression_structure, self.variable_names)
        self.variable_names = tuple(self.variable_names)

    def __str__(self):
        container = []
        print_expression(self.expression, container)
        return "".join(container)

    def evaluate(self, **variables):
        lhs = expression_evaluate(self.expression[0], **variables)
        operation = self.expression[1].function
        rhs = expression_evaluate(self.expression[2], **variables)
        return operation(lhs, rhs)