timeit

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

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

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

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

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

Резултати

  • 9 точки от тестове
  • 1 отнета точка
  • 8 точки общо
  • 17 успешни тест(а)
  • 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
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
import collections
import numbers

class DunderProvider:

    @staticmethod
    def operator_factory(symbol):
        oper_expr = 'Operator("{s}", lambda x, y: x {s} y)'.format(s=symbol)
        return eval(oper_expr)

    def __add__(self, other):
        oper = DunderProvider.operator_factory('+')
        return Expression((self, oper, other))

    def __radd__(self, other):
        return self + other

    def __sub__(self, other):
        oper = DunderProvider.operator_factory('-')
        return Expression((self, oper, other))

    def __rsub__(self, other):
        oper = DunderProvider.operator_factory('-')
        return Expression((other, oper, self))

    def __mul__(self, other):
        oper = DunderProvider.operator_factory('*')
        return Expression((self, oper, other))

    def __rmul__(self, other):
        return self * other

    def __truediv__(self, other):
        oper = DunderProvider.operator_factory('/')
        return Expression((self, oper, other))

    def __rtruediv__(self, other):
        oper = DunderProvider.operator_factory('/')
        return Expression((other, oper, self))

    def __floordiv__(self, other):
        oper = DunderProvider.operator_factory('//')
        return Expression((self, oper, other))
    
    def __rfloordiv__(self, other):
        oper = DunderProvider.operator_factory('//')
        return Expression((other, oper, self))
    
    def __mod__(self, other):
        oper = DunderProvider.operator_factory('%')
        return Expression((self, oper, other))
    
    def __rmod__(self, other):
        oper = DunderProvider.operator_factory('%')
        return Expression((other, oper, self))


class Constant(DunderProvider):

    '''
    def customize(self):
        dunders = ['__add__', '__mul__', '__sub__', '__truediv__',
                   '__floordiv__', '__mod__', '__divmod__', '__pow__']
        operators = ['+', '*', '-', '/', '//', '%', 'divmod', '**']

        for d, o in zip(dunders, operators):
            Constant.__dict__[d] = Expression((constant.operator_factory(o)))
    '''
    def __init__(self, value):
        self.__value = value

    @property
    def value(self):
        return self.__value

    @value.setter
    def value(self):
        raise AttributeError('''Can't set new value
        for {} object'''.format(type(self).__name__))
        
    def __str__(self):
        return str(self.value)

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



class Variable(DunderProvider):

    def __init__(self, name):
        self.name = name
        
    def __str__(self):
        return self.name

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


class Operator:

    objects = set()

    def __new__(cls, *args, **kwargs):
        for ind, obj in enumerate(cls.objects):
            if all(arg in obj.__dict__.values() for arg in args):
                return obj
        new_obj = super().__new__(cls)
        return new_obj

    def __init__(self, symbol, func):
        self.symbol, self.func = symbol, func
        self.objects.add(self)
        
    def __str__(self):
        return self.symbol

    def __call__(self, *args, **kwargs):
        return self.func(*args, **kwargs)


class Expression(DunderProvider):

    def __init__(self, expression):
        self.expression = list(expression)
        self._variable_names = set()

    def stringify(self, expression):
        for ind, exp in enumerate(expression):
            if isinstance(exp, collections.Sequence):
                expression[ind] = list(exp)
                self.stringify(expression[ind])
            else:
                expression[ind] = str(expression[ind])

    def __str__(self):
        str_ver = self.expression[:]
        self.stringify(str_ver)
        final_ver = str(str_ver)
        while "'" in final_ver:
            final_ver = final_ver.replace("'", '')
        while "," in final_ver:
            final_ver = final_ver.replace(",", '')
        while "[" in final_ver:
            final_ver = final_ver.replace("[", '(')
        while "]" in final_ver:
            final_ver = final_ver.replace("]", ')')
        return final_ver

    def get_variable_names(self, expression):
        for exp in expression:
            if isinstance(exp, Variable):
                self._variable_names.add(exp.name)
            elif isinstance(exp, collections.Sequence):
                self.get_variable_names(exp)

    @property
    def variable_names(self):
        self.get_variable_names(self.expression)
        return tuple(self._variable_names)

    def simplify(self, expr, **variables):
        operands = []
        for el in expr:
            if isinstance(el, Operator):
                oper = el
            elif isinstance(el, Variable):
                operands.append(variables[el.name])
            elif isinstance(el, Constant):
                operands.append(el.value)
            elif isinstance(el, numbers.Number):
                operands.append(el)
            elif isinstance(el, Expression):
                operands.append(self.evaluate_v2(el.expression, **variables))
        return oper(*operands)

    def evaluate_v2(self, expression, **variables):
        if any(hasattr(x, '__iter__') for x in expression):
            for ind, expr in enumerate(expression):
                if hasattr(expr, '__iter__'):
                    expression[ind] = list(expr)
                    res = self.evaluate_v2(expression[ind], **variables)
                    expression[ind] = res
        else:
            res = self.simplify(expression, **variables)

        return self.simplify(expression, **variables)

    def evaluate(self, **variables):
        return self.evaluate_v2(self.expression,  **variables)


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)

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

