timeit

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

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

Решение на Аритметични изрази от Андрей Иванов

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

Към профила на Андрей Иванов

Резултати

  • 8 точки от тестове
  • 0 бонус точки
  • 8 точки общо
  • 16 успешни тест(а)
  • 3 неуспешни тест(а)

Код

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
import collections


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

    def evaluate(self):
        return self.value


def create_constant(value):
    return Constant(value)


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

    def __str__(self):
        return self.name

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


def create_variable(name):
    return Variable(name)


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

    def __str__(self):
        return self.symbol


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


def convert_to_tuple(expression, list_help):
    for i in expression:
        if isinstance(i, Variable):
            list_help.append(i.name)
        elif isinstance(i, collections.Iterable):
            convert_to_tuple(i, list_help)
    return tuple(list_help)


def to_print(expression, list_help):
    list_help += '('
    for i in expression:
        if isinstance(i, Constant) or isinstance(i, Variable):
            list_help += str(i)
        elif isinstance(i, BinaryOperator):
            list_help += str(i)
        elif isinstance(i, int) or isinstance(i, float):
            list_help += str(i)
        elif isinstance(i, collections.Iterable):
            to_print(i, list_help)
        elif isinstance(i, Expression):
            to_print(i.expression, list_help)
    list_help += ')'


def evaluate_help(element, **variables):
    if isinstance(element, Constant):
        value = element.evaluate()
    elif isinstance(element, Variable):
        value = element.evaluate(**variables)
    elif isinstance(element, int) or isinstance(element, float):
        value = element
    elif isinstance(element, collections.Iterable):
        sub_expression = create_expression(element)
        value = sub_expression.evaluate(**variables)
    elif isinstance(element, Expression):
        value = element.evaluate(**variables)
    return value


class Expression(Operators):
    def __init__(self, expression):
        self.expression = expression
        list_help = []
        self.variable_names = convert_to_tuple(expression, list_help)

    def __str__(self):
        list_help = []
        to_print(self.expression, list_help)
        return ''.join(list_help)

    def evaluate(self, **variables):
        lhr = self.expression[0]
        function = self.expression[1].execution
        rhr = self.expression[2]
        value_lhr = evaluate_help(lhr, **variables)
        value_rhr = evaluate_help(rhr, **variables)
        return function(value_lhr, value_rhr)


def create_expression(expression_structure):
    return Expression(expression_structure)

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

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


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


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


----------------------------------------------------------------------
Ran 19 tests in 0.156s

FAILED (failures=3)

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

