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


class Operand:
    def __add__(self, arg):
        return self._create_expression(arg, '+', is_reversed=False)

    def __sub__(self, arg):
        return self._create_expression(arg, '-', is_reversed=False)

    def __mul__(self, arg):
        return self._create_expression(arg, '*', is_reversed=False)

    def __truediv__(self, arg):
        return self._create_expression(arg, '/', is_reversed=False)

    def __floordiv__(self, arg):
        return self._create_expression(arg, '//', is_reversed=False)

    def __mod__(self, arg):
        return self._create_expression(arg, '%', is_reversed=False)

    def __divmod__(self, arg):
        return self._create_expression(arg, 'divmod', is_reversed=False)

    def __pow__(self, arg):
        return self._create_expression(arg, '**', is_reversed=False)

    def __lshift__(self, arg):
        return self._create_expression(arg, '<<', is_reversed=False)

    def __rshift__(self, arg):
        return self._create_expression(arg, '>>', is_reversed=False)

    def __and__(self, arg):
        return self._create_expression(arg, '&', is_reversed=False)

    def __xor__(self, arg):
        return self._create_expression(arg, '^', is_reversed=False)

    def __or__(self, arg):
        return self._create_expression(arg, '|', is_reversed=False)

    def __radd__(self, arg):
        return self._create_expression(arg, '+', is_reversed=True)

    def __rsub__(self, arg):
        return self._create_expression(arg, '-', is_reversed=True)

    def __rmul__(self, arg):
        return self._create_expression(arg, '*', is_reversed=True)

    def __rtruediv__(self, arg):
        return self._create_expression(arg, '/', is_reversed=True)

    def __rfloordiv__(self, arg):
        return self._create_expression(arg, '//', is_reversed=True)

    def __rmod__(self, arg):
        return self._create_expression(arg, '%', is_reversed=True)

    def __rdivmod__(self, arg):
        return self._create_expression(arg, 'divmod', is_reversed=True)

    def __rpow__(self, arg):
        return self._create_expression(arg, '**', is_reversed=True)

    def __rlshift__(self, arg):
        return self._create_expression(arg, '<<', is_reversed=True)

    def __rrshift__(self, arg):
        return self._create_expression(arg, '>>', is_reversed=True)

    def __rand__(self, arg):
        return self._create_expression(arg, '&', is_reversed=True)

    def __rxor__(self, arg):
        return self._create_expression(arg, '^', is_reversed=True)

    def __ror__(self, arg):
        return self._create_expression(arg, '|', is_reversed=True)

    def _create_expression(self, argument, operator_symbol, is_reversed):
        pass


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

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

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

    def __repr__(self):
        return str(self)

    def _create_expression(self, argument, operator_symbol, is_reversed):
        return transform(self, argument, operator_symbol, is_reversed)


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

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

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

    def __repr__(self):
        return str(self)

    def _create_expression(self, argument, operator_symbol, is_reversed):
        return transform(self, argument, operator_symbol, is_reversed)


class Operator:
    def __init__(self, name, func):
        self.name = name
        self.func = func

    def evaluate(self, left_arg, right_arg):
        return self.func(left_arg, right_arg)

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

    def __repr__(self):
        return str(self)


class Expression(Operand):
    def __init__(self, first, second, third):
        self.left = first
        self.right = third
        self.function = second

    def evaluate(self, **kwargs):
        left_argument = self.left.evaluate(**kwargs)
        right_argument = self.right.evaluate(**kwargs)
        return self.function.evaluate(left_argument, right_argument)

    @property
    def variable_names(self):
        left_variables = self.variables(self.left)
        right_variables = self.variables(self.right)
        return left_variables.union(right_variables)

    def variables(self, operand):
        if type(operand) == Expression:
            return operand.variable_names
        elif type(operand) == Variable:
            return {operand.name}
        return set()

    def __str__(self):
        return "({} {} {})".format(self.left, self.function, self.right)

    def __repr__(self):
        return str(self)

    def _create_expression(self, argument, operator_symbol, is_reversed):
        return transform(self, argument, operator_symbol, is_reversed)


