timeit

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

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

Решение на Аритметични изрази от Даниел Делчев

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

Към профила на Даниел Делчев

Резултати

  • 10 точки от тестове
  • 0 бонус точки
  • 10 точки общо
  • 19 успешни тест(а)
  • 0 неуспешни тест(а)

Код

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


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

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

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

    def evaluate(self, *args, **kwargs):
        return self.function


plus = Operator('+', lambda a, b: a+b)
minus = Operator('-', lambda a, b: a-b)
times = Operator('*', lambda a, b: b*a)
exp = Operator('**', lambda a, b: a**b)
truediv = Operator('/', lambda a, b: a/b)
floordiv = Operator('//', lambda a, b: a//b)
mod_div = Operator('%', lambda a, b: a % b)
leftshift = Operator('<<', lambda a, b: int(a) << int(b))
rightshift = Operator('>>', lambda a, b: int(a) >> int(b))
binary_and = Operator('&', lambda a, b: int(a) & int(b))
binary_or = Operator('|', lambda a, b: int(a) | int(b))
binary_xor = Operator('^', lambda a, b: int(a) ^ int(b))


class Arithmetic:
    def __add__(self, other):
        return Expression((self, plus, other))

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

    def __sub__(self, other):
        return Expression((self, minus, other))

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

    def __mul__(self, other):
        return Expression((self, times, other))

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

    def __pow__(self, other):
        return Expression((self, exp, other))

    def __rpow__(self, other):
        return Expression((other, exp, self))

    def __truediv__(self, other):
        return Expression((self, truediv, other))

    def __rtruediv__(self, other):
        return Expression((other, truediv, self))

    def __floordiv__(self, other):
        return Expression((self, floordiv, other))

    def __rfloordiv__(self, other):
        return Expression((other, truediv, self))

    def __mod__(self, other):
        return Expression((self, mod_div, other))

    def __rmod__(self, other):
        return Expression((other, mod_div, self))

    def __lshift__(self, other):
        return Expression((self, leftshift, other))

    def __rshift__(self, other):
        return Expression((self, rightshift, other))

    def __and__(self, other):
        return Expression((self, binary_and, other))

    def __xor__(self, other):
        return Expression((self, binary_xor, other))

    def __or__(self, other):
        return Expression((self, binary_or, other))

    def __rlshift__(self, other):
        return Expression((other, leftshift, self))

    def __rrshift__(self, other):
        return Expression((other, rightshift, self))

    def __rand__(self, other):
        return Expression((other, binary_and, self))

    def __rxor__(self, other):
        return Expression((other, binary_xor, self))

    def __ror__(self, other):
        return Expression((other, binary_or, self))


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

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

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

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


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

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

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

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


class Expression(Arithmetic):
    def gather_variables(self, storage):
        one = self.representation[0]
        two = self.representation[2]
        if isinstance(one, Variable):
            storage.append(one.name)
        elif isinstance(one, Expression):
            one.gather_variables(storage)
        elif not (isinstance(one, (numbers.Number, Constant))):
            Expression(one).gather_variables(storage)
        if isinstance(two, Variable):
            storage.append(two.name)
        elif isinstance(two, Expression):
            two.gather_variables(storage)
        elif not (isinstance(two, (numbers.Number, Constant))):
            Expression(two).gather_variables(storage)

    def __init__(self, inception):
        self.representation = inception
        storage = []
        self.gather_variables(storage)
        self.variable_names = tuple(storage)

    def __str__(self):
        raw = str(self.representation)
        raw = raw.translate({ord(','): None, ord('['): '(', ord(']'): ')'})
        return raw

    def __repr__(self):
        raw = str(self.representation)
        raw = raw.translate({ord(','): None, ord('['): '(', ord(']'): ')'})
        return raw

    def evaluate(self, *args, **kwargs):
        one = self.representation[0]
        operation = self.representation[1].evaluate()
        two = self.representation[2]
        if isinstance(one, (Constant, Variable, Expression)):
            one = one.evaluate(*args, **kwargs)
        elif not (isinstance(one, numbers.Number)):
            one = Expression(one).evaluate(*args, **kwargs)
        if isinstance(two, (Constant, Variable, Expression)):
            two = two.evaluate(*args, **kwargs)
        elif not (isinstance(two, numbers.Number)):
            two = Expression(two).evaluate(*args, **kwargs)
        return operation(one, two)


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)

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

