timeit

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

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

Решение на Аритметични изрази от Теодор Тошков

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

Към профила на Теодор Тошков

Резултати

  • 9 точки от тестове
  • 1 отнета точка
  • 8 точки общо
  • 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
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
class Expression:
    def __init__(self, expression_structure):
        if isinstance(expression_structure, Expression):
            self.mid = expression_structure
        else:
            self.mid = expression_structure[1]
            self.left = Expression(expression_structure[0])
            self.right = Expression(expression_structure[2])

    def __str__(self):
        if isinstance(self.mid, Expression):
            return str(self.mid)
        else:
            return "({} {} {})".format(
                str(self.left),
                str(self.mid),
                str(self.right),
                )

    @property
    def variable_names(self):
        if isinstance(self.mid, Expression):
            return self.mid.variable_names
        else:
            return self.left.variable_names | \
                   self.right.variable_names

    def evaluate(self, **variables):
        if isinstance(self.mid, Expression):
            return self.mid.evaluate(**variables)
        else:
            return self.mid.function(
                self.left.evaluate(**variables),
                self.right.evaluate(**variables)
                )

    def __add__(self, other):
        if isinstance(other, Expression):
            return Expression((self, plus, other))
        else:
            return Expression((self, plus, Constant(other)))

    def __radd__(self, other):
        return Expression((Constant(other), plus, self))

    def __mul__(self, other):
        if isinstance(other, Expression):
            return Expression((self, times, other))
        else:
            return Expression((self, times, Constant(other)))

    def __rmul__(self, other):
        return Expression((Constant(other), times, self))

    def __sub__(self, other):
        if isinstance(other, Expression):
            return Expression((self, minus, other))
        else:
            return Expression((self, minus, Constant(other)))

    def __rsub__(self, other):
        return Expression((Constant(other), minus, self))

    def __truediv__(self, other):
        if isinstance(other, Expression):
            return Expression((self, divided_by, other))
        else:
            return Expression((self, divided_by, Constant(other)))

    def __rtruediv__(self, other):
        return Expression((Constant(other), divided_by, self))

    def __mod__(self, other):
        if isinstance(other, Expression):
            return Expression((self, mod, other))
        else:
            return Expression((self, mod, Constant(other)))

    def __rmod__(self, other):
        return Expression((Constant(other), mod, self))

    def __xor__(self, other):
        if isinstance(other, Expression):
            return Expression((self, xor, other))
        else:
            return Expression((self, xor, Constant(other)))

    def __rxor__(self, other):
        return Expression((Constant(other), xor, self))

    def __and__(self, other):
        if isinstance(other, Expression):
            return Expression((self, myand, other))
        else:
            return Expression((self, myand, Constant(other)))

    def __rand__(self, other):
        return Expression((Constant(other), myand, self))

    def __or__(self, other):
        if isinstance(other, Expression):
            return Expression((self, myor, other))
        else:
            return Expression((self, myor, Constant(other)))

    def __ror__(self, other):
        return Expression((Constant(other), myor, self))

    def __lshift__(self, other):
        if isinstance(other, Expression):
            return Expression((self, lshift, other))
        else:
            return Expression((self, lshift, Constant(other)))

    def __rlshift__(self, other):
        return Expression((Constant(other), lshift, self))

    def __rshift__(self, other):
        if isinstance(other, Expression):
            return Expression((self, rshift, other))
        else:
            return Expression((self, rshift, Constant(other)))

    def __rrshift__(self, other):
        return Expression((Constant(other), rshift, self))

    def __pow__(self, other):
        if isinstance(other, Expression):
            return Expression((self, power, other))
        else:
            return Expression((self, power, Constant(other)))

    def __rpow__(self, other):
        return Expression((Constant(other), power, self))

    def __floordiv__(self, other):
        if isinstance(other, Expression):
            return Expression((self, floordiv, other))
        else:
            return Expression((self, floordiv, Constant(other)))

    def __rfloordiv__(self, other):
        return Expression((Constant(other), floordiv, self))

    def __divmod__(self, other):
        if isinstance(other, Expression):
            return Expression((self, mydivmod, other))
        else:
            return Expression((self, mydivmod, Constant(other)))

    def __rdivmod__(self, other):
        return Expression((Constant(other), mydivmod, self))


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

    def __str__(self):
        return self.symbol


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

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

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

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

    @property
    def variable_names(self):
        return set()


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

    def __str__(self):
        return self.name

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

    @property
    def variable_names(self):
        return {self.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)