def transform(operand, argument, operator_symbol, is_reversed):
    if isinstance(argument, numbers.Number):
        argument = create_constant(argument)
    elif isinstance(argument, str):
        argument = create_variable(argument)

    function = CREATED_OPERATORS[operator_symbol]
    if is_reversed:
        return create_expression((argument, function, operand))
    return create_expression((operand, function, argument))


CREATED_OPERATORS = {
        '+': Operator('+', operator.add),
        '-': Operator('-', operator.sub),
        '*': Operator('*', operator.mul),
        '/': Operator('/', operator.truediv),
        '//': Operator('//', operator.floordiv),
        '%': Operator('%', operator.mod),
        '**': Operator('**', operator.pow),
        '<<': Operator('<<', operator.lshift),
        '>>': Operator('>>', operator.rshift),
        '&': Operator('&', operator.and_),
        '^': Operator('^', operator.xor),
        '|': Operator('|', operator.or_),
        'divmod': Operator('divmod', divmod)
    }


def generate(name, func):
    if name not in CREATED_OPERATORS:
        CREATED_OPERATORS[name] = Operator(name, func)
    return CREATED_OPERATORS[name]


def create_constant(value):
    return Constant(value)


def create_variable(name):
    return Variable(name)


def create_operator(name, func):
    return generate(name, func)


def parse(argument):
    if isinstance(argument, collections.Iterable):
        return create_expression(argument)
    return argument


def create_expression(args):
    return Expression(*map(parse, args))

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

.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.195s

FAILED (errors=1)

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

