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
191
import operator
from collections import Iterable

variables = {}
OPERATORS = {}


class Expression:
    def __init__(self, expression):
        self.expression = expression
        self.variable_names = self.variable_names()

    def __str__(self):
        result, brackets = "(", 1
        for elem in self.expression:
            if type(elem) is tuple:
                result += str(Expression(elem))
            elif isinstance(elem, Operator):
                result += " " + str(elem) + " "
            else:
                result += str(elem)
        return result + brackets * ")"

    def operator(self, lhs, operator, rhs, symbol):
        rhs = Constant(rhs) if isinstance(rhs, (int, float, complex)) else rhs
        rhs = rhs.expression if type(rhs) is Expression else rhs
        lhs = Constant(lhs) if isinstance(lhs, (int, float, complex)) else lhs
        lhs = lhs.expression if type(lhs) is Expression else lhs
        return Expression((lhs, Operator(symbol, operator), rhs))

    def __add__(self, other):
        return self.operator(self, operator.add, other, '+')

    def __radd__(self, other):
        return self.operator(other, operator.add, self, '+')

    def __mul__(self, other):
        return self.operator(self, operator.mul, other, '*')

    def __rmul__(self, other):
        return self.operator(other, operator.mul, self, '*')

    def __sub__(self, other):
        return self.operator(self, operator.sub, other, '-')

    def __rsub__(self, other):
        return self.operator(other, operator.sub, self, '-')

    def __div__(self, other):
        return self.operator(self, operator.div, other, '/')

    def __rdiv__(self, other):
        return self.operator(other, operator.div, self, '/')

    def __floordiv__(self, other):
        return self.operator(self, operator.floordiv, other, '//')

    def __rfloordiv__(self, other):
        return self.operator(other, operator.floordiv, self, '//')

    def __truediv__(self, other):
        return self.operator(self, operator.truediv, other, '/')

    def __rtruediv__(self, other):
        return self.operator(other, operator.truediv, self, '/')

    def __mod__(self, other):
        return self.operator(self, operator.mod, other, '%')

    def __rmod__(self, other):
        return self.operator(other, operator.mod, self, '%')

    def __divmod__(self, other):
        return self.operator(self, operator.divmod, other, '%')

    def __rdivmod__(self, other):
        return self.operator(other, operator.divmod, self, '%')

    def __pow__(self, other):
        return self.operator(self, operator.pow, other, '**')

    def __rpow__(self, other):
        return self.operator(other, operator.pow, self, '**')

    def __rshift__(self, other):
        return self.operator(self, operator.rshift, other, '>>')

    def __rrshift__(self, other):
        return self.operator(other, operator.rshift, self, '>>')

    def __lshift__(self, other):
        return self.operator(self, operator.lshift, other, '<<')

    def __rlshift__(self, other):
        return self.operator(other, operator.lshift, self, '<<')

    def __and__(self, other):
        return self.operator(self, operator.and_, other, '&')

    def __rand__(self, other):
        return self.operator(other, operator.and_, self, '&')

    def __or__(self, other):
        return self.operator(self, operator.or_, other, '|')

    def __ror__(self, other):
        return self.operator(other, operator.or_, self, '|')

    def __xor__(self, other):
        return self.operator(self, operator.xor, other, '^')

    def __rxor__(self, other):
        return self.operator(other, operator.xor, self, '^')

    def evaluate(self, **kwargs):
        for key, value in kwargs.items():
            variables[key] = value

        expr = self.expression
        operator = expr[1]
        lhs = Expression(expr[0]) if isinstance(expr[0], Iterable) else expr[0]
        rhs = Expression(expr[2]) if isinstance(expr[2], Iterable) else expr[2]
        return operator.evaluate(lhs.evaluate(), rhs.evaluate())

    def extract_variables(self, expression, result):
        if isinstance(expression, Iterable):
            for elem in expression:
                if type(elem) is Variable:
                    result.append(str(elem))
                if isinstance(elem, Iterable):
                    self.extract_variables(elem, result)

    def variable_names(self):
        variables = []
        self.extract_variables(self.expression, variables)
        return variables


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

    def evaluate(self):
        return self.value

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


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

    def __str__(self):
        return self.name

    def evaluate(self, **kwargs):
        for key, value in kwargs.items():
            variables[key] = value
        return variables[self.name]

    def name(self):
        return self.name