...................
----------------------------------------------------------------------
Ran 19 tests in 0.135s

OK

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

Даниел обнови решението на 19.03.2016 14:23 (преди над 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
class Operator:
    def __init__(self, sign, function):
        self.sign = sign
        self.function = function

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

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

    def evaluate(self, *args, **kwargs):
        return self.function


plus = Operator('+', lambda a, b: a+b)
minus = Operator('-', lambda a, b: a-b)
times = Operator('*', lambda a, b: b*a)
exp = Operator('**', lambda a, b: a**b)
truediv = Operator('/', lambda a, b: a/b)
floordiv = Operator('//', lambda a, b: a//b)
mod_div = Operator('%', lambda a, b: a % b)


class Arithmetic:
    def __init__(self): pass

    def __add__(self, other):
        return Expression((self, plus, other))

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

    def __sub__(self, other):
        return Expression((self, minus, other))

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

    def __mul__(self, other):
        return Expression((self, times, other))

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

    def __pow__(self, other):
        return Expression((self, exp, other))

    def __rpow__(self, other):
        return Expression((other, exp, self))

    def __truediv__(self, other):
        return Expression((self, truediv, other))

    def __rtruediv__(self, other):
        return Expression((other, truediv, self))

    def __floordiv__(self, other):
        return Expression((self, floordiv, other))

    def __rfloordiv__(self, other):
        return Expression((other, truediv, self))

    def __mod__(self, other):
        return Expression((self, mod_div, other))

    def __rmod__(self, other):
        return Expression((other, mod_div, self))


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

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

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

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


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

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

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

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


class Expression(Arithmetic):
    def gather_variables(self, storage):
        one = self.representation[0]
        two = self.representation[2]
        if isinstance(one, Variable):
            storage.append(one.name)
        elif isinstance(one, (tuple, range, list)):
            one = Expression(one)
            one.gather_variables(storage)
        elif isinstance(one, Expression):
            one.gather_variables(storage)
        if isinstance(two, Variable):
            storage.append(two.name)
        elif isinstance(two, (tuple, range, list)):
            two = Expression(two)
            two.gather_variables(storage)
        elif isinstance(two, Expression):
            two.gather_variables(storage)

    def __init__(self, inception):
        Arithmetic.__init__(self)
        self.representation = inception
        storage = []
        self.gather_variables(storage)
        self.variable_names = tuple(storage)

    def __str__(self):
        raw = str(self.representation)
        raw = raw.translate({ord(','): None, ord('['): '(', ord(']'): ')'})
        return raw

    def __repr__(self):
        raw = str(self.representation)
        raw = raw.translate({ord(','): None, ord('['): '(', ord(']'): ')'})
        return raw

    def evaluate(self, *args, **kwargs):
        one = self.representation[0]
        operation = self.representation[1].evaluate()
        two = self.representation[2]
        if isinstance(one, (Constant, Variable, Expression)):
            one = one.evaluate(*args, **kwargs)
        if isinstance(one, (tuple, range, list)):
            one = Expression(one)
            one = one.evaluate(*args, **kwargs)
        if isinstance(two, (Constant, Variable, Expression)):
            two = two.evaluate(*args, **kwargs)
        if isinstance(two, (tuple, range, list)):
            two = Expression(two)
            two = two.evaluate(*args, **kwargs)
        return operation(one, two)


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)
  • Няма нужда да дефинираш празен __init__ и да го извикваш в наследниците. Просто го махни :)
  • Имплментациите на Expression.gather_variables и Expression.evaluate са твърде сложни. Опрости ги малко.
  • Всички стандартни колекции в езика наследяват от collections.Iterable.

Даниел обнови решението на 20.03.2016 01:07 (преди над 1 година)

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


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

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

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

    def evaluate(self, *args, **kwargs):
        return self.function


