timeit

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

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

Решение на Аритметични изрази от Димитър Керезов

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

Към профила на Димитър Керезов

Резултати

  • 10 точки от тестове
  • 0 бонус точки
  • 10 точки общо
  • 19 успешни тест(а)
  • 0 неуспешни тест(а)

Код

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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
def convert_operand(o):
    return o if isinstance(o, Element) else create_expression(o)


class Element:
    def __apply_operator(self, other, operator, reverse):
        if reverse:
            return create_expression((other, operator, self))
        else:
            return create_expression((self, operator, other))

    def __create_base_function(self, other, symbol, reverse, custom_func=None):
        def func(lhs, rhs):
            return eval("{0}{1}{2}".format(lhs, symbol, rhs))
        operator = create_operator(symbol, custom_func or func)
        return self.__apply_operator(other, operator, reverse)

    def __add_base(self, other, reverse):
        return self.__create_base_function(other, '+', reverse)

    def __add__(self, other):
        return self.__add_base(other, False)

    def __radd__(self, other):
        return self.__add_base(other, True)

    def __sub_base(self, other, reverse):
        return self.__create_base_function(other, '-', reverse)

    def __sub__(self, other):
        return self.__sub_base(other, False)

    def __rsub__(self, other):
        return self.__sub_base(other, True)

    def __mul_base(self, other, reverse):
        return self.__create_base_function(other, '*', reverse)

    def __mul__(self, other):
        return self.__mul_base(other, False)

    def __rmul__(self, other):
        return self.__mul_base(other, True)

    def __truediv_base(self, other, reverse):
        return self.__create_base_function(other, '/', reverse)

    def __truediv__(self, other):
        return self.__truediv_base(other, False)

    def __rtruediv__(self, other):
        return self.__truediv_base(other, True)

    def __floordiv_base(self, other, reverse):
        return self.__create_base_function(other, '//', reverse)

    def __floordiv__(self, other):
        return self.__floordiv_base(other, False)

    def __rfloordiv__(self, other):
        return self.__floordiv_base(other, True)

    def __matmul_base(self, other, reverse):
        return self.__create_base_function(other, '@', reverse)

    def __matmul__(self, other):
        return self.__matmul_base(other, False)

    def __rmatmul__(self, other):
        return self.__matmul_base(other, True)

    def __mod_base(self, other, reverse):
        return self.__create_base_function(other, '%', reverse)

    def __mod__(self, other):
        return self.__mod_base(other, False)

    def __rmod__(self, other):
        return self.__mod_base(other, True)

    def __divmod_base(self, other, reverse):
        def __divmod(lhs, rhs):
            return (lhs // rhs, lhs % rhs)
        return self.__create_base_function(other, 'divmod', reverse, __divmod)

    def __divmod__(self, other):
        return self.__divmod_base(other, False)

    def __rdivmod__(self, other):
        return self.__divmod_base(other, True)

    def __pow_base(self, other, reverse):
        return self.__create_base_function(other, '**', reverse)

    def __pow__(self, other):
        return self.__pow_base(other, False)

    def __rpow__(self, other):
        return self.__pow_base(other, True)

    def __lshift_base(self, other, reverse):
        return self.__create_base_function(other, '<<', reverse)

    def __lshift__(self, other):
        return self.__lshift_base(other, False)

    def __rlshift__(self, other):
        return self.__lshift_base(other, True)

    def __rshift_base(self, other, reverse):
        return self.__create_base_function(other, '>>', reverse)

    def __rshift__(self, other):
        return self.__rshift_base(other, False)

    def __rrshift__(self, other):
        return self.__rshift_base(other, True)

    def __and_base(self, other, reverse):
        return self.__create_base_function(other, '&', reverse)

    def __and__(self, other):
        return self.__and_base(other, False)

    def __rand__(self, other):
        return self.__and_base(other, True)

    def __xor_base(self, other, reverse):
        return self.__create_base_function(other, '^', reverse)

    def __xor__(self, other):
        return self.__xor_base(other, False)

    def __rxor__(self, other):
        return self.__xor_base(other, True)

    def __or_base(self, other, reverse):
        return self.__create_base_function(other, '|', reverse)

    def __or__(self, other):
        return self.__or_base(other, False)

    def __ror__(self, other):
        return self.__or_base(other, True)


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

    def evaluate(self, **variables):
        return(variables.get(self.name, self.name))

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


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

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

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


class Operator(Element):
    cache = []

    @classmethod
    def __get_cache(cls, symbol, function):
        for o in Operator.cache:
            if o.symbol == symbol and o.function == function:
                return o

    def __new__(cls, symbol, function, *args, **kwargs):
        existing = cls.__get_cache(symbol, function)
        if existing:
            return existing
        operator = super(Operator, cls).__new__(cls)
        return operator

    def __init__(self, symbol, function):
        if self in self.cache:
            return
        self.symbol = symbol
        self.function = function
        self.cache.append(self)

    def __call__(self, lhs, rhs):
        return self.function(lhs, rhs)

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


class Expression(Element):
    def __init__(self, expr):
        self.expr = expr

    def evaluate(self, **variables):
        if hasattr(self.expr, '__iter__'):
            lhs, op, rhs = self.expr
            lhs = convert_operand(lhs)
            rhs = convert_operand(rhs)
            result = op(lhs.evaluate(**variables), rhs.evaluate(**variables))
        else:
            result = self.expr
        return result

    def __str__(self):
        result = ""
        for element in self.expr:
            if hasattr(element, '__iter__'):
                result += str(create_expression(element))
            else:
                str_format = " {} " if isinstance(element, Operator) else "{}"
                result += str_format.format(str(element))
        return "({})".format(result)

    @property
    def variable_names(self):
        result = set()
        for element in self.expr:
            if isinstance(element, Variable):
                result.add(element.evaluate())
            elif isinstance(element, Expression):
                result.update(element.variable_names)
        return result


def create_constant(value):
    return Constant(value)


def create_variable(name):
    return Variable(name)


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


def create_expression(expression_structure):
    return Expression(expression_structure)

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

...................
----------------------------------------------------------------------
Ran 19 tests in 0.295s

OK

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

Димитър обнови решението на 20.03.2016 00:27 (преди над 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
210
211
212
213
214
215
216
217
218
219
220
221
def convert_operand(o):
    return o if isinstance(o, Element) else create_expression(o)


class Element:
    def __init__(self, value):
        self.value = value

    def evaluate(self, **variables):
        return(variables.get(self.value, self.value))

    def __apply_operator(self, other, operator, reverse):
        if reverse:
            return create_expression((other, operator, self))
        else:
            return create_expression((self, operator, other))

    def __create_base_function(self, other, symbol, reverse, custom_func=None):
        def func(lhs, rhs):
            return eval("{0}{1}{2}".format(lhs, symbol, rhs))

        operator = create_operator(symbol, custom_func or func)
        return self.__apply_operator(other, operator, reverse)

    def __add_base(self, other, reverse):
        return self.__create_base_function(other, '+', reverse)

    def __add__(self, other):
        return self.__add_base(other, False)

    def __radd__(self, other):
        return self.__add_base(other, True)

    def __sub_base(self, other, reverse):
        return self.__create_base_function(other, '-', reverse)

    def __sub__(self, other):
        return self.__sub_base(other, False)

    def __rsub__(self, other):
        return self.__sub_base(other, True)

    def __mul_base(self, other, reverse):
        return self.__create_base_function(other, '*', reverse)

    def __mul__(self, other):
        return self.__mul_base(other, False)

    def __rmul__(self, other):
        return self.__mul_base(other, True)

    def __truediv_base(self, other, reverse):
        return self.__create_base_function(other, '/', reverse)

    def __truediv__(self, other):
        return self.__truediv_base(other, False)

    def __rtruediv__(self, other):
        return self.__truediv_base(other, True)

    def __floordiv_base(self, other, reverse):
        return self.__create_base_function(other, '//', reverse)

    def __floordiv__(self, other):
        return self.__floordiv_base(other, False)

    def __rfloordiv__(self, other):
        return self.__floordiv_base(other, True)

    def __matmul_base(self, other, reverse):
        return self.__create_base_function(other, '@', reverse)

    def __matmul__(self, other):
        return self.__matmul_base(other, False)

    def __rmatmul__(self, other):
        return self.__matmul_base(other, True)

    def __mod_base(self, other, reverse):
        return self.__create_base_function(other, '%', reverse)

    def __mod__(self, other):
        return self.__mod_base(other, False)

    def __rmod__(self, other):
        return self.__mod_base(other, True)

    def __divmod_base(self, other, reverse):
        def __divmod(lhs, rhs):
            return (lhs // rhs, lhs % rhs)

        return self.__create_base_function(other, 'divmod', reverse, __divmod)

    def __divmod__(self, other):
        return self.__divmod_base(other, False)

    def __rdivmod__(self, other):
        return self.__divmod_base(other, True)

    def __pow_base(self, other, reverse):
        return self.__create_base_function(other, '**', reverse)

    def __pow__(self, other):
        return self.__pow_base(other, False)

    def __rpow__(self, other):
        return self.__pow_base(other, True)

    def __lshift_base(self, other, reverse):
        return self.__create_base_function(other, '<<', reverse)

    def __lshift__(self, other):
        return self.__lshift_base(other, False)

    def __rlshift__(self, other):
        return self.__lshift_base(other, True)

    def __rshift_base(self, other, reverse):
        return self.__create_base_function(other, '>>', reverse)

    def __rshift__(self, other):
        return self.__rshift_base(other, False)

    def __rrshift__(self, other):
        return self.__rshift_base(other, True)

    def __and_base(self, other, reverse):
        return self.__create_base_function(other, '&', reverse)

    def __and__(self, other):
        return self.__and_base(other, False)

    def __rand__(self, other):
        return self.__and_base(other, True)

    def __xor_base(self, other, reverse):
        return self.__create_base_function(other, '^', reverse)

    def __xor__(self, other):
        return self.__xor_base(other, False)

    def __rxor__(self, other):
        return self.__xor_base(other, True)

    def __or_base(self, other, reverse):
        return self.__create_base_function(other, '|', reverse)

    def __or__(self, other):
        return self.__or_base(other, False)

    def __ror__(self, other):
        return self.__or_base(other, True)

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


class Variable(Element):
    def __init__(self, value):
        super().__init__(value)


class Operator(Element):
    def __init__(self, symbol, function):
        super().__init__(symbol)
        self.function = function

    def __call__(self, lhs, rhs):
        return self.function(lhs, rhs)


class Expression(Element):
    def __init__(self, expr):
        self.expr = expr

    def evaluate(self, **variables):
        if hasattr(self.expr, '__iter__'):
            lhs, op, rhs = self.expr
            lhs = convert_operand(lhs)
            rhs = convert_operand(rhs)
            result = str(op(lhs.evaluate(**variables), rhs.evaluate(**variables)))
        else:
            result = str(self.expr)

        return eval("({})".format(result))

    def __str__(self):
        result = ""
        for element in self.expr:
            if hasattr(element, '__iter__'):
                result += str(create_expression(element))
            else:
                str_format = " {} " if isinstance(element, Operator) else "{}"
                result += str_format.format(str(element))
        return "({})".format(result)

    @property
    def variable_names(self):
        result = set()
        for element in self.expr:
            if isinstance(element, Variable):
                result.add(element.evaluate())
            elif isinstance(element, Expression):
                result.update(element.variable_names)
        return result


def create_constant(value):
    return Variable(value)


def create_variable(name):
    return Variable(name)


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


def create_expression(expression_structure):
    return Expression(expression_structure)

Не съм сигурен дали(как) мога да имплементирам бонус-а. Мислех си да пазя операторите в един речник като ключовете да са символите на оператора и при създваване на ги вадя от речника ако ги има.

Но това би значело, че при следния код:

plus = create_operator('+', lambda lhs, rhs: lhs + rhs)
plus_minus = create_operator('+', lambda lhs, rhs: lhs - rhs)

plus_minus отново ще съдържа кода на plus във function-a си, защото + символът ще е "кеширан".

А нямам представа как да проверявам дали вече съществува такъв function, защото той може да е зададен като lambda, пълноправна функция, декларирана с def, eval и прочие.

  • Никога не използвай eval и exec
  • Начина, по който преизползваш value за променливи и константи е малко tricky, по-добре е да имаш два отделни атрибута за това, всеки в съответния клас, за който има смисъл.
  • По-добре от архитектурна гледна точка е всеки наследник на Element да може сам да дефинира какво да прави evaluate за него.
  • _base методите които дефинираш всъщност правят кода ти по-сложен, вместо по-прост.

  • За бонуса, ако ти се подаде различна lambda няма как да знаеш, че тя е същата като някоя предишна, Дума, която търсиш е cache.

Димитър обнови решението на 20.03.2016 23:11 (преди над 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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
def convert_operand(o):
    return o if isinstance(o, Element) else create_expression(o)


class Element:
    def __init__(self, value):
        self.value = value

    def __apply_operator(self, other, operator, reverse):
        if reverse:
            return create_expression((other, operator, self))
        else:
            return create_expression((self, operator, other))

    def __create_base_function(self, other, symbol, reverse, custom_func=None):
        def func(lhs, rhs):
            return eval("{0}{1}{2}".format(lhs, symbol, rhs))
        operator = create_operator(symbol, custom_func or func)
        return self.__apply_operator(other, operator, reverse)

    def __add_base(self, other, reverse):
        return self.__create_base_function(other, '+', reverse)

    def __add__(self, other):
        return self.__add_base(other, False)

    def __radd__(self, other):
        return self.__add_base(other, True)

    def __sub_base(self, other, reverse):
        return self.__create_base_function(other, '-', reverse)

    def __sub__(self, other):
        return self.__sub_base(other, False)

    def __rsub__(self, other):
        return self.__sub_base(other, True)

    def __mul_base(self, other, reverse):
        return self.__create_base_function(other, '*', reverse)

    def __mul__(self, other):
        return self.__mul_base(other, False)

    def __rmul__(self, other):
        return self.__mul_base(other, True)

    def __truediv_base(self, other, reverse):
        return self.__create_base_function(other, '/', reverse)

    def __truediv__(self, other):
        return self.__truediv_base(other, False)

    def __rtruediv__(self, other):
        return self.__truediv_base(other, True)

    def __floordiv_base(self, other, reverse):
        return self.__create_base_function(other, '//', reverse)

    def __floordiv__(self, other):
        return self.__floordiv_base(other, False)

    def __rfloordiv__(self, other):
        return self.__floordiv_base(other, True)

    def __matmul_base(self, other, reverse):
        return self.__create_base_function(other, '@', reverse)

    def __matmul__(self, other):
        return self.__matmul_base(other, False)

    def __rmatmul__(self, other):
        return self.__matmul_base(other, True)

    def __mod_base(self, other, reverse):
        return self.__create_base_function(other, '%', reverse)

    def __mod__(self, other):
        return self.__mod_base(other, False)

    def __rmod__(self, other):
        return self.__mod_base(other, True)

    def __divmod_base(self, other, reverse):
        def __divmod(lhs, rhs):
            return (lhs // rhs, lhs % rhs)
        return self.__create_base_function(other, 'divmod', reverse, __divmod)

    def __divmod__(self, other):
        return self.__divmod_base(other, False)

    def __rdivmod__(self, other):
        return self.__divmod_base(other, True)

    def __pow_base(self, other, reverse):
        return self.__create_base_function(other, '**', reverse)

    def __pow__(self, other):
        return self.__pow_base(other, False)

    def __rpow__(self, other):
        return self.__pow_base(other, True)

    def __lshift_base(self, other, reverse):
        return self.__create_base_function(other, '<<', reverse)

    def __lshift__(self, other):
        return self.__lshift_base(other, False)

    def __rlshift__(self, other):
        return self.__lshift_base(other, True)

    def __rshift_base(self, other, reverse):
        return self.__create_base_function(other, '>>', reverse)

    def __rshift__(self, other):
        return self.__rshift_base(other, False)

    def __rrshift__(self, other):
        return self.__rshift_base(other, True)

    def __and_base(self, other, reverse):
        return self.__create_base_function(other, '&', reverse)

    def __and__(self, other):
        return self.__and_base(other, False)

    def __rand__(self, other):
        return self.__and_base(other, True)

    def __xor_base(self, other, reverse):
        return self.__create_base_function(other, '^', reverse)

    def __xor__(self, other):
        return self.__xor_base(other, False)

    def __rxor__(self, other):
        return self.__xor_base(other, True)

    def __or_base(self, other, reverse):
        return self.__create_base_function(other, '|', reverse)

    def __or__(self, other):
        return self.__or_base(other, False)

    def __ror__(self, other):
        return self.__or_base(other, True)

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


class Variable(Element):
    def __init__(self, value):
        super().__init__(value)

    def evaluate(self, **variables):
        return(variables.get(self.value, self.value))


class Constant(Element):
    def __init__(self, value):
        super().__init__(value)

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


class Operator(Element):
    cache = []

    @classmethod
    def __getCache(cls, symbol, function):
        for o in Operator.cache:
            if o.value == symbol and o.function == function:
                return o
        return None

    def __new__(cls, symbol, function, *args, **kwargs):
        existing = cls.__getCache(symbol, function)
        if existing:
            return existing
        operator = super(Operator, cls).__new__(cls)
        return operator

    def __init__(self, symbol, function):
        if self in self.cache:
            return
        super().__init__(symbol)
        self.function = function
        self.cache.append(self)

    def __call__(self, lhs, rhs):
        return self.function(lhs, rhs)


class Expression(Element):
    def __init__(self, expr):
        self.expr = expr

    def evaluate(self, **variables):
        if hasattr(self.expr, '__iter__'):
            lhs, op, rhs = self.expr
            lhs = convert_operand(lhs)
            rhs = convert_operand(rhs)
            result = op(lhs.evaluate(**variables), rhs.evaluate(**variables))
        else:
            result = self.expr
        return result

    def __str__(self):
        result = ""
        for element in self.expr:
            if hasattr(element, '__iter__'):
                result += str(create_expression(element))
            else:
                str_format = " {} " if isinstance(element, Operator) else "{}"
                result += str_format.format(str(element))
        return "({})".format(result)

    @property
    def variable_names(self):
        result = set()
        for element in self.expr:
            if isinstance(element, Variable):
                result.add(element.evaluate())
            elif isinstance(element, Expression):
                result.update(element.variable_names)
        return result


def create_constant(value):
    return Constant(value)


def create_variable(name):
    return Variable(name)


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


def create_expression(expression_structure):
    return Expression(expression_structure)

@evgeni

Прикачвам второ решение с оправени някои коментари, а по други имам въпроси, here it goes:

  • Никога не използвай eval и exec - не разбирам хейтът по eval - във всички скриптови езици го има. В случая вършеше перфектна работа(все пак не ми трябваше де - останало беше от първите итерации на кода) - вие сте казали: няма да ви даваме невалидни данни, тогава защо да ме е страх от eval..?
  • Начина, по който преизползваш value за променливи и константи е малко tricky, по-добре е да имаш два отделни атрибута за това, всеки в съответния клас, за който има смисъл. - тука малко не разбрах, преизпозвам пропъртито просто, за да запазвам данни, константите са просто променливи, на които не можеш да им сменяш стойността.
  • По-добре от архитектурна гледна точка е всеки наследник на Element да може сам да дефинира какво да прави evaluate за него. - съгласен, fixed
  • _base методите които дефинираш всъщност правят кода ти по-сложен, вместо по-прост. - тука също съм съгласен, и го осъзнах някъде посредата на дефинирането на n-тия оператор, но вече бях написал кода и реших да го оставя. Щеше ми се да бях измислил начин да мина през декоратор, но не успях и оставям кода така.

  • За бонуса, ако ти се подаде различна lambda няма как да знаеш, че тя е същата като някоя предишна, Дума, която търсиш е cache. - имплементирах някаква версия на caching, пробвах с lru_cache и с memoize, но някак си не правеха това, което исках, а именно:
def addition(lhs, rhs):
    return lhs + rhs

plus = create_operator('+', addition)
another_plus = create_operator('+', addition)
print(plus == another_plus) # True

не успях да постигна ефекта с нито един декоратор и това, в решението, е резултатът.

  • Във всеки език eval/exec и подобните им вариации са по-скоро имплементационни детайли, които ти позволяват в извънредно крайни случаи, в които нищо друго не помага, да правиш селянии. :) Има далеч по-красиви и семантично коректни начини да се имплементира общо взето всичко, за което човек би се изкушил да ги ползва. Ти си намерил един такъв начин. Не тестваме кода ви с невалидни данни, защото част от това нещо да е архитектурно добре издържано е валидацията и логиката оперираща върху данните да са два отделни компонента. Валидацията е относително досадна занимавка, с която доста по-трудно можем да привлечем вниманието на хората, за разлика от задачи, в които има що-годе интересна логика и обещания за хубав код. Крайния образователен ефект от писането на който и да е от двата компонента е сходен. Ползването на eval и подобни обаче е изрично добавяне на проблеми, най-вече от гледна точка на сигурност, но пък за сметка това е по-бавно, за което даже искам да ти дам малък пример, понеже е лесно за демонстриране, а доста информативно:
-> [2]: a = 5
-> [3]: b = 7
-> [6]: %timeit eval('{} + {}'.format(a, b))
100000 loops, best of 3: 8.31 µs per loop
-> [7]: %timeit a + b
10000000 loops, best of 3: 52.5 ns per loop
-> [8]: %timeit (lambda x, y: x + y)(a, b)
10000000 loops, best of 3: 194 ns per loop
  • Проблема с value във Variable и Constant е, че в двата класа този атрибуте има различна семантика. За Variable това е името на променливата, а по дефиниция променливите нямат стойност, защото се променят, те имат имена. За Constant от друга страна value е наистина стойността на константата.

@evgeni

Благодаря за нагледния пример - наистина помогна, за да разбера!

От гледна точка value разбрах най-сетне какво имаш предвид, но за съжаление няма да мога да го оправя навреме за крайния срок. Първоначалната ми идея с преизползването произтече от гледна точка на преизползване на код просто.

As a side note: Благодаря за feedback-a, смятам, че е невероятно полезен при тия домашни, не само че ти се дава feedback на място + обяснения, ами и имаш стимул да предаваш домашните по-рано.

Keep up the good work!

Само да вмъкна нещо, което е убягнало на @Евгени:

Методът __getCache трябва да се казва __get_cache. Предвид факта, че е единственото ти такова неконвенционално име допускам знаеш, че това е в разрез с PEP8 и просто си го оставил по невнимание.

Също така нямаш нужда от return None в последния ред на функция. Ако една функция приключва през return се счита, че е върнала None.

Димитър обнови решението на 21.03.2016 14:21 (преди над 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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
def convert_operand(o):
    return o if isinstance(o, Element) else create_expression(o)


class Element:
    def __apply_operator(self, other, operator, reverse):
        if reverse:
            return create_expression((other, operator, self))
        else:
            return create_expression((self, operator, other))

    def __create_base_function(self, other, symbol, reverse, custom_func=None):
        def func(lhs, rhs):
            return eval("{0}{1}{2}".format(lhs, symbol, rhs))
        operator = create_operator(symbol, custom_func or func)
        return self.__apply_operator(other, operator, reverse)

    def __add_base(self, other, reverse):
        return self.__create_base_function(other, '+', reverse)

    def __add__(self, other):
        return self.__add_base(other, False)

    def __radd__(self, other):
        return self.__add_base(other, True)

    def __sub_base(self, other, reverse):
        return self.__create_base_function(other, '-', reverse)

    def __sub__(self, other):
        return self.__sub_base(other, False)

    def __rsub__(self, other):
        return self.__sub_base(other, True)

    def __mul_base(self, other, reverse):
        return self.__create_base_function(other, '*', reverse)

    def __mul__(self, other):
        return self.__mul_base(other, False)

    def __rmul__(self, other):
        return self.__mul_base(other, True)

    def __truediv_base(self, other, reverse):
        return self.__create_base_function(other, '/', reverse)

    def __truediv__(self, other):
        return self.__truediv_base(other, False)

    def __rtruediv__(self, other):
        return self.__truediv_base(other, True)

    def __floordiv_base(self, other, reverse):
        return self.__create_base_function(other, '//', reverse)

    def __floordiv__(self, other):
        return self.__floordiv_base(other, False)

    def __rfloordiv__(self, other):
        return self.__floordiv_base(other, True)

    def __matmul_base(self, other, reverse):
        return self.__create_base_function(other, '@', reverse)

    def __matmul__(self, other):
        return self.__matmul_base(other, False)

    def __rmatmul__(self, other):
        return self.__matmul_base(other, True)

    def __mod_base(self, other, reverse):
        return self.__create_base_function(other, '%', reverse)

    def __mod__(self, other):
        return self.__mod_base(other, False)

    def __rmod__(self, other):
        return self.__mod_base(other, True)

    def __divmod_base(self, other, reverse):
        def __divmod(lhs, rhs):
            return (lhs // rhs, lhs % rhs)
        return self.__create_base_function(other, 'divmod', reverse, __divmod)

    def __divmod__(self, other):
        return self.__divmod_base(other, False)

    def __rdivmod__(self, other):
        return self.__divmod_base(other, True)

    def __pow_base(self, other, reverse):
        return self.__create_base_function(other, '**', reverse)

    def __pow__(self, other):
        return self.__pow_base(other, False)

    def __rpow__(self, other):
        return self.__pow_base(other, True)

    def __lshift_base(self, other, reverse):
        return self.__create_base_function(other, '<<', reverse)

    def __lshift__(self, other):
        return self.__lshift_base(other, False)

    def __rlshift__(self, other):
        return self.__lshift_base(other, True)

    def __rshift_base(self, other, reverse):
        return self.__create_base_function(other, '>>', reverse)

    def __rshift__(self, other):
        return self.__rshift_base(other, False)

    def __rrshift__(self, other):
        return self.__rshift_base(other, True)

    def __and_base(self, other, reverse):
        return self.__create_base_function(other, '&', reverse)

    def __and__(self, other):
        return self.__and_base(other, False)

    def __rand__(self, other):
        return self.__and_base(other, True)

    def __xor_base(self, other, reverse):
        return self.__create_base_function(other, '^', reverse)

    def __xor__(self, other):
        return self.__xor_base(other, False)

    def __rxor__(self, other):
        return self.__xor_base(other, True)

    def __or_base(self, other, reverse):
        return self.__create_base_function(other, '|', reverse)

    def __or__(self, other):
        return self.__or_base(other, False)

    def __ror__(self, other):
        return self.__or_base(other, True)


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

    def evaluate(self, **variables):
        return(variables.get(self.name, self.name))

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


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

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

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


class Operator(Element):
    cache = []

    @classmethod
    def __getCache(cls, symbol, function):
        for o in Operator.cache:
            if o.symbol == symbol and o.function == function:
                return o
        return None

    def __new__(cls, symbol, function, *args, **kwargs):
        existing = cls.__getCache(symbol, function)
        if existing:
            return existing
        operator = super(Operator, cls).__new__(cls)
        return operator

    def __init__(self, symbol, function):
        if self in self.cache:
            return
        self.symbol = symbol
        self.function = function
        self.cache.append(self)

    def __call__(self, lhs, rhs):
        return self.function(lhs, rhs)

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


class Expression(Element):
    def __init__(self, expr):
        self.expr = expr

    def evaluate(self, **variables):
        if hasattr(self.expr, '__iter__'):
            lhs, op, rhs = self.expr
            lhs = convert_operand(lhs)
            rhs = convert_operand(rhs)
            result = op(lhs.evaluate(**variables), rhs.evaluate(**variables))
        else:
            result = self.expr
        return result

    def __str__(self):
        result = ""
        for element in self.expr:
            if hasattr(element, '__iter__'):
                result += str(create_expression(element))
            else:
                str_format = " {} " if isinstance(element, Operator) else "{}"
                result += str_format.format(str(element))
        return "({})".format(result)

    @property
    def variable_names(self):
        result = set()
        for element in self.expr:
            if isinstance(element, Variable):
                result.add(element.evaluate())
            elif isinstance(element, Expression):
                result.update(element.variable_names)
        return result


def create_constant(value):
    return Constant(value)


def create_variable(name):
    return Variable(name)


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


def create_expression(expression_structure):
    return Expression(expression_structure)

Димитър обнови решението на 21.03.2016 14:22 (преди над 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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
def convert_operand(o):
    return o if isinstance(o, Element) else create_expression(o)


class Element:
    def __apply_operator(self, other, operator, reverse):
        if reverse:
            return create_expression((other, operator, self))
        else:
            return create_expression((self, operator, other))

    def __create_base_function(self, other, symbol, reverse, custom_func=None):
        def func(lhs, rhs):
            return eval("{0}{1}{2}".format(lhs, symbol, rhs))
        operator = create_operator(symbol, custom_func or func)
        return self.__apply_operator(other, operator, reverse)

    def __add_base(self, other, reverse):
        return self.__create_base_function(other, '+', reverse)

    def __add__(self, other):
        return self.__add_base(other, False)

    def __radd__(self, other):
        return self.__add_base(other, True)

    def __sub_base(self, other, reverse):
        return self.__create_base_function(other, '-', reverse)

    def __sub__(self, other):
        return self.__sub_base(other, False)

    def __rsub__(self, other):
        return self.__sub_base(other, True)

    def __mul_base(self, other, reverse):
        return self.__create_base_function(other, '*', reverse)

    def __mul__(self, other):
        return self.__mul_base(other, False)

    def __rmul__(self, other):
        return self.__mul_base(other, True)

    def __truediv_base(self, other, reverse):
        return self.__create_base_function(other, '/', reverse)

    def __truediv__(self, other):
        return self.__truediv_base(other, False)

    def __rtruediv__(self, other):
        return self.__truediv_base(other, True)

    def __floordiv_base(self, other, reverse):
        return self.__create_base_function(other, '//', reverse)

    def __floordiv__(self, other):
        return self.__floordiv_base(other, False)

    def __rfloordiv__(self, other):
        return self.__floordiv_base(other, True)

    def __matmul_base(self, other, reverse):
        return self.__create_base_function(other, '@', reverse)

    def __matmul__(self, other):
        return self.__matmul_base(other, False)

    def __rmatmul__(self, other):
        return self.__matmul_base(other, True)

    def __mod_base(self, other, reverse):
        return self.__create_base_function(other, '%', reverse)

    def __mod__(self, other):
        return self.__mod_base(other, False)

    def __rmod__(self, other):
        return self.__mod_base(other, True)

    def __divmod_base(self, other, reverse):
        def __divmod(lhs, rhs):
            return (lhs // rhs, lhs % rhs)
        return self.__create_base_function(other, 'divmod', reverse, __divmod)

    def __divmod__(self, other):
        return self.__divmod_base(other, False)

    def __rdivmod__(self, other):
        return self.__divmod_base(other, True)

    def __pow_base(self, other, reverse):
        return self.__create_base_function(other, '**', reverse)

    def __pow__(self, other):
        return self.__pow_base(other, False)

    def __rpow__(self, other):
        return self.__pow_base(other, True)

    def __lshift_base(self, other, reverse):
        return self.__create_base_function(other, '<<', reverse)

    def __lshift__(self, other):
        return self.__lshift_base(other, False)

    def __rlshift__(self, other):
        return self.__lshift_base(other, True)

    def __rshift_base(self, other, reverse):
        return self.__create_base_function(other, '>>', reverse)

    def __rshift__(self, other):
        return self.__rshift_base(other, False)

    def __rrshift__(self, other):
        return self.__rshift_base(other, True)

    def __and_base(self, other, reverse):
        return self.__create_base_function(other, '&', reverse)

    def __and__(self, other):
        return self.__and_base(other, False)

    def __rand__(self, other):
        return self.__and_base(other, True)

    def __xor_base(self, other, reverse):
        return self.__create_base_function(other, '^', reverse)

    def __xor__(self, other):
        return self.__xor_base(other, False)

    def __rxor__(self, other):
        return self.__xor_base(other, True)

    def __or_base(self, other, reverse):
        return self.__create_base_function(other, '|', reverse)

    def __or__(self, other):
        return self.__or_base(other, False)

    def __ror__(self, other):
        return self.__or_base(other, True)


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

    def evaluate(self, **variables):
        return(variables.get(self.name, self.name))

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


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

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

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


class Operator(Element):
    cache = []

    @classmethod
    def __get_cache(cls, symbol, function):
        for o in Operator.cache:
            if o.symbol == symbol and o.function == function:
                return o

    def __new__(cls, symbol, function, *args, **kwargs):
        existing = cls.__get_cache(symbol, function)
        if existing:
            return existing
        operator = super(Operator, cls).__new__(cls)
        return operator

    def __init__(self, symbol, function):
        if self in self.cache:
            return
        self.symbol = symbol
        self.function = function
        self.cache.append(self)

    def __call__(self, lhs, rhs):
        return self.function(lhs, rhs)

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


class Expression(Element):
    def __init__(self, expr):
        self.expr = expr

    def evaluate(self, **variables):
        if hasattr(self.expr, '__iter__'):
            lhs, op, rhs = self.expr
            lhs = convert_operand(lhs)
            rhs = convert_operand(rhs)
            result = op(lhs.evaluate(**variables), rhs.evaluate(**variables))
        else:
            result = self.expr
        return result

    def __str__(self):
        result = ""
        for element in self.expr:
            if hasattr(element, '__iter__'):
                result += str(create_expression(element))
            else:
                str_format = " {} " if isinstance(element, Operator) else "{}"
                result += str_format.format(str(element))
        return "({})".format(result)

    @property
    def variable_names(self):
        result = set()
        for element in self.expr:
            if isinstance(element, Variable):
                result.add(element.evaluate())
            elif isinstance(element, Expression):
                result.update(element.variable_names)
        return result


def create_constant(value):
    return Constant(value)


def create_variable(name):
    return Variable(name)


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


def create_expression(expression_structure):
    return Expression(expression_structure)

Предадох ново решение, след което видях коментарите на @Кирил и пушнах нова версия.

Интересно защо pep8 не е хванал нарушението на името на метода при мене - ще трябва да го погледна.

Успях да намеря време да попипна домашното още малко и разделих name от value за променливи и константи, но не ми хареса много, защото се наложи да предефинирам __str__ на Operator, Constant и Variable, - нещо, от което нямах нужда преди.

Съгласен съм обаче че архитектурно е по-правилно, просто ми оставя лош вкус, защото тук спира развитието на този "проект/домашно" и е накоден така, че да се extend-ва лесно, но за моментното решение има и по-добро според мен.