class Operator(Expression):
    def __init__(self, symbol, function):
        self.symbol = symbol
        OPERATORS[self.symbol] = function

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

    def evaluate(self, lhs, rhs):
        return OPERATORS[self.symbol](lhs, rhs)


def create_variable(name):
    return Variable(name)


def create_constant(value):
    return Constant(value)


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


def create_expression(expression_structure):
    return Expression(expression_structure)

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

.E.................
======================================================================
ERROR: test_create_expression_with_literal (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
AttributeError: 'int' object has no attribute 'evaluate'

----------------------------------------------------------------------
Ran 19 tests in 0.169s

FAILED (errors=1)

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

Деница обнови решението на 20.03.2016 18:34 (преди над 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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
import operator
from collections import Iterable

VARIABLES = {}
OPERATORS = {}


class Expression:
    def __init__(self, expression):
        self.expression = expression
        self.variable_names = self.variable_names()

    def __str__(self):
        result, brackets = "(", 1
        for elem in self.expression:
            if type(elem) is tuple:
                result += str(Expression(elem))
            elif isinstance(elem, Operator):
                result += " " + str(elem) + " "
            else:
                result += str(elem)
        return result + brackets * ")"

    def __add__(self, other):
        if isinstance(other, (int, float, complex)):
            other = Constant(other)
        other = other.expression if type(other) is Expression else other
        expr = self.expression if type(self) is Expression else self
        return Expression((expr, Operator('+', operator.add), other))

    def __radd__(self, other):
        if isinstance(other, (int, float, complex)):
            other = Constant(other)
        other = other.expression if type(other) is Expression else other
        expr = self.expression if type(self) is Expression else self
        return Expression((other, Operator('+', operator.add), expr))

    def __mul__(self, other):
        if isinstance(other, (int, float, complex)):
            other = Constant(other)
        other = other.expression if type(other) is Expression else other
        expr = self.expression if type(self) is Expression else self
        return Expression((expr, Operator('*', operator.mul), other))

    def __rmul__(self, other):
        if isinstance(other, (int, float, complex)):
            other = Constant(other)
        other = other.expression if type(other) is Expression else other
        expr = self.expression if type(self) is Expression else self
        return Expression((other, Operator('*', operator.mul), expr))

    def __sub__(self, other):
        if isinstance(other, (int, float, complex)):
            other = Constant(other)
        other = other.expression if type(other) is Expression else other
        expr = self.expression if type(self) is Expression else self
        return Expression((expr, Operator('-', operator.sub), other))

    def __rsub__(self, other):
        if isinstance(other, (int, float, complex)):
            other = Constant(other)
        other = other.expression if type(other) is Expression else other
        expr = self.expression if type(self) is Expression else self
        return Expression((other, Operator('-', operator.sub), expr))

    def __div__(self, other):
        if isinstance(other, (int, float, complex)):
            other = Constant(other)
        other = other.expression if type(other) is Expression else other
        expr = self.expression if type(self) is Expression else self
        return Expression((expr, Operator('/', operator.div), other))

    def __rdiv__(self, other):
        if isinstance(other, (int, float, complex)):
            other = Constant(other)
        other = other.expression if type(other) is Expression else other
        expr = self.expression if type(self) is Expression else self
        return Expression((other, Operator('/', operator.div), expr))

    def __floordiv__(self, other):
        if isinstance(other, (int, float, complex)):
            other = Constant(other)
        other = other.expression if type(other) is Expression else other
        expr = self.expression if type(self) is Expression else self
        return Expression((expr, Operator('//', operator.floordiv), other))

    def __rfloordiv__(self, other):
        if isinstance(other, (int, float, complex)):
            other = Constant(other)
        other = other.expression if type(other) is Expression else other
        expr = self.expression if type(self) is Expression else self
        return Expression((other, Operator('//', operator.floordiv), expr))

    def __truediv__(self, other):
        if isinstance(other, (int, float, complex)):
            other = Constant(other)
        other = other.expression if type(other) is Expression else other
        expr = self.expression if type(self) is Expression else self
        return Expression((expr, Operator('/', operator.truediv), other))

    def __rtruediv__(self, other):
        if isinstance(other, (int, float, complex)):
            other = Constant(other)
        other = other.expression if type(other) is Expression else other
        expr = self.expression if type(self) is Expression else self
        return Expression((other, Operator('/', operator.truediv), expr))

    def __mod__(self, other):
        if isinstance(other, (int, float, complex)):
            other = Constant(other)
        other = other.expression if type(other) is Expression else other
        expr = self.expression if type(self) is Expression else self
        return Expression((expr, Operator('%', operator.truediv), other))

    def __rmod__(self, other):
        if isinstance(other, (int, float, complex)):
            other = Constant(other)
        other = other.expression if type(other) is Expression else other
        expr = self.expression if type(self) is Expression else self
        return Expression((other, Operator('%', operator.truediv), expr))

    def __divmod__(self, other):
        if isinstance(other, (int, float, complex)):
            other = Constant(other)
        other = other.expression if type(other) is Expression else other
        expr = self.expression if type(self) is Expression else self
        return Expression((expr, Operator('%', operator.truediv), other))

    def __rdivmod__(self, other):
        if isinstance(other, (int, float, complex)):
            other = Constant(other)
        other = other.expression if type(other) is Expression else other
        expr = self.expression if type(self) is Expression else self
        return Expression((other, Operator('%', operator.truediv), expr))

    def __pow__(self, other):
        if isinstance(other, (int, float, complex)):
            other = Constant(other)
        other = other.expression if type(other) is Expression else other
        expr = self.expression if type(self) is Expression else self
        return Expression((expr, Operator('**', operator.truediv), other))

    def __rpow__(self, other):
        if isinstance(other, (int, float, complex)):
            other = Constant(other)
        other = other.expression if type(other) is Expression else other
        expr = self.expression if type(self) is Expression else self
        return Expression((other, Operator('**', operator.truediv), expr))

    def __rshift__(self, other):
        if isinstance(other, (int, float, complex)):
            other = Constant(other)
        other = other.expression if type(other) is Expression else other
        expr = self.expression if type(self) is Expression else self
        return Expression((expr, Operator('>>', operator.truediv), other))

    def __rrshift__(self, other):
        if isinstance(other, (int, float, complex)):
            other = Constant(other)
        other = other.expression if type(other) is Expression else other
        expr = self.expression if type(self) is Expression else self
        return Expression((other, Operator('>>', operator.truediv), expr))

    def __lshift__(self, other):
        if isinstance(other, (int, float, complex)):
            other = Constant(other)
        other = other.expression if type(other) is Expression else other
        expr = self.expression if type(self) is Expression else self
        return Expression((expr, Operator('<<', operator.truediv), other))

    def __rlshift__(self, other):
        if isinstance(other, (int, float, complex)):
            other = Constant(other)
        other = other.expression if type(other) is Expression else other
        expr = self.expression if type(self) is Expression else self
        return Expression((other, Operator('<<', operator.truediv), expr))

    def __and__(self, other):
        if isinstance(other, (int, float, complex)):
            other = Constant(other)
        other = other.expression if type(other) is Expression else other
        expr = self.expression if type(self) is Expression else self
        return Expression((expr, Operator('&', operator.truediv), other))

    def __rand__(self, other):
        if isinstance(other, (int, float, complex)):
            other = Constant(other)
        other = other.expression if type(other) is Expression else other
        expr = self.expression if type(self) is Expression else self
        return Expression((other, Operator('&', operator.truediv), expr))

    def __or__(self, other):
        if isinstance(other, (int, float, complex)):
            other = Constant(other)
        other = other.expression if type(other) is Expression else other
        expr = self.expression if type(self) is Expression else self
        return Expression((expr, Operator('|', operator.truediv), other))

    def __ror__(self, other):
        if isinstance(other, (int, float, complex)):
            other = Constant(other)
        other = other.expression if type(other) is Expression else other
        expr = self.expression if type(self) is Expression else self
        return Expression((other, Operator('|', operator.truediv), expr))

    def __xor__(self, other):
        if isinstance(other, (int, float, complex)):
            other = Constant(other)
        other = other.expression if type(other) is Expression else other
        expr = self.expression if type(self) is Expression else self
        return Expression((expr, Operator('^', operator.truediv), other))

    def __rxor__(self, other):
        if isinstance(other, (int, float, complex)):
            other = Constant(other)
        other = other.expression if type(other) is Expression else other
        expr = self.expression if type(self) is Expression else self
        return Expression((other, Operator('^', operator.truediv), expr))

    def evaluate(self, **kwargs):
        for key, value in kwargs.items():
            VARIABLES[key] = value

        expr = self.expression
        operator = expr[1]
        lhs = Expression(expr[0]) if isinstance(expr[0], Iterable) else expr[0]
        rhs = Expression(expr[2]) if isinstance(expr[2], Iterable) else expr[2]
        return operator.evaluate(lhs.evaluate(), rhs.evaluate())

    def extract_variables(self, expression, result):
        if isinstance(expression, Iterable):
            for elem in expression:
                if type(elem) is Variable:
                    result.append(str(elem))
                if isinstance(elem, Iterable):
                    self.extract_variables(elem, result)

    def variable_names(self):
        variables = []
        self.extract_variables(self.expression, variables)
        return list((var for var in variables))


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

    def evaluate(self):
        return self.value

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


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

    def __str__(self):
        return self.name

    def evaluate(self, **kwargs):
        for key, value in kwargs.items():
            VARIABLES[key] = value
        return VARIABLES[self.name]

    def name(self):
        return self.name


class Operator(Expression):
    def __init__(self, symbol, function):
        self.symbol = symbol
        OPERATORS[self.symbol] = function

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

    def evaluate(self, lhs, rhs):
        return OPERATORS[self.symbol](lhs, rhs)


def create_variable(name):
    return Variable(name)


def create_constant(value):
    return Constant(value)


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


def create_expression(expression_structure):
    return Expression(expression_structure)
  • Всичките еднотипни проверки в предефинираните ти оператори не те ли навеждат на мисълта, че може да стане с малко по-малко код?
  • Името VARIABLES изглежда като нещо, което трябва да е константа, но всъщност то се променя всеки път, когато извикаш evaluate.
  • Всички проверки за това дали нещо е инстанция на Iterable могат да изчезнат ако пазиш структура(дърво?) от твои обекти вместо оригиналните tuple-и, които се подават на Expression.__init__.
  • Във variable_names създаваш списък, който попълваш чрез функция, която мутира аргумента си, който след това обхождаш с generator comprehension, който подаваш на констурктура на list. Преточваш едни и същи данни през три различни списъка, винаги в един и същи ред, винаги с една и съща стойност.
  • extract_cariables и evaluate могат да са много по-приятни реализирани с рекурсия.

Деница обнови решението на 20.03.2016 22:07 (преди над 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
import operator
from collections import Iterable

variables = {}
OPERATORS = {}


class Expression:
    def __init__(self, expression):
        self.expression = expression
        self.variable_names = self.variable_names()

    def __str__(self):
        result, brackets = "(", 1
        for elem in self.expression:
            if type(elem) is tuple:
                result += str(Expression(elem))
            elif isinstance(elem, Operator):
                result += " " + str(elem) + " "
            else:
                result += str(elem)
        return result + brackets * ")"

    def operator(self, lhs, operator, rhs, symbol):
        rhs = Constant(rhs) if isinstance(rhs, (int, float, complex)) else rhs
        rhs = rhs.expression if type(rhs) is Expression else rhs
        lhs = Constant(lhs) if isinstance(lhs, (int, float, complex)) else lhs
        lhs = lhs.expression if type(lhs) is Expression else lhs
        return Expression((lhs, Operator(symbol, operator), rhs))

    def __add__(self, other):
        return self.operator(self, operator.add, other, '+')

    def __radd__(self, other):
        return self.operator(other, operator.add, self, '+')

    def __mul__(self, other):
        return self.operator(self, operator.mul, other, '*')

    def __rmul__(self, other):
        return self.operator(other, operator.mul, self, '*')

    def __sub__(self, other):
        return self.operator(self, operator.sub, other, '-')

    def __rsub__(self, other):
        return self.operator(other, operator.sub, self, '-')

    def __div__(self, other):
        return self.operator(self, operator.div, other, '/')

    def __rdiv__(self, other):
        return self.operator(other, operator.div, self, '/')

    def __floordiv__(self, other):
        return self.operator(self, operator.floordiv, other, '//')

    def __rfloordiv__(self, other):
        return self.operator(other, operator.floordiv, self, '//')

    def __truediv__(self, other):
        return self.operator(self, operator.truediv, other, '/')

    def __rtruediv__(self, other):
        return self.operator(other, operator.truediv, self, '/')

    def __mod__(self, other):
        return self.operator(self, operator.mod, other, '%')

    def __rmod__(self, other):
        return self.operator(other, operator.mod, self, '%')

    def __divmod__(self, other):
        return self.operator(self, operator.divmod, other, '%')

    def __rdivmod__(self, other):
        return self.operator(other, operator.divmod, self, '%')

    def __pow__(self, other):
        return self.operator(self, operator.pow, other, '**')

    def __rpow__(self, other):
        return self.operator(other, operator.pow, self, '**')

    def __rshift__(self, other):
        return self.operator(self, operator.rshift, other, '>>')

    def __rrshift__(self, other):
        return self.operator(other, operator.rshift, self, '>>')

    def __lshift__(self, other):
        return self.operator(self, operator.lshift, other, '<<')

    def __rlshift__(self, other):
        return self.operator(other, operator.lshift, self, '<<')

    def __and__(self, other):
        return self.operator(self, operator.and_, other, '&')

    def __rand__(self, other):
        return self.operator(other, operator.and_, self, '&')

    def __or__(self, other):
        return self.operator(self, operator.or_, other, '|')

    def __ror__(self, other):
        return self.operator(other, operator.or_, self, '|')

    def __xor__(self, other):
        return self.operator(self, operator.xor, other, '^')

    def __rxor__(self, other):
        return self.operator(other, operator.xor, self, '^')

    def evaluate(self, **kwargs):
        for key, value in kwargs.items():
            variables[key] = value

        expr = self.expression
        operator = expr[1]
        lhs = Expression(expr[0]) if isinstance(expr[0], Iterable) else expr[0]
        rhs = Expression(expr[2]) if isinstance(expr[2], Iterable) else expr[2]
        return operator.evaluate(lhs.evaluate(), rhs.evaluate())

    def extract_variables(self, expression, result):
        if isinstance(expression, Iterable):
            for elem in expression:
                if type(elem) is Variable:
                    result.append(str(elem))
                if isinstance(elem, Iterable):
                    self.extract_variables(elem, result)

    def variable_names(self):
        variables = []
        self.extract_variables(self.expression, variables)
        return variables


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

    def evaluate(self):
        return self.value

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


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

    def __str__(self):
        return self.name

    def evaluate(self, **kwargs):
        for key, value in kwargs.items():
            variables[key] = value
        return variables[self.name]

    def name(self):
        return self.name


class Operator(Expression):
    def __init__(self, symbol, function):
        self.symbol = symbol
        OPERATORS[self.symbol] = function

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

    def evaluate(self, lhs, rhs):
        return OPERATORS[self.symbol](lhs, rhs)


def create_variable(name):
    return Variable(name)


def create_constant(value):
    return Constant(value)


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


def create_expression(expression_structure):
    return Expression(expression_structure)