plus = Operator('+', lambda a, b: a+b)
minus = Operator('-', lambda a, b: a-b)
times = Operator('*', lambda a, b: b*a)
exp = Operator('**', lambda a, b: a**b)
truediv = Operator('/', lambda a, b: a/b)
floordiv = Operator('//', lambda a, b: a//b)
mod_div = Operator('%', lambda a, b: a % b)
leftshift = Operator('<<', lambda a, b: int(a) << int(b))
rightshift = Operator('>>', lambda a, b: int(a) >> int(b))
binary_and = Operator('&', lambda a, b: int(a) & int(b))
binary_or = Operator('|', lambda a, b: int(a) | int(b))
binary_xor = Operator('^', lambda a, b: int(a) ^ int(b))


class Arithmetic:
    def __add__(self, other):
        return Expression((self, plus, other))

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

    def __sub__(self, other):
        return Expression((self, minus, other))

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

    def __mul__(self, other):
        return Expression((self, times, other))

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

    def __pow__(self, other):
        return Expression((self, exp, other))

    def __rpow__(self, other):
        return Expression((other, exp, self))

    def __truediv__(self, other):
        return Expression((self, truediv, other))

    def __rtruediv__(self, other):
        return Expression((other, truediv, self))

    def __floordiv__(self, other):
        return Expression((self, floordiv, other))

    def __rfloordiv__(self, other):
        return Expression((other, truediv, self))

    def __mod__(self, other):
        return Expression((self, mod_div, other))

    def __rmod__(self, other):
        return Expression((other, mod_div, self))

    def __lshift__(self, other):
        return Expression((self, leftshift, other))

    def __rshift__(self, other):
        return Expression((self, rightshift, other))

    def __and__(self, other):
        return Expression((self, binary_and, other))

    def __xor__(self, other):
        return Expression((self, binary_xor, other))

    def __or__(self, other):
        return Expression((self, binary_or, other))

    def __rlshift__(self, other):
        return Expression((other, leftshift, self))

    def __rrshift__(self, other):
        return Expression((other, rightshift, self))

    def __rand__(self, other):
        return Expression((other, binary_and, self))

    def __rxor__(self, other):
        return Expression((other, binary_xor, self))

    def __ror__(self, other):
        return Expression((other, binary_or, self))


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

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

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

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


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

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

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

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


class Expression(Arithmetic):
    def gather_variables(self, storage):
        one = self.representation[0]
        two = self.representation[2]
        if isinstance(one, Variable):
            storage.append(one.name)
        elif isinstance(one, Expression):
            one.gather_variables(storage)
        elif not (isinstance(one, (numbers.Number, Constant))):
            Expression(one).gather_variables(storage)
        if isinstance(two, Variable):
            storage.append(two.name)
        elif isinstance(two, Expression):
            two.gather_variables(storage)
        elif not (isinstance(two, (numbers.Number, Constant))):
            Expression(two).gather_variables(storage)

    def __init__(self, inception):
        self.representation = inception
        storage = []
        self.gather_variables(storage)
        self.variable_names = tuple(storage)

    def __str__(self):
        raw = str(self.representation)
        raw = raw.translate({ord(','): None, ord('['): '(', ord(']'): ')'})
        return raw

    def __repr__(self):
        raw = str(self.representation)
        raw = raw.translate({ord(','): None, ord('['): '(', ord(']'): ')'})
        return raw

    def evaluate(self, *args, **kwargs):
        one = self.representation[0]
        operation = self.representation[1].evaluate()
        two = self.representation[2]
        if isinstance(one, (Constant, Variable, Expression)):
            one = one.evaluate(*args, **kwargs)
        elif not (isinstance(one, numbers.Number)):
            one = Expression(one).evaluate(*args, **kwargs)
        if isinstance(two, (Constant, Variable, Expression)):
            two = two.evaluate(*args, **kwargs)
        elif not (isinstance(two, numbers.Number)):
            two = Expression(two).evaluate(*args, **kwargs)
        return operation(one, two)


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)