Андрей обнови решението на 20.03.2016 19:52 (преди над 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
import collections


class Abstract:
    def __add__(self, other):
        plus = create_operator('+', lambda lhs, rhs: lhs + rhs)
        result = create_expression((self, plus, other))
        return result

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

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

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

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

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

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

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

    def __floordiv__(self, other):
        fldiv = create_operator('//', lambda lhs, rhs: lhs // rhs)
        result = create_expression((self, fldiv, other))
        return result

    def __rfloordiv__(self, other):
        fldiv = create_operator('//', lambda lhs, rhs: lhs // rhs)
        result = create_expression((other, fldiv, self))
        return result

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

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

    def __pow__(self, other):
        p = create_operator('**', lambda lhs, rhs: lhs ** rhs)
        result = create_expression((self, p, other))
        return result

    def __rpow__(self, other):
        p = create_operator('**', lambda lhs, rhs: lhs ** rhs)
        result = create_expression((other, p, self))
        return result

    def __lshift__(self, other):
        lsh = create_operator('<<', lambda lhs, rhs: lhs << rhs)
        result = create_expression((self, lsh, other))
        return result

    def __rlshift__(self, other):
        lsh = create_operator('<<', lambda lhs, rhs: lhs << rhs)
        result = create_expression((other, lsh, self))
        return result

    def __rshift__(self, other):
        rsh = create_operator('>>', lambda lhs, rhs: lhs >> rhs)
        result = create_expression((self, rsh, other))
        return result

    def __rrshift__(self, other):
        rsh = create_operator('>>', lambda lhs, rhs: lhs >> rhs)
        result = create_expression((other, rsh, self))
        return result

    def __and__(self, other):
        opAnd = create_operator('and', lambda lhs, rhs: lhs and rhs)
        result = create_expression((self, opAnd, other))
        return result

    def __or__(self, other):
        opOr = create_operator('or', lambda lhs, rhs: lhs or rhs)
        result = create_expression((self, opOr, other))
        return result

    def __xor__(self, other):
        opXor = create_operator('^', lambda lhs, rhs: lhs ^ rhs)
        result = create_expression((self, opXor, other))
        return result


class Constant(Abstract):
    def __init__(self, val):
        self.__dict__['value'] = val

    def __setattr__(self, name, val):
        raise ValueError("Trying to change a constant value", self)

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

    def evaluate(self):
        return self.value


def create_constant(value):
    result = Constant(value)
    return result


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

    def __str__(self):
        return self.name

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


def create_variable(name):
    name = Variable(name)
    return name


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

    def __str__(self):
        return self.symbol


def create_operator(symbol, function):
    res = BinaryOperator(symbol)
    res.execution = function
    return res


def convertToTuple(arithExpression, listHelp):
    for i in arithExpression:
        if type(i) == Variable:
            listHelp.append(i.name)
        elif isinstance(i, collections.Iterable):
            convertToTuple(i, listHelp)
    return tuple(listHelp)


def toPrint(expression, res):
    res += '('
    for i in expression:
        if type(i) == Constant or type(i) == Variable:
            res += str(i)
        elif type(i) == BinaryOperator:
            res += str(i)
        elif type(i) == int or type(i) == float:
            res += str(i)
        elif isinstance(i, collections.Iterable):
            toPrint(i, res)
        elif type(i) == Expression:
            toPrint(i.expr, res)
    res += ')'


class Expression(Abstract):
    def __init__(self, arithExpression):
        self.expr = arithExpression
        res = []
        self.variable_names = convertToTuple(arithExpression, res)

    def __str__(self):
        res = []
        toPrint(self.expr, res)
        return ''.join(res)

    def evaluate(self, **variables):
        element = self.expr
        lhr = element[0]
        op = element[1].execution
        rhr = element[2]
        if type(lhr) == Constant:
            valueLhr = lhr.evaluate()
        elif type(lhr) == Variable:
            valueLhr = lhr.evaluate(** variables)
        elif type(lhr) == int or type(lhr) == float:
            valueLhr = lhr
        elif isinstance(lhr, collections.Iterable):
            temp = create_expression(lhr)
            valueLhr = temp.evaluate(**variables)
        elif type(lhr) == Expression:
            valueLhr = lhr.evaluate(**variables)
        if type(rhr) == Constant:
            valueRhr = rhr.evaluate()
        elif type(rhr) == Variable:
            valueRhr = rhr.evaluate(**variables)
        elif type(rhr) == int or type(rhr) == float:
            valueRhr = rhr
        elif isinstance(rhr, collections.Iterable):
            temp = create_expression(rhr)
            valueRhr = temp.evaluate(**variables)
        elif type(rhr) == Expression:
            valueRhr = rhr.evaluate(**variables)
        return op(valueLhr, valueRhr)


def create_expression(expression_structure):
        expr = Expression(expression_structure)
        return expr
  • В дефиницята на операторите създаваш променлива result само за да я върнеш на следващия ред. Същия приом го виждам и на доста други места.
  • Abstract не е добро име за това, за което го ползваш. Най-малкото класът ти не е абстрактен.
  • Защо правиш self.__dict__['value'] = val вместо self.value = val? Не използвай __dict__, освен ако нямаш наистина добра причина.
  • В този ред на мисли, val, temp и res не са добри имена.
  • На места използваш camelCase за да именуваш променливи (listHelp, valueLhr и valueRhr) и функции (toPrint и convertToTuple), което е в разрез с PEP8.
  • Предпочитай isinstance пред type за сравнение на типове. Ако все пак ти трябва type (какъвто не е случаят в това домашно), сравнявай с оператора is.
  • Нямаш нужда от Constant.__setattr__
  • Предпочитай str.format пред конкатениране на низове.
  • Имплементацията ти на Expression.evaluate е страшно сложна. Опрости малко.

Андрей обнови решението на 21.03.2016 15: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
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
import collections


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

    def evaluate(self):
        return self.value


def create_constant(value):
    return Constant(value)


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

    def __str__(self):
        return self.name

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


def create_variable(name):
    return Variable(name)


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

    def __str__(self):
        return self.symbol


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


def convert_to_tuple(expression, list_help):
    for i in expression:
        if isinstance(i, Variable):
            list_help.append(i.name)
        elif isinstance(i, collections.Iterable):
            convert_to_tuple(i, list_help)
    return tuple(list_help)


def to_print(expression, list_help):
    list_help += '('
    for i in expression:
        if isinstance(i, Constant) or isinstance(i, Variable):
            list_help += str(i)
        elif isinstance(i, BinaryOperator):
            list_help += str(i)
        elif isinstance(i, int) or isinstance(i, float):
            list_help += str(i)
        elif isinstance(i, collections.Iterable):
            to_print(i, list_help)
        elif isinstance(i, Expression):
            to_print(i.expression, list_help)
    list_help += ')'


def evaluate_help(element, **variables):
    if isinstance(element, Constant):
        value = element.evaluate()
    elif isinstance(element, Variable):
        value = element.evaluate(**variables)
    elif isinstance(element, int) or isinstance(element, float):
        value = element
    elif isinstance(element, collections.Iterable):
        sub_expression = create_expression(element)
        value = sub_expression.evaluate(**variables)
    elif isinstance(element, Expression):
        value = element.evaluate(**variables)
    return value


class Expression(Operators):
    def __init__(self, expression):
        self.expression = expression
        list_help = []
        self.variable_names = convert_to_tuple(expression, list_help)

    def __str__(self):
        list_help = []
        to_print(self.expression, list_help)
        return ''.join(list_help)

    def evaluate(self, **variables):
        lhr = self.expression[0]
        function = self.expression[1].execution
        rhr = self.expression[2]
        value_lhr = evaluate_help(lhr, **variables)
        value_rhr = evaluate_help(rhr, **variables)
        return function(value_lhr, value_rhr)


def create_expression(expression_structure):
    return Expression(expression_structure)