Александър обнови решението на 15.03.2016 23:21 (преди почти 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
import operator as o
import numbers


class Operand:
    def __add__(self, arg):
        return self.__create_expression(arg, '+', False)

    def __sub__(self, arg):
        return self.__create_expression(arg, '-', False)

    def __mul__(self, arg):
        return self.__create_expression(arg, '*', False)

    def __truediv__(self, arg):
        return self.__create_expression(arg, '/', False)

    def __radd__(self, arg):
        return self.__create_expression(arg, '+', True)

    def __rsub__(self, arg):
        return self.__create_expression(arg, '-', True)

    def __rmul__(self, arg):
        return self.__create_expression(arg, '*', True)

    def __rtruediv__(self, arg):
        return self.__create_expression(arg, '/', True)

    def __create_expression(self, argument, operator, is_arg_left):
        if isinstance(argument, numbers.Number):
            argument = create_constant(argument)
        elif isinstance(argument, str):
            argument = create_variable(argument)

        operator = CreateOperators.get(operator)
        if is_arg_left:
            return create_expression((argument, operator, self))
        return create_expression((self, operator, argument))


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

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

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

    def __repr__(self):
        return self.__str__()


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

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

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

    def __repr__(self):
        return self.__str__()


class Operator:
    def __init__(self, name, func):
        self.name = name
        self.func = func

    def evaluate(self, left_arg, right_arg):
        return self.func(left_arg, right_arg)

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

    def __repr__(self):
        return self.__str__()


class Expression(Operand):
    def __init__(self, first, second, third):
        self.left = first
        self.right = third
        self.operator = second

    def evaluate(self, **kwargs):
        left_argument = self.left.evaluate(**kwargs)
        right_argument = self.right.evaluate(**kwargs)
        return self.operator.evaluate(left_argument, right_argument)

    @property
    def variable_names(self):
        left_variables = self.variables(self.left)
        right_variables = self.variables(self.right)
        return set().update(left_variables, right_variables)

    def variables(self, operand):
        if type(operand) == Expression:
            return operand.variable_names
        elif type(operand) == Variable:
            return {operand.name}
        return set()

    def __str__(self):
        return "({} {} {})".format(self.left, self.operator, self.right)

    def __repr__(self):
        return self.__str__()


class CreateOperators:
    operators = {'+': Operator('+', o.add),
                 '-': Operator('-', o.sub),
                 '*': Operator('*', o.mul),
                 '/': Operator('/', o.truediv)}

    @staticmethod
    def generate(name, func):
        if name not in CreateOperators.operators:
            CreateOperators.operators[name] = Operator(name, func)
        return CreateOperators.operators[name]

    @staticmethod
    def get(name):
        return CreateOperators.operators[name]


def create_constant(value):
    return Constant(value)


def create_variable(name):
    return Variable(name)


def create_operator(name, func):
    return CreateOperators.generate(name, func)


def parse(argument):
    if type(argument) == tuple:
        return create_expression(argument)
    return argument


def create_expression(args):
    return Expression(*map(parse, args))

Имагинерните числа да ги считаме ли за валиден вход за константи?

и класа CreateOperator добра идея ли е? Защото мисля да направя нещо подобно за константите и променливите(не мисля,че ни трябват дест 5-ци и пет 'x'-a например).

Александър обнови решението на 16.03.2016 00:14 (преди почти 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
import operator as o
import numbers


class Operand:
    def __add__(self, arg):
        return self.__create_expression(arg, '+', False)

    def __sub__(self, arg):
        return self.__create_expression(arg, '-', False)

    def __mul__(self, arg):
        return self.__create_expression(arg, '*', False)

    def __truediv__(self, arg):
        return self.__create_expression(arg, '/', False)

    def __radd__(self, arg):
        return self.__create_expression(arg, '+', True)

    def __rsub__(self, arg):
        return self.__create_expression(arg, '-', True)

    def __rmul__(self, arg):
        return self.__create_expression(arg, '*', True)

    def __rtruediv__(self, arg):
        return self.__create_expression(arg, '/', True)

    def __create_expression(self, argument, operator, is_arg_left):
        if isinstance(argument, numbers.Number):
            argument = create_constant(argument)
        elif isinstance(argument, str):
            argument = create_variable(argument)

        operator = CreateOperators.get(operator)
        if is_arg_left:
            return create_expression((argument, operator, self))
        return create_expression((self, operator, argument))


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

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

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

    def __repr__(self):
        return self.__str__()


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

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

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

    def __repr__(self):
        return self.__str__()


class Operator:
    def __init__(self, name, func):
        self.name = name
        self.func = func

    def evaluate(self, left_arg, right_arg):
        return self.func(left_arg, right_arg)

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

    def __repr__(self):
        return self.__str__()


class Expression(Operand):
    def __init__(self, first, second, third):
        self.left = first
        self.right = third
        self.operator = second

    def evaluate(self, **kwargs):
        left_argument = self.left.evaluate(**kwargs)
        right_argument = self.right.evaluate(**kwargs)
        return self.operator.evaluate(left_argument, right_argument)

    @property
    def variable_names(self):
        left_variables = self.variables(self.left)
        right_variables = self.variables(self.right)
        return left_variables.union(right_variables)

    def variables(self, operand):
        if type(operand) == Expression:
            return operand.variable_names
        elif type(operand) == Variable:
            return {operand.name}
        return set()

    def __str__(self):
        return "({} {} {})".format(self.left, self.operator, self.right)

    def __repr__(self):
        return self.__str__()


class CreateOperators:
    operators = {'+': Operator('+', o.add),
                 '-': Operator('-', o.sub),
                 '*': Operator('*', o.mul),
                 '/': Operator('/', o.truediv)}

    @staticmethod
    def generate(name, func):
        if name not in CreateOperators.operators:
            CreateOperators.operators[name] = Operator(name, func)
        return CreateOperators.operators[name]

    @staticmethod
    def get(name):
        return CreateOperators.operators[name]


def create_constant(value):
    return Constant(value)


def create_variable(name):
    return Variable(name)


def create_operator(name, func):
    return CreateOperators.generate(name, func)


def parse(argument):
    if type(argument) == tuple:
        return create_expression(argument)
    return argument


def create_expression(args):
    return Expression(*map(parse, args))
  • имагинерните числа са числа, да :)
  • предвид, че никога няма да го инстанцираш, спокойно можеш да разкараш CreateOperators и просто да оставиш dict-а и двете функции в него като глобални имена във файла ти.
  • не е яко Operand да се занимава със създаване на Expression обекти. Родителския клас не би следвало изобщо да знае за съществуването на децата си.
  • import operator as o не е хубав избор. Така или иначе __create_expression е лоша идея, така че сблъска на имена ще изезне ако го махнеш. От друга страна o е ужасно име, особено за модул, който има доста хубаво описателно име. :)

