timeit

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

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

Решение на Аритметични изрази от Петър Иванов

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

Към профила на Петър Иванов

Резултати

  • 9 точки от тестове
  • 1 отнета точка
  • 8 точки общо
  • 18 успешни тест(а)
  • 1 неуспешни тест(а)

Код

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


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(structure):
    return Expression(structure)


class Entity:
    OPERATORS = {
        '+': lambda lhs, rhs: lhs + rhs,
        '-': lambda lhs, rhs: lhs - rhs,
        '*': lambda lhs, rhs: lhs * rhs,
        '/': lambda lhs, rhs: lhs / rhs,
        '//': lambda lhs, rhs: lhs // rhs,
        '%': lambda lhs, rhs: lhs % rhs,
    }

    def __add__(self, other):
        exp_structure = (self, Operator('+', Entity.OPERATORS['+']), other)
        return Expression(exp_structure)

    def __radd__(self, other):
        exp_structure = (other, Operator('+', Entity.OPERATORS['+']), self)
        return Expression(exp_structure)

    def __sub__(self, other):
        exp_structure = (self, Operator('-', Entity.OPERATORS['-']), other)
        return Expression(exp_structure)

    def __rsub__(self, other):
        exp_structure = (other, Operator('-', Entity.OPERATORS['-']), self)
        return Expression(exp_structure)

    def __mul__(self, other):
        exp_structure = (self, Operator('*', Entity.OPERATORS['*']), other)
        return Expression(exp_structure)

    def __rmul__(self, other):
        exp_structure = (other, Operator('*', Entity.OPERATORS['*']), self)
        return Expression(exp_structure)

    def __truediv__(self, other):
        exp_structure = (self, Operator('/', Entity.OPERATORS['/']), other)
        return Expression(exp_structure)

    def __rtruediv__(self, other):
        exp_structure = (other, Operator('/', Entity.OPERATORS['/']), self)
        return Expression(exp_structure)

    def __floordiv__(self, other):
        exp_structure = (self, Operator('//', Entity.OPERATORS['//']), other)
        return Expression(exp_structure)

    def __rfloordiv__(self, other):
        exp_structure = (other, Operator('//', Entity.OPERATORS['//']), self)
        return Expression(exp_structure)

    def __mod__(self, other):
        exp_structure = (self, Operator('%', Entity.OPERATORS['%']), other)
        return Expression(exp_structure)

    def __rmod__(self, other):
        exp_structure = (other, Operator('%', Entity.OPERATORS['%']), self)
        return Expression(exp_structure)


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

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

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

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


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

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

    @property
    def name(self):
        return self._name

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


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

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


class Expression(Entity):
    def __init__(self, structure):
        self._structure = structure

    def __str__(self):
        expression = Expression.flatten_string(self._structure)
        stack = '('
        for item in expression:
            stack += item
        stack += ')'
        return str(stack)

    def __iter__(self):
        return iter(self._structure)

    @staticmethod
    def flatten(structure):
        for item in structure:
            if isinstance(item, Iterable):
                for sub in Expression.flatten(item):
                    yield sub
            elif isinstance(item, Expression):
                Expression.flatten(item.structure)
            else:
                yield item

    @property
    def structure(self):
        return self._structure

    @staticmethod
    def flatten_string(structure):
        for item in structure:
            if isinstance(item, Iterable):
                yield '('
                for sub in Expression.flatten_string(item):
                    yield str(sub)
                yield ')'
            elif isinstance(item, Expression):
                Expression.flatten(item.structure)
            else:
                if isinstance(item, Operator):
                    yield ' '
                    yield str(item)
                    yield ' '
                else:
                    yield str(item)

    def evaluate(self, **variables):
        stack = str(self)
        for i in stack:
            if i in variables:
                stack = stack.replace(i, str(variables[i]))
        return eval(stack)

    @property
    def variable_names(self):
        expression = Expression.flatten(self._structure)
        variables = set()
        for item in expression:
            if isinstance(item, Variable):
                variables.add(item.name)
        return tuple(variables)

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

................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'

----------------------------------------------------------------------
Ran 19 tests in 0.158s