def create_variable(name):
    return Variable(name)


plus = Operator("+", lambda x, y: x + y)
times = Operator("*", lambda x, y: x * y)
minus = Operator("-", lambda x, y: x - y)
divided_by = Operator("/", lambda x, y: x / y)
floordiv = Operator("//", lambda x, y: x // y)
mod = Operator("%", lambda x, y: x % y)
xor = Operator("^", lambda x, y: x ^ y)
myor = Operator("|", lambda x, y: x | y)
myand = Operator("&", lambda x, y: x & y)
lshift = Operator("<<", lambda x, y: x << y)
rshift = Operator(">>", lambda x, y: x >> y)
power = Operator("**", lambda x, y: x ** y)
mydivmod = Operator("divmod", lambda x, y: divmod(x, y))

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

.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
TypeError: 'int' object is not subscriptable

----------------------------------------------------------------------
Ran 19 tests in 0.115s

FAILED (errors=1)

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

Теодор обнови решението на 15.03.2016 16:57 (преди почти 2 години)

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
class Expression:
    def __init__(self, expression_structure):
        self.expression_structure = expression_structure

    def __str__(self):
        if type(self.expression_structure) in {Variable, Constant}:
            return str(self.expression_structure)
        else:
            return "(" +  \
                   str(Expression(self.expression_structure[0])) + \
                   " " + \
                   str(self.expression_structure[1]) + \
                   " " + \
                   str(Expression(self.expression_structure[2])) + \
                   ")"

    @property
    def variable_names(self):
        if type(self.expression_structure) is Constant:
            return set()
        elif type(self.expression_structure) is Variable:
            return {self.expression_structure.name}
        else:
            return Expression(self.expression_structure[0]).variable_names | \
                   Expression(self.expression_structure[2]).variable_names

    def evaluate(self, **variables):
        if type(self.expression_structure) is Constant:
            return self.expression_structure.evaluate()
        elif type(self.expression_structure) is Variable:
            return self.expression_structure.evaluate(**variables)
        else:
            return self.expression_structure[1].function(
                Expression(self.expression_structure[0]).evaluate(**variables),
                Expression(self.expression_structure[2]).evaluate(**variables)
                )

    def content(self):
        return self.expression_structure

    def __add__(self, other):
        if type(other) in {Expression, Constant, Variable}:
            return Expression((self.content(), plus, other.content()))
        else:
            return Expression((self.content(), plus, create_constant(other)))

    def __radd__(self, other):
        return Expression((create_constant(other), plus, self.content()))

    def __mul__(self, other):
        if type(other) in {Expression, Constant, Variable}:
            return Expression((self.content(), times, other.content()))
        else:
            return Expression((self.content(), times, create_constant(other)))

    def __rmul__(self, other):
        return Expression((create_constant(other), times, self.content()))

    def __sub__(self, other):
        if type(other) in {Expression, Constant, Variable}:
            return Expression((self.content(), minus, other.content()))
        else:
            return Expression((self.content(), minus, create_constant(other)))

    def __rsub__(self, other):
        return Expression((create_constant(other), minus, self.content()))

    def __truediv__(self, other):
        if type(other) in {Expression, Constant, Variable}:
            return Expression((self.content(), divided_by, other.content()))
        else:
            return Expression((self.content(), divided_by, Constant(other)))

    def __rtruediv__(self, other):
        return Expression((create_constant(other), divided_by, self.content()))


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

    def __str__(self):
        return self.symbol


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

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

    def evaluate(self):
        return self.value

    def content(self):
        return self


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

    def __str__(self):
        return self.name

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

    def content(self):
        return self


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)


def create_variable(name):
    return Variable(name)