Александър обнови решението на 17.03.2016 00:56 (преди над 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
import operator
import numbers
import collections


class Operand:
    def __add__(self, arg):
        return self._create_expression(arg, '+', is_reversed=False)

    def __sub__(self, arg):
        return self._create_expression(arg, '-', is_reversed=False)

    def __mul__(self, arg):
        return self._create_expression(arg, '*', is_reversed=False)

    def __truediv__(self, arg):
        return self._create_expression(arg, '/', is_reversed=False)

    def __radd__(self, arg):
        return self._create_expression(arg, '+', is_reversed=True)

    def __rsub__(self, arg):
        return self._create_expression(arg, '-', is_reversed=True)

    def __rmul__(self, arg):
        return self._create_expression(arg, '*', is_reversed=True)

    def __rtruediv__(self, arg):
        return self._create_expression(arg, '/', is_reversed=True)

    def _create_expression(self, argument, function_symbol, is_reversed):
        pass


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

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

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

    def __repr__(self):
        return str(self)

    def _create_expression(self, argument, function_symbol, is_reversed):
        if isinstance(argument, numbers.Number):
            argument = create_constant(argument)
        elif isinstance(argument, str):
            argument = create_variable(argument)

        function = CREATED_FUNCTIONS[function_symbol]
        if is_reversed:
            return create_expression((argument, function, self))
        return create_expression((self, function, argument))


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

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

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

    def __repr__(self):
        return str(self)

    def _create_expression(self, argument, function_symbol, is_reversed):
        if isinstance(argument, numbers.Number):
            argument = create_constant(argument)
        elif isinstance(argument, str):
            argument = create_variable(argument)

        function = CREATED_FUNCTIONS[function_symbol]
        if is_reversed:
            return create_expression((argument, function, self))
        return create_expression((self, function, argument))


class Operator:
    def __init__(self, name, func):
        self.name = name
        self.func = func

    def evaluate(self, left_arg, right_arg):
        return self.func(left_arg, right_arg)

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

    def __repr__(self):
        return str(self)


class Expression(Operand):
    def __init__(self, first, second, third):
        self.left = first
        self.right = third
        self.function = second

    def evaluate(self, **kwargs):
        left_argument = self.left.evaluate(**kwargs)
        right_argument = self.right.evaluate(**kwargs)
        return self.function.evaluate(left_argument, right_argument)

    @property
    def variable_names(self):
        left_variables = self.variables(self.left)
        right_variables = self.variables(self.right)
        return left_variables.union(right_variables)

    def variables(self, operand):
        if type(operand) == Expression:
            return operand.variable_names
        elif type(operand) == Variable:
            return {operand.name}
        return set()

    def __str__(self):
        return "({} {} {})".format(self.left, self.function, self.right)

    def __repr__(self):
        return str(self)

    def _create_expression(self, argument, function_symbol, is_reversed):
        if isinstance(argument, numbers.Number):
            argument = create_constant(argument)
        elif isinstance(argument, str):
            argument = create_variable(argument)

        function = CREATED_FUNCTIONS[function_symbol]
        if is_reversed:
            return create_expression((argument, function, self))
        return create_expression((self, function, argument))


CREATED_FUNCTIONS = {'+': Operator('+', operator.add),
                     '-': Operator('-', operator.sub),
                     '*': Operator('*', operator.mul),
                     '/': Operator('/', operator.truediv)}


def generate(name, func):
    if name not in CREATED_FUNCTIONS:
        CREATED_FUNCTIONS[name] = Operator(name, func)
    return CREATED_FUNCTIONS[name]


def create_constant(value):
    return Constant(value)


def create_variable(name):
    return Variable(name)


def create_operator(name, func):
    return generate(name, func)


def parse(argument):
    if isinstance(argument, collections.Iterable):
        return create_expression(argument)
    return argument


def create_expression(args):
    return Expression(*map(parse, args))

махнах създаването на Expression обекти в Operand, наследниците си предефинират _create_expression, но сега има доста copy/paste

ОК ли е да изведа логиката на _create_expression във външна функция и да си я викам от съответните класове?

Александър обнови решението на 17.03.2016 10:14 (преди над 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
import operator
import numbers
import collections


class Operand:
    def __add__(self, arg):
        return self._create_expression(arg, '+', is_reversed=False)

    def __sub__(self, arg):
        return self._create_expression(arg, '-', is_reversed=False)

    def __mul__(self, arg):
        return self._create_expression(arg, '*', is_reversed=False)

    def __truediv__(self, arg):
        return self._create_expression(arg, '/', is_reversed=False)

    def __radd__(self, arg):
        return self._create_expression(arg, '+', is_reversed=True)

    def __rsub__(self, arg):
        return self._create_expression(arg, '-', is_reversed=True)

    def __rmul__(self, arg):
        return self._create_expression(arg, '*', is_reversed=True)

    def __rtruediv__(self, arg):
        return self._create_expression(arg, '/', is_reversed=True)

    def _create_expression(self, argument, operator_symbol, is_reversed):
        pass


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

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

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

    def __repr__(self):
        return str(self)

    def _create_expression(self, argument, operator_symbol, is_reversed):
        return transform(self, argument, operator_symbol, is_reversed)


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

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

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

    def __repr__(self):
        return str(self)

    def _create_expression(self, argument, operator_symbol, is_reversed):
        return transform(self, argument, operator_symbol, is_reversed)


class Operator:
    def __init__(self, name, func):
        self.name = name
        self.func = func

    def evaluate(self, left_arg, right_arg):
        return self.func(left_arg, right_arg)

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

    def __repr__(self):
        return str(self)


CREATED_OPERATORS = {'+': Operator('+', operator.add),
                     '-': Operator('-', operator.sub),
                     '*': Operator('*', operator.mul),
                     '/': Operator('/', operator.truediv)}


class Expression(Operand):
    def __init__(self, first, second, third):
        self.left = first
        self.right = third
        self.function = second

    def evaluate(self, **kwargs):
        left_argument = self.left.evaluate(**kwargs)
        right_argument = self.right.evaluate(**kwargs)
        return self.function.evaluate(left_argument, right_argument)

    @property
    def variable_names(self):
        left_variables = self.variables(self.left)
        right_variables = self.variables(self.right)
        return left_variables.union(right_variables)

    def variables(self, operand):
        if type(operand) == Expression:
            return operand.variable_names
        elif type(operand) == Variable:
            return {operand.name}
        return set()

    def __str__(self):
        return "({} {} {})".format(self.left, self.function, self.right)

    def __repr__(self):
        return str(self)

    def _create_expression(self, argument, operator_symbol, is_reversed):
        return transform(self, argument, operator_symbol, is_reversed)


def transform(operand, argument, operator_symbol, is_reversed):
    if isinstance(argument, numbers.Number):
        argument = create_constant(argument)
    elif isinstance(argument, str):
        argument = create_variable(argument)

    function = CREATED_OPERATORS[operator_symbol]
    if is_reversed:
        return create_expression((argument, function, operand))
    return create_expression((operand, function, argument))


def generate(name, func):
    if name not in CREATED_OPERATORS:
        CREATED_OPERATORS[name] = Operator(name, func)
    return CREATED_OPERATORS[name]


def create_constant(value):
    return Constant(value)


def create_variable(name):
    return Variable(name)


def create_operator(name, func):
    return generate(name, func)


def parse(argument):
    if isinstance(argument, collections.Iterable):
        return create_expression(argument)
    return argument


def create_expression(args):
    return Expression(*map(parse, args))

Александър обнови решението на 20.03.2016 17:12 (преди над 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
import operator
import numbers
import collections


class Operand:
    def __add__(self, arg):
        return self._create_expression(arg, '+', is_reversed=False)

    def __sub__(self, arg):
        return self._create_expression(arg, '-', is_reversed=False)

    def __mul__(self, arg):
        return self._create_expression(arg, '*', is_reversed=False)

    def __truediv__(self, arg):
        return self._create_expression(arg, '/', is_reversed=False)

    def __floordiv__(self, arg):
        return self._create_expression(arg, '//', is_reversed=False)

    def __mod__(self, arg):
        return self._create_expression(arg, '%', is_reversed=False)

    def __divmod__(self, arg):
        return self._create_expression(arg, '?', is_reversed=False)

    def __pow__(self, arg):
        return self._create_expression(arg, '**', is_reversed=False)

    def __lshift__(self, arg):
        return self._create_expression(arg, '<<', is_reversed=False)

    def __rshift__(self, arg):
        return self._create_expression(arg, '>>', is_reversed=False)

    def __and__(self, arg):
        return self._create_expression(arg, '&', is_reversed=False)

    def __xor__(self, arg):
        return self._create_expression(arg, '^', is_reversed=False)

    def __or__(self, arg):
        return self._create_expression(arg, '|', is_reversed=False)

    def __radd__(self, arg):
        return self._create_expression(arg, '+', is_reversed=True)

    def __rsub__(self, arg):
        return self._create_expression(arg, '-', is_reversed=True)

    def __rmul__(self, arg):
        return self._create_expression(arg, '*', is_reversed=True)

    def __rtruediv__(self, arg):
        return self._create_expression(arg, '/', is_reversed=True)

    def __rfloordiv__(self, arg):
        return self._create_expression(arg, '//', is_reversed=True)

    def __rmod__(self, arg):
        return self._create_expression(arg, '%', is_reversed=True)

    def __rdivmod__(self, arg):
        return self._create_expression(arg, '?', is_reversed=True)

    def __rpow__(self, arg):
        return self._create_expression(arg, '**', is_reversed=True)

    def __rlshift__(self, arg):
        return self._create_expression(arg, '<<', is_reversed=True)

    def __rrshift__(self, arg):
        return self._create_expression(arg, '>>', is_reversed=True)

    def __rand__(self, arg):
        return self._create_expression(arg, '&', is_reversed=True)

    def __rxor__(self, arg):
        return self._create_expression(arg, '^', is_reversed=True)

    def __ror__(self, arg):
        return self._create_expression(arg, '|', is_reversed=True)

    def _create_expression(self, argument, operator_symbol, is_reversed):
        pass


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

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

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

    def __repr__(self):
        return str(self)

    def _create_expression(self, argument, operator_symbol, is_reversed):
        return transform(self, argument, operator_symbol, is_reversed)


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

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

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

    def __repr__(self):
        return str(self)

    def _create_expression(self, argument, operator_symbol, is_reversed):
        return transform(self, argument, operator_symbol, is_reversed)


class Operator:
    def __init__(self, name, func):
        self.name = name
        self.func = func

    def evaluate(self, left_arg, right_arg):
        return self.func(left_arg, right_arg)

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

    def __repr__(self):
        return str(self)


class Expression(Operand):
    def __init__(self, first, second, third):
        self.left = first
        self.right = third
        self.function = second

    def evaluate(self, **kwargs):
        left_argument = self.left.evaluate(**kwargs)
        right_argument = self.right.evaluate(**kwargs)
        return self.function.evaluate(left_argument, right_argument)

    @property
    def variable_names(self):
        left_variables = self.variables(self.left)
        right_variables = self.variables(self.right)
        return left_variables.union(right_variables)

    def variables(self, operand):
        if type(operand) == Expression:
            return operand.variable_names
        elif type(operand) == Variable:
            return {operand.name}
        return set()

    def __str__(self):
        return "({} {} {})".format(self.left, self.function, self.right)

    def __repr__(self):
        return str(self)

    def _create_expression(self, argument, operator_symbol, is_reversed):
        return transform(self, argument, operator_symbol, is_reversed)


def transform(operand, argument, operator_symbol, is_reversed):
    if isinstance(argument, numbers.Number):
        argument = create_constant(argument)
    elif isinstance(argument, str):
        argument = create_variable(argument)

    function = CREATED_OPERATORS[operator_symbol]
    if is_reversed:
        return create_expression((argument, function, operand))
    return create_expression((operand, function, argument))


CREATED_OPERATORS = {'+': Operator('+', operator.add),
                     '-': Operator('-', operator.sub),
                     '*': Operator('*', operator.mul),
                     '/': Operator('/', operator.truediv),
                     '//': Operator('//', operator.floordiv),
                     '%': Operator('%', operator.mod),
                     '**': Operator('**', operator.pow),
                     '<<': Operator('<<', operator.lshift),
                     '>>': Operator('>>', operator.rshift),
                     '&': Operator('&', operator.and_),
                     '^': Operator('^', operator.xor),
                     '|': Operator('|', operator.or_)}


def generate(name, func):
    if name not in CREATED_OPERATORS:
        CREATED_OPERATORS[name] = Operator(name, func)
    return CREATED_OPERATORS[name]


def create_constant(value):
    return Constant(value)


def create_variable(name):
    return Variable(name)


def create_operator(name, func):
    return generate(name, func)


def parse(argument):
    if isinstance(argument, collections.Iterable):
        return create_expression(argument)
    return argument


def create_expression(args):
    return Expression(*map(parse, args))

Александър обнови решението на 20.03.2016 18:17 (преди над 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
import operator
import numbers
import collections


class Operand:
    def __add__(self, arg):
        return self._create_expression(arg, '+', is_reversed=False)

    def __sub__(self, arg):
        return self._create_expression(arg, '-', is_reversed=False)

    def __mul__(self, arg):
        return self._create_expression(arg, '*', is_reversed=False)

    def __truediv__(self, arg):
        return self._create_expression(arg, '/', is_reversed=False)

    def __floordiv__(self, arg):
        return self._create_expression(arg, '//', is_reversed=False)

    def __mod__(self, arg):
        return self._create_expression(arg, '%', is_reversed=False)

    def __divmod__(self, arg):
        return self._create_expression(arg, 'divmod', is_reversed=False)

    def __pow__(self, arg):
        return self._create_expression(arg, '**', is_reversed=False)

    def __lshift__(self, arg):
        return self._create_expression(arg, '<<', is_reversed=False)

    def __rshift__(self, arg):
        return self._create_expression(arg, '>>', is_reversed=False)

    def __and__(self, arg):
        return self._create_expression(arg, '&', is_reversed=False)

    def __xor__(self, arg):
        return self._create_expression(arg, '^', is_reversed=False)

    def __or__(self, arg):
        return self._create_expression(arg, '|', is_reversed=False)

    def __radd__(self, arg):
        return self._create_expression(arg, '+', is_reversed=True)

    def __rsub__(self, arg):
        return self._create_expression(arg, '-', is_reversed=True)

    def __rmul__(self, arg):
        return self._create_expression(arg, '*', is_reversed=True)

    def __rtruediv__(self, arg):
        return self._create_expression(arg, '/', is_reversed=True)

    def __rfloordiv__(self, arg):
        return self._create_expression(arg, '//', is_reversed=True)

    def __rmod__(self, arg):
        return self._create_expression(arg, '%', is_reversed=True)

    def __rdivmod__(self, arg):
        return self._create_expression(arg, 'divmod', is_reversed=True)

    def __rpow__(self, arg):
        return self._create_expression(arg, '**', is_reversed=True)

    def __rlshift__(self, arg):
        return self._create_expression(arg, '<<', is_reversed=True)

    def __rrshift__(self, arg):
        return self._create_expression(arg, '>>', is_reversed=True)

    def __rand__(self, arg):
        return self._create_expression(arg, '&', is_reversed=True)

    def __rxor__(self, arg):
        return self._create_expression(arg, '^', is_reversed=True)

    def __ror__(self, arg):
        return self._create_expression(arg, '|', is_reversed=True)

    def _create_expression(self, argument, operator_symbol, is_reversed):
        pass


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

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

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

    def __repr__(self):
        return str(self)

    def _create_expression(self, argument, operator_symbol, is_reversed):
        return transform(self, argument, operator_symbol, is_reversed)


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

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

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

    def __repr__(self):
        return str(self)

    def _create_expression(self, argument, operator_symbol, is_reversed):
        return transform(self, argument, operator_symbol, is_reversed)


class Operator:
    def __init__(self, name, func):
        self.name = name
        self.func = func

    def evaluate(self, left_arg, right_arg):
        return self.func(left_arg, right_arg)

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

    def __repr__(self):
        return str(self)


class Expression(Operand):
    def __init__(self, first, second, third):
        self.left = first
        self.right = third
        self.function = second

    def evaluate(self, **kwargs):
        left_argument = self.left.evaluate(**kwargs)
        right_argument = self.right.evaluate(**kwargs)
        return self.function.evaluate(left_argument, right_argument)

    @property
    def variable_names(self):
        left_variables = self.variables(self.left)
        right_variables = self.variables(self.right)
        return left_variables.union(right_variables)

    def variables(self, operand):
        if type(operand) == Expression:
            return operand.variable_names
        elif type(operand) == Variable:
            return {operand.name}
        return set()

    def __str__(self):
        return "({} {} {})".format(self.left, self.function, self.right)

    def __repr__(self):
        return str(self)

    def _create_expression(self, argument, operator_symbol, is_reversed):
        return transform(self, argument, operator_symbol, is_reversed)


def transform(operand, argument, operator_symbol, is_reversed):
    if isinstance(argument, numbers.Number):
        argument = create_constant(argument)
    elif isinstance(argument, str):
        argument = create_variable(argument)

    function = CREATED_OPERATORS[operator_symbol]
    if is_reversed:
        return create_expression((argument, function, operand))
    return create_expression((operand, function, argument))


CREATED_OPERATORS = {
        '+': Operator('+', operator.add),
        '-': Operator('-', operator.sub),
        '*': Operator('*', operator.mul),
        '/': Operator('/', operator.truediv),
        '//': Operator('//', operator.floordiv),
        '%': Operator('%', operator.mod),
        '**': Operator('**', operator.pow),
        '<<': Operator('<<', operator.lshift),
        '>>': Operator('>>', operator.rshift),
        '&': Operator('&', operator.and_),
        '^': Operator('^', operator.xor),
        '|': Operator('|', operator.or_),
        'divmod': Operator('divmod', divmod)
    }


def generate(name, func):
    if name not in CREATED_OPERATORS:
        CREATED_OPERATORS[name] = Operator(name, func)
    return CREATED_OPERATORS[name]


def create_constant(value):
    return Constant(value)


def create_variable(name):
    return Variable(name)


def create_operator(name, func):
    return generate(name, func)


def parse(argument):
    if isinstance(argument, collections.Iterable):
        return create_expression(argument)
    return argument


def create_expression(args):
    return Expression(*map(parse, args))