....F...........E..
======================================================================
ERROR: test_variables_and_constants_extra_operators (test.TestNativeOperators)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/data/rails/pyfmi-2016/releases/20160307095126/lib/language/python/runner.py", line 67, in thread
    raise result
TypeError: unsupported operand type(s) for ** or pow(): 'Variable' and 'Variable'

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


----------------------------------------------------------------------
Ran 19 tests in 0.141s

FAILED (failures=1, errors=1)

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

Ивелин обнови решението на 21.03.2016 14:46 (преди над 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
import collections
import numbers

class DunderProvider:

    @staticmethod
    def operator_factory(symbol):
        oper_expr = 'Operator("{s}", lambda x, y: x {s} y)'.format(s=symbol)
        return eval(oper_expr)

    def __add__(self, other):
        oper = DunderProvider.operator_factory('+')
        return Expression((self, oper, other))

    def __radd__(self, other):
        return self + other

    def __sub__(self, other):
        oper = DunderProvider.operator_factory('-')
        return Expression((self, oper, other))

    def __rsub__(self, other):
        oper = DunderProvider.operator_factory('-')
        return Expression((other, oper, self))

    def __mul__(self, other):
        oper = DunderProvider.operator_factory('*')
        return Expression((self, oper, other))

    def __rmul__(self, other):
        return self * other

    def __truediv__(self, other):
        oper = DunderProvider.operator_factory('/')
        return Expression((self, oper, other))

    def __rtruediv__(self, other):
        return self / other


class Constant(DunderProvider):

    '''
    def customize(self):
        dunders = ['__add__', '__mul__', '__sub__', '__truediv__',
                   '__floordiv__', '__mod__', '__divmod__', '__pow__']
        operators = ['+', '*', '-', '/', '//', '%', 'divmod', '**']

        for d, o in zip(dunders, operators):
            Constant.__dict__[d] = Expression((constant.operator_factory(o)))
    '''
    def __init__(self, value):
        self.__value = value

    @property
    def value(self):
        return self.__value

    @value.setter
    def value(self):
        raise AttributeError('''Can't set new value
        for {} object'''.format(type(self).__name__))
        
    def __str__(self):
        return str(self.value)

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



class Variable(DunderProvider):

    def __init__(self, name):
        self.name = name
        
    def __str__(self):
        return self.name

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


class Operator:

    objects = set()

    def __new__(cls, *args, **kwargs):
        for ind, obj in enumerate(cls.objects):
            if all(arg in obj.__dict__.values() for arg in args):
                return obj
        new_obj = super().__new__(cls)
        return new_obj

    def __init__(self, symbol, func):
        self.symbol, self.func = symbol, func
        self.objects.add(self)
        
    def __str__(self):
        return self.symbol

    def __call__(self, *args, **kwargs):
        return self.func(*args, **kwargs)


class Expression(DunderProvider):

    def __init__(self, expression):
        self.expression = list(expression)
        self._variable_names = set()

    def stringify(self, expression):
        for ind, exp in enumerate(expression):
            if isinstance(exp, collections.Sequence):
                expression[ind] = list(exp)
                self.stringify(expression[ind])
            else:
                expression[ind] = str(expression[ind])

    def __str__(self):
        str_ver = self.expression[:]
        self.stringify(str_ver)
        final_ver = str(str_ver)
        while "'" in final_ver:
            final_ver = final_ver.replace("'", '')
        while "," in final_ver:
            final_ver = final_ver.replace(",", '')
        while "[" in final_ver:
            final_ver = final_ver.replace("[", '(')
        while "]" in final_ver:
            final_ver = final_ver.replace("]", ')')
        return final_ver

    def get_variable_names(self, expression):
        for exp in expression:
            if isinstance(exp, Variable):
                self._variable_names.add(exp.name)
            elif isinstance(exp, collections.Sequence):
                self.get_variable_names(exp)

    @property
    def variable_names(self):
        self.get_variable_names(self.expression)
        return tuple(self._variable_names)

    def simplify(self, expr, **variables):
        operands = []
        for el in expr:
            if isinstance(el, Operator):
                oper = el
            elif isinstance(el, Variable):
                operands.append(variables[el.name])
            elif isinstance(el, Constant):
                operands.append(el.value)
            elif isinstance(el, numbers.Number):
                operands.append(el)
            elif isinstance(el, Expression):
                operands.append(self.evaluate_v2(el.expression, **variables))
        return oper(*operands)

    def evaluate_v2(self, expression, **variables):
        if any(hasattr(x, '__iter__') for x in expression):
            for ind, expr in enumerate(expression):
                if hasattr(expr, '__iter__'):
                    expression[ind] = list(expr)
                    res = self.evaluate_v2(expression[ind], **variables)
                    expression[ind] = res
        else:
            res = self.simplify(expression, **variables)

        return self.simplify(expression, **variables)

    def evaluate(self, **variables):
        return self.evaluate_v2(self.expression,  **variables)


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 15:42 (преди над 1 година)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
import collections
import numbers

class DunderProvider:

    @staticmethod
    def operator_factory(symbol):
        oper_expr = 'Operator("{s}", lambda x, y: x {s} y)'.format(s=symbol)
        return eval(oper_expr)

    def __add__(self, other):
        oper = DunderProvider.operator_factory('+')
        return Expression((self, oper, other))

    def __radd__(self, other):
        return self + other

    def __sub__(self, other):
        oper = DunderProvider.operator_factory('-')
        return Expression((self, oper, other))

    def __rsub__(self, other):
        oper = DunderProvider.operator_factory('-')
        return Expression((other, oper, self))

    def __mul__(self, other):
        oper = DunderProvider.operator_factory('*')
        return Expression((self, oper, other))

    def __rmul__(self, other):
        return self * other

    def __truediv__(self, other):
        oper = DunderProvider.operator_factory('/')
        return Expression((self, oper, other))

    def __rtruediv__(self, other):
        oper = DunderProvider.operator_factory('/')
        return Expression((other, oper, self))

    def __floordiv__(self, other):
        oper = DunderProvider.operator_factory('//')
        return Expression((self, oper, other))
    
    def __rfloordiv__(self, other):
        oper = DunderProvider.operator_factory('//')
        return Expression((other, oper, self))
    
    def __mod__(self, other):
        oper = DunderProvider.operator_factory('%')
        return Expression((self, oper, other))
    
    def __rmod__(self, other):
        oper = DunderProvider.operator_factory('%')
        return Expression((other, oper, self))


class Constant(DunderProvider):

    '''
    def customize(self):
        dunders = ['__add__', '__mul__', '__sub__', '__truediv__',
                   '__floordiv__', '__mod__', '__divmod__', '__pow__']
        operators = ['+', '*', '-', '/', '//', '%', 'divmod', '**']

        for d, o in zip(dunders, operators):
            Constant.__dict__[d] = Expression((constant.operator_factory(o)))
    '''
    def __init__(self, value):
        self.__value = value

    @property
    def value(self):
        return self.__value

    @value.setter
    def value(self):
        raise AttributeError('''Can't set new value
        for {} object'''.format(type(self).__name__))
        
    def __str__(self):
        return str(self.value)

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



class Variable(DunderProvider):

    def __init__(self, name):
        self.name = name
        
    def __str__(self):
        return self.name

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


class Operator:

    objects = set()

    def __new__(cls, *args, **kwargs):
        for ind, obj in enumerate(cls.objects):
            if all(arg in obj.__dict__.values() for arg in args):
                return obj
        new_obj = super().__new__(cls)
        return new_obj

    def __init__(self, symbol, func):
        self.symbol, self.func = symbol, func
        self.objects.add(self)
        
    def __str__(self):
        return self.symbol

    def __call__(self, *args, **kwargs):
        return self.func(*args, **kwargs)


class Expression(DunderProvider):

    def __init__(self, expression):
        self.expression = list(expression)
        self._variable_names = set()

    def stringify(self, expression):
        for ind, exp in enumerate(expression):
            if isinstance(exp, collections.Sequence):
                expression[ind] = list(exp)
                self.stringify(expression[ind])
            else:
                expression[ind] = str(expression[ind])

    def __str__(self):
        str_ver = self.expression[:]
        self.stringify(str_ver)
        final_ver = str(str_ver)
        while "'" in final_ver:
            final_ver = final_ver.replace("'", '')
        while "," in final_ver:
            final_ver = final_ver.replace(",", '')
        while "[" in final_ver:
            final_ver = final_ver.replace("[", '(')
        while "]" in final_ver:
            final_ver = final_ver.replace("]", ')')
        return final_ver

    def get_variable_names(self, expression):
        for exp in expression:
            if isinstance(exp, Variable):
                self._variable_names.add(exp.name)
            elif isinstance(exp, collections.Sequence):
                self.get_variable_names(exp)

    @property
    def variable_names(self):
        self.get_variable_names(self.expression)
        return tuple(self._variable_names)

    def simplify(self, expr, **variables):
        operands = []
        for el in expr:
            if isinstance(el, Operator):
                oper = el
            elif isinstance(el, Variable):
                operands.append(variables[el.name])
            elif isinstance(el, Constant):
                operands.append(el.value)
            elif isinstance(el, numbers.Number):
                operands.append(el)
            elif isinstance(el, Expression):
                operands.append(self.evaluate_v2(el.expression, **variables))
        return oper(*operands)

    def evaluate_v2(self, expression, **variables):
        if any(hasattr(x, '__iter__') for x in expression):
            for ind, expr in enumerate(expression):
                if hasattr(expr, '__iter__'):
                    expression[ind] = list(expr)
                    res = self.evaluate_v2(expression[ind], **variables)
                    expression[ind] = res
        else:
            res = self.simplify(expression, **variables)

        return self.simplify(expression, **variables)

    def evaluate(self, **variables):
        return self.evaluate_v2(self.expression,  **variables)


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)