FAILED (errors=1)

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

Петър обнови решението на 20.03.2016 15:16 (преди над 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
from collections import Iterable


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(structure):
    return Expression(structure)


class Entity:
    OPERATORS = {
        '+': lambda lhs, rhs: lhs + rhs,
        '-': lambda lhs, rhs: lhs - rhs,
        '*': lambda lhs, rhs: lhs * rhs,
        '/': lambda lhs, rhs: lhs / rhs,
        '//': lambda lhs, rhs: lhs // rhs,
        '%': lambda lhs, rhs: lhs % rhs,
    }

    def __add__(self, other):
        exp_structure = (self, Operator('+', Entity.OPERATORS['+']), other)
        return Expression(exp_structure)

    def __radd__(self, other):
        exp_structure = (other, Operator('+', Entity.OPERATORS['+']), self)
        return Expression(exp_structure)

    def __sub__(self, other):
        exp_structure = (self, Operator('-', Entity.OPERATORS['-']), other)
        return Expression(exp_structure)

    def __rsub__(self, other):
        exp_structure = (other, Operator('-', Entity.OPERATORS['-']), self)
        return Expression(exp_structure)

    def __mul__(self, other):
        exp_structure = (self, Operator('*', Entity.OPERATORS['*']), other)
        return Expression(exp_structure)

    def __rmul__(self, other):
        exp_structure = (other, Operator('*', Entity.OPERATORS['*']), self)
        return Expression(exp_structure)

    def __truediv__(self, other):
        exp_structure = (self, Operator('/', Entity.OPERATORS['/']), other)
        return Expression(exp_structure)

    def __rtruediv__(self, other):
        exp_structure = (other, Operator('/', Entity.OPERATORS['/']), self)
        return Expression(exp_structure)

    def __floordiv__(self, other):
        exp_structure = (self, Operator('//', Entity.OPERATORS['//']), other)
        return Expression(exp_structure)

    def __rfloordiv__(self, other):
        exp_structure = (other, Operator('//', Entity.OPERATORS['//']), self)
        return Expression(exp_structure)

    def __mod__(self, other):
        exp_structure = (self, Operator('%', Entity.OPERATORS['%']), other)
        return Expression(exp_structure)

    def __rmod__(self, other):
        exp_structure = (other, Operator('%', Entity.OPERATORS['%']), self)
        return Expression(exp_structure)


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

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

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

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


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

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

    @property
    def name(self):
        return self._name

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


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

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


class Expression(Entity):
    def __init__(self, structure):
        self._structure = structure

    def __str__(self):
        expression = Expression.flatten_string(self._structure)
        stack = '('
        for item in expression:
            stack += item
        stack += ')'
        return self.__format_string(stack)

    def __iter__(self):
        return iter(self._structure)

    @staticmethod
    def flatten(structure):
        for item in structure:
            if isinstance(item, Iterable):
                for sub in Expression.flatten(item):
                    yield sub
            elif isinstance(item, Expression):
                Expression.flatten(item.structure)
            else:
                yield item

    @property
    def structure(self):
        return self._structure

    @staticmethod
    def flatten_string(structure):
        for item in structure:
            if isinstance(item, Iterable):
                yield '('
                for sub in Expression.flatten_string(item):
                    yield str(sub)
                yield ')'
            elif isinstance(item, Expression):
                Expression.flatten(item.structure)
            else:
                yield str(item)

    def __format_string(self, text):
        result = ''
        letters = 'zxcvbnmasdfghjklqwertyuiopZXCVBNMASDFGHJKLQWERTYUIOP'
        for elem in text:
            if elem in '()':
                result += elem
            elif elem in '0123456789' or elem in letters:
                result += elem
            elif elem in '+-/*':
                result += ' ' + elem + ' '
            else:
                result += elem
        return result

    def evaluate(self, **variables):
        stack = str(self)
        for i in stack:
            if i in variables:
                stack = stack.replace(i, str(variables[i]))
        return eval(stack)

    @property
    def variable_names(self):
        expression = Expression.flatten(self._structure)
        variables = set()
        for item in expression:
            if isinstance(item, Variable):
                variables.add(item.name)
        return tuple(variables)

Петър обнови решението на 20.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
from collections import Iterable


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(structure):
    return Expression(structure)


class Entity:
    OPERATORS = {
        '+': lambda lhs, rhs: lhs + rhs,
        '-': lambda lhs, rhs: lhs - rhs,
        '*': lambda lhs, rhs: lhs * rhs,
        '/': lambda lhs, rhs: lhs / rhs,
        '//': lambda lhs, rhs: lhs // rhs,
        '%': lambda lhs, rhs: lhs % rhs,
    }

    def __add__(self, other):
        exp_structure = (self, Operator('+', Entity.OPERATORS['+']), other)
        return Expression(exp_structure)

    def __radd__(self, other):
        exp_structure = (other, Operator('+', Entity.OPERATORS['+']), self)
        return Expression(exp_structure)

    def __sub__(self, other):
        exp_structure = (self, Operator('-', Entity.OPERATORS['-']), other)
        return Expression(exp_structure)

    def __rsub__(self, other):
        exp_structure = (other, Operator('-', Entity.OPERATORS['-']), self)
        return Expression(exp_structure)

    def __mul__(self, other):
        exp_structure = (self, Operator('*', Entity.OPERATORS['*']), other)
        return Expression(exp_structure)

    def __rmul__(self, other):
        exp_structure = (other, Operator('*', Entity.OPERATORS['*']), self)
        return Expression(exp_structure)

    def __truediv__(self, other):
        exp_structure = (self, Operator('/', Entity.OPERATORS['/']), other)
        return Expression(exp_structure)

    def __rtruediv__(self, other):
        exp_structure = (other, Operator('/', Entity.OPERATORS['/']), self)
        return Expression(exp_structure)

    def __floordiv__(self, other):
        exp_structure = (self, Operator('//', Entity.OPERATORS['//']), other)
        return Expression(exp_structure)

    def __rfloordiv__(self, other):
        exp_structure = (other, Operator('//', Entity.OPERATORS['//']), self)
        return Expression(exp_structure)

    def __mod__(self, other):
        exp_structure = (self, Operator('%', Entity.OPERATORS['%']), other)
        return Expression(exp_structure)

    def __rmod__(self, other):
        exp_structure = (other, Operator('%', Entity.OPERATORS['%']), self)
        return Expression(exp_structure)


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

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

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

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


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

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

    @property
    def name(self):
        return self._name

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


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

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


class Expression(Entity):
    def __init__(self, structure):
        self._structure = structure

    def __str__(self):
        expression = Expression.flatten_string(self._structure)
        stack = '('
        for item in expression:
            stack += item
        stack += ')'
        return str(stack)

    def __iter__(self):
        return iter(self._structure)

    @staticmethod
    def flatten(structure):
        for item in structure:
            if isinstance(item, Iterable):
                for sub in Expression.flatten(item):
                    yield sub
            elif isinstance(item, Expression):
                Expression.flatten(item.structure)
            else:
                yield item

    @property
    def structure(self):
        return self._structure

    @staticmethod
    def flatten_string(structure):
        for item in structure:
            if isinstance(item, Iterable):
                yield '('
                for sub in Expression.flatten_string(item):
                    yield str(sub)
                yield ')'
            elif isinstance(item, Expression):
                Expression.flatten(item.structure)
            else:
                if isinstance(item, Operator):
                    yield ' '
                    yield str(item)
                    yield ' '
                else:
                    yield str(item)

    def evaluate(self, **variables):
        stack = str(self)
        for i in stack:
            if i in variables:
                stack = stack.replace(i, str(variables[i]))
        return eval(stack)

    @property
    def variable_names(self):
        expression = Expression.flatten(self._structure)
        variables = set()
        for item in expression:
            if isinstance(item, Variable):
                variables.add(item.name)
        return tuple(variables)
  • __str__ може да стане много много по-прост с едно малко "рекурсивно" извикване. Това би обезсмислило flatten* методите ти.
  • Аналогично variable_names може да се реализира доста красиво с рекурсия, което ще доведе и до отпадането на structure.