plus = Operator("+", lambda x, y: x + y)
times = Operator("*", lambda x, y: x * y)
minus = Operator("-", lambda x, y: x - y)
divided_by = Operator("/", lambda x, y: x / y)
  • __str__ на Expression може да стане много по-добре ако ползваш format метода на str.
  • проверките ти с type(нещо) е доста по-удачно да се правят с isinstance, който сравнява не само класа на обекта, но и класовете, от които той наследява.
  • всеки път когато правил evaluate създаваш много Expression инстанции, които веднага след това умират, изглежда като да ти е по-полезно да имаш въпросните инстанции вместо да пазиш expression_structureи на всяка операция да го конвертираш до структура от Expression-и.

Проблем ли ще е, ако _ _init__ на Expression може да създава само по-прости изрази (const/var, operator, const/var), a create_expression може да си създава всякакви? (В примерите всички изрази са създадени чрез create_expression)

Това е твое решение. Според условието на задачата create_expression трябва да създава изрази. За външния свят няма значение какви класове ще дефинираш и как ще ги използваш, стига 4-те функции да връщат обекти с описаните атрибути и методи. Структурата, която искаш да постигнеш най-вероятно е двоично дърво. :)

Теодор обнови решението на 17.03.2016 18:20 (преди над 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
class Expression:
    def __init__(self, expression_structure):
        if isinstance(expression_structure, Expression):
            self.mid = expression_structure
        else:
            self.mid = expression_structure[1]
            self.left = Expression(expression_structure[0])
            self.right = Expression(expression_structure[2])

    def __str__(self):
        if isinstance(self.mid, Expression):
            return str(self.mid)
        else:
            return "({} {} {})".format(
                str(self.left),
                str(self.mid),
                str(self.right),
                )

    @property
    def variable_names(self):
        if isinstance(self.mid, Expression):
            return self.mid.variable_names
        else:
            return self.left.variable_names | \
                   self.right.variable_names

    def evaluate(self, **variables):
        if isinstance(self.mid, Expression):
            return self.mid.evaluate(**variables)
        else:
            return self.mid.function(
                self.left.evaluate(**variables),
                self.right.evaluate(**variables)
                )

    def __add__(self, other):
        if isinstance(other, Expression):
            return Expression((self, plus, other))
        else:
            return Expression((self, plus, Constant(other)))

    def __radd__(self, other):
        return Expression((Constant(other), plus, self))

    def __mul__(self, other):
        if isinstance(other, Expression):
            return Expression((self, times, other))
        else:
            return Expression((self, times, Constant(other)))

    def __rmul__(self, other):
        return Expression((Constant(other), times, self))

    def __sub__(self, other):
        if isinstance(other, Expression):
            return Expression((self, minus, other))
        else:
            return Expression((self, minus, Constant(other)))

    def __rsub__(self, other):
        return Expression((Constant(other), minus, self))

    def __truediv__(self, other):
        if isinstance(other, Expression):
            return Expression((self, divided_by, other))
        else:
            return Expression((self, divided_by, Constant(other)))

    def __rtruediv__(self, other):
        return Expression((Constant(other), divided_by, self))


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

    def __str__(self):
        return self.symbol


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

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

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

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

    @property
    def variable_names(self):
        return set()


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

    def __str__(self):
        return self.name

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

    @property
    def variable_names(self):
        return {self.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)


def create_variable(name):
    return Variable(name)


plus = Operator("+", lambda x, y: x + y)
times = Operator("*", lambda x, y: x * y)
minus = Operator("-", lambda x, y: x - y)
divided_by = Operator("/", lambda x, y: x / y)

Теодор обнови решението на 20.03.2016 10:29 (преди над 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
class Expression:
    def __init__(self, expression_structure):
        if isinstance(expression_structure, Expression):
            self.mid = expression_structure
        else:
            self.mid = expression_structure[1]
            self.left = Expression(expression_structure[0])
            self.right = Expression(expression_structure[2])

    def __str__(self):
        if isinstance(self.mid, Expression):
            return str(self.mid)
        else:
            return "({} {} {})".format(
                str(self.left),
                str(self.mid),
                str(self.right),
                )

    @property
    def variable_names(self):
        if isinstance(self.mid, Expression):
            return self.mid.variable_names
        else:
            return self.left.variable_names | \
                   self.right.variable_names

    def evaluate(self, **variables):
        if isinstance(self.mid, Expression):
            return self.mid.evaluate(**variables)
        else:
            return self.mid.function(
                self.left.evaluate(**variables),
                self.right.evaluate(**variables)
                )

    def __add__(self, other):
        if isinstance(other, Expression):
            return Expression((self, plus, other))
        else:
            return Expression((self, plus, Constant(other)))

    def __radd__(self, other):
        return Expression((Constant(other), plus, self))

    def __mul__(self, other):
        if isinstance(other, Expression):
            return Expression((self, times, other))
        else:
            return Expression((self, times, Constant(other)))

    def __rmul__(self, other):
        return Expression((Constant(other), times, self))

    def __sub__(self, other):
        if isinstance(other, Expression):
            return Expression((self, minus, other))
        else:
            return Expression((self, minus, Constant(other)))

    def __rsub__(self, other):
        return Expression((Constant(other), minus, self))

    def __truediv__(self, other):
        if isinstance(other, Expression):
            return Expression((self, divided_by, other))
        else:
            return Expression((self, divided_by, Constant(other)))

    def __rtruediv__(self, other):
        return Expression((Constant(other), divided_by, self))

    def __mod__(self, other):
        if isinstance(other, Expression):
            return Expression((self, mod, other))
        else:
            return Expression((self, mod, Constant(other)))

    def __rmod__(self, other):
        return Expression((Constant(other), mod, self))

    def __xor__(self, other):
        if isinstance(other, Expression):
            return Expression((self, xor, other))
        else:
            return Expression((self, xor, Constant(other)))

    def __rxor__(self, other):
        return Expression((Constant(other), xor, self))

    def __and__(self, other):
        if isinstance(other, Expression):
            return Expression((self, myand, other))
        else:
            return Expression((self, myand, Constant(other)))

    def __rand__(self, other):
        return Expression((Constant(other), myand, self))

    def __or__(self, other):
        if isinstance(other, Expression):
            return Expression((self, myor, other))
        else:
            return Expression((self, myor, Constant(other)))

    def __ror__(self, other):
        return Expression((Constant(other), myor, self))

    def __lshift__(self, other):
        if isinstance(other, Expression):
            return Expression((self, lshift, other))
        else:
            return Expression((self, lshift, Constant(other)))

    def __rlshift__(self, other):
        return Expression((Constant(other), lshift, self))

    def __rshift__(self, other):
        if isinstance(other, Expression):
            return Expression((self, rshift, other))
        else:
            return Expression((self, rshift, Constant(other)))

    def __rrshift__(self, other):
        return Expression((Constant(other), rshift, self))

    def __pow__(self, other):
        if isinstance(other, Expression):
            return Expression((self, power, other))
        else:
            return Expression((self, power, Constant(other)))

    def __rpow__(self, other):
        return Expression((Constant(other), power, self))

    def __floordiv__(self, other):
        if isinstance(other, Expression):
            return Expression((self, floordiv, other))
        else:
            return Expression((self, floordiv, Constant(other)))

    def __rfloordiv__(self, other):
        return Expression((Constant(other), floordiv, self))

    def __divmod__(self, other):
        if isinstance(other, Expression):
            return Expression((self, mydivmod, other))
        else:
            return Expression((self, mydivmod, Constant(other)))

    def __rdivmod__(self, other):
        return Expression((Constant(other), mydivmod, self))


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

    def __str__(self):
        return self.symbol


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

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

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

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

    @property
    def variable_names(self):
        return set()


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

    def __str__(self):
        return self.name

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

    @property
    def variable_names(self):
        return {self.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)


def create_variable(name):
    return Variable(name)


plus = Operator("+", lambda x, y: x + y)
times = Operator("*", lambda x, y: x * y)
minus = Operator("-", lambda x, y: x - y)
divided_by = Operator("/", lambda x, y: x / y)
floordiv = Operator("//", lambda x, y: x // y)
mod = Operator("%", lambda x, y: x % y)
xor = Operator("^", lambda x, y: x ^ y)
myor = Operator("|", lambda x, y: x | y)
myand = Operator("&", lambda x, y: x & y)
lshift = Operator("<<", lambda x, y: x << y)
rshift = Operator(">>", lambda x, y: x >> y)
power = Operator("**", lambda x, y: x ** y)
mydivmod = Operator("divmod", lambda x, y: divmod(x, y))