timeit

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

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

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

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

Към профила на Йоан Динков

Резултати

  • 9 точки от тестове
  • 2 бонус точки
  • 11 точки общо
  • 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
import collections
import itertools

from functools import wraps
from numbers import Number


def get_function_name(name):
    function_names = {
        '__add__': '+',
        '__radd__': '+',
        '__sub__': '-',
        '__rsub__': '-',
        '__mul__': '*',
        '__rmul__': '*',
        '__truediv__': '/',
        '__rtruediv__': '/',
        '__floordiv__': '//',
        '__rfloordiv__': '//',
        '__mod__': '%',
        '__rmod__': '%',
        '__rdivmod__': 'divmod',
        '__divmod__': 'divmod',
        '__pow__': '**',
        '__rpow__': '**',
        '__lshift__': '<<',
        '__rlshift__': '<<',
        '__rshift__': '>>',
        '__rrshift__': '>>',
        '__and__': '&',
        '__rand__': '&',
        '__or__': '|',
        '__ror__': '|',
        '__xor__': '^',
        '__rxor__': '^'
    }

    if name in function_names:
        return function_names[name]

    return name


def get_value(input):
    if isinstance(input, ArithmeticObject) is False:
        return Constant(input)

    return input


def to_expression(func):
    @wraps(func)
    def wrapper(*args, **kw):
        lhs = get_value(args[0])
        rhs = get_value(args[1])
        operator = Operator(get_function_name(func.__name__), func)

        return Expression((lhs, operator, rhs))

    return wrapper


def decorate_all_functions(function_decorator):
    system_names = ['__new__', '__repr__', '__getattribute__', '__format__',
                    '__str__']

    def decorator(cls):
        for name, obj in vars(int).items():
            if callable(obj) and name not in system_names:
                setattr(cls, name, function_decorator(obj))
        return cls
    return decorator


@decorate_all_functions(to_expression)
class ArithmeticObject(Number):
    def __new__(cls, *args, **kwargs):
        return super(ArithmeticObject, cls).__new__(cls)


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

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

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


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

    def __str__(self):
        return self.name

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


class Expression(ArithmeticObject):
    def __init__(self, operations):
        self.lhs = self.__side(operations[0])
        self.operator = operations[1]
        self.rhs = self.__side(operations[2])
        self.variable_names = self.__variable_names(operations)

    def evaluate(self, **variables):
        lhs = self.lhs.evaluate(**variables)
        rhs = self.rhs.evaluate(**variables)

        return self.operator.function(lhs, rhs)

    def __str__(self):
        return "({0} {1} {2})".format(self.lhs, self.operator, self.rhs)

    def __side(self, input):
        if isinstance(input, collections.Iterable):
            return Expression(input)

        return input

    def __variable_names(self, operations):
        result = []

        for operation in operations:
            if isinstance(operation, Variable):
                result.append(operation.name)

            if isinstance(operation, Expression):
                result.append(operation.variable_names)

        return list(itertools.chain.from_iterable(result))


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

    def __str__(self):
        return self.name

    def __repr__(self):
        return self.name


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)

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

.E..F..............
======================================================================
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'

======================================================================
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.163s

FAILED (failures=1, errors=1)

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

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


class Object:
    def __radd__(self, other):
        operator = create_operator('+', lambda lhs, rhs: lhs + rhs)
        return self.__create_expression(self, operator, other)

    def __rsub__(self, other):
        operator = create_operator('-', lambda lhs, rhs: lhs - rhs)
        return self.__create_expression(self, operator, other)

    def __rmul__(self, other):
        operator = create_operator('*', lambda lhs, rhs: lhs * rhs)
        return self.__create_expression(self, operator, other)

    def __rtruediv__(self, other):
        operator = create_operator('/', lambda lhs, rhs: lhs / rhs)
        return self.__create_expression(self, operator, other)

    def __rfloordiv__(self, other):
        operator = create_operator('//', lambda lhs, rhs: lhs // rhs)
        return self.__create_expression(self, operator, other)

    def __rmod__(self, other):
        operator = create_operator('%', lambda lhs, rhs: lhs % rhs)
        return self.__create_expression(self, operator, other)

    def __rdivmod__(self, other):
        operator = create_operator('<<', lambda lhs, rhs: divmod(lhs << rhs))
        return self.__create_expression(self, operator, other)

    def __rpow__(self, other):
        operator = create_operator('<<', lambda lhs, rhs: pow(lhs << rhs))
        return self.__create_expression(self, operator, other)

    def __rlshift__(self, other):
        operator = create_operator('<<', lambda lhs, rhs: lhs << rhs)
        return self.__create_expression(self, operator, other)

    def __rrshift__(self, other):
        operator = create_operator('>>', lambda lhs, rhs: lhs >> rhs)
        return self.__create_expression(self, operator, other)

    def __rand__(self, other):
        operator = create_operator('&', lambda lhs, rhs: lhs & rhs)
        return self.__create_expression(self, operator, other)

    def __rxor__(self, other):
        operator = create_operator('^', lambda lhs, rhs: lhs ^ rhs)
        return self.__create_expression(self, operator, other)

    def __ror__(self, other):
        operator = create_operator('|', lambda lhs, rhs: lhs | rhs)
        return self.__create_expression(self, operator, other)

    def __add__(self, other):
        operator = create_operator('+', lambda lhs, rhs: lhs + rhs)
        return self.__create_expression(self, operator, other)

    def __sub__(self, other):
        operator = create_operator('-', lambda lhs, rhs: lhs - rhs)
        return self.__create_expression(self, operator, other)

    def __mul__(self, other):
        operator = create_operator('*', lambda lhs, rhs: lhs * rhs)
        return self.__create_expression(self, operator, other)

    def __truediv__(self, other):
        operator = create_operator('/', lambda lhs, rhs: lhs / rhs)
        return self.__create_expression(self, operator, other)

    def __floordiv__(self, other):
        operator = create_operator('//', lambda lhs, rhs: lhs // rhs)
        return self.__create_expression(self, operator, other)

    def __mod__(self, other):
        operator = create_operator('%', lambda lhs, rhs: lhs % rhs)
        return self.__create_expression(self, operator, other)

    def __divmod__(self, other):
        operator = create_operator('<<', lambda lhs, rhs: divmod(lhs << rhs))
        return self.__create_expression(self, operator, other)

    def __pow__(self, other):
        operator = create_operator('<<', lambda lhs, rhs: pow(lhs << rhs))
        return self.__create_expression(self, operator, other)

    def __lshift__(self, other):
        operator = create_operator('<<', lambda lhs, rhs: lhs << rhs)
        return self.__create_expression(self, operator, other)

    def __rshift__(self, other):
        operator = create_operator('>>', lambda lhs, rhs: lhs >> rhs)
        return self.__create_expression(self, operator, other)

    def __and__(self, other):
        operator = create_operator('&', lambda lhs, rhs: lhs & rhs)
        return self.__create_expression(self, operator, other)

    def __xor__(self, other):
        operator = create_operator('^', lambda lhs, rhs: lhs ^ rhs)
        return self.__create_expression(self, operator, other)

    def __or__(self, other):
        operator = create_operator('|', lambda lhs, rhs: lhs | rhs)
        return self.__create_expression(self, operator, other)

    def __create_expression(self, lhs, operator, rhs):
        if isinstance(lhs, (int, float, complex)):
            lhs = Constant(lhs)

        if isinstance(rhs, (int, float, complex)):
            rhs = Constant(rhs)

        return Expression((lhs, operator, rhs))


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

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

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


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

    def __str__(self):
        return self.name

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


class Expression(Object):
    def __init__(self, operations):
        self.lhs = self.__side(operations[0])
        self.operator = operations[1]
        self.rhs = self.__side(operations[2])
        self.variable_names = self.__variable_names(operations)

    def evaluate(self, **variables):
        lhs = self.lhs.evaluate(**variables)
        rhs = self.rhs.evaluate(**variables)

        return self.operator.invoke(lhs, rhs)

    def __str__(self):
        return "({0} {1} {2})".format(self.lhs, self.operator, self.rhs)

    def __side(self, input):
        if isinstance(input, collections.Iterable):
            return Expression(input)

        return input

    def __variable_names(self, operations):
        return [str(x) for x in operations if isinstance(x, Variable)]


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

    def __str__(self):
        return self.name

    def invoke(self, lhs, rhs):
        return self.function(lhs, rhs)


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)

Йоан обнови решението на 20.03.2016 19: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
import collections


class Object:
    def __radd__(self, other):
        operator = create_operator('+', lambda lhs, rhs: lhs + rhs)
        return self.__create_expression(self, operator, other)

    def __rsub__(self, other):
        operator = create_operator('-', lambda lhs, rhs: lhs - rhs)
        return self.__create_expression(self, operator, other)

    def __rmul__(self, other):
        operator = create_operator('*', lambda lhs, rhs: lhs * rhs)
        return self.__create_expression(self, operator, other)

    def __rtruediv__(self, other):
        operator = create_operator('/', lambda lhs, rhs: lhs / rhs)
        return self.__create_expression(self, operator, other)

    def __rfloordiv__(self, other):
        operator = create_operator('//', lambda lhs, rhs: lhs // rhs)
        return self.__create_expression(self, operator, other)

    def __rmod__(self, other):
        operator = create_operator('%', lambda lhs, rhs: lhs % rhs)
        return self.__create_expression(self, operator, other)

    def __rdivmod__(self, other):
        operator = create_operator('divmod',
                                   lambda lhs, rhs: divmod(lhs << rhs))
        return self.__create_expression(self, operator, other)

    def __rpow__(self, other):
        operator = create_operator('pow', lambda lhs, rhs: pow(lhs << rhs))
        return self.__create_expression(self, operator, other)

    def __rlshift__(self, other):
        operator = create_operator('<<', lambda lhs, rhs: lhs << rhs)
        return self.__create_expression(self, operator, other)

    def __rrshift__(self, other):
        operator = create_operator('>>', lambda lhs, rhs: lhs >> rhs)
        return self.__create_expression(self, operator, other)

    def __rand__(self, other):
        operator = create_operator('&', lambda lhs, rhs: lhs & rhs)
        return self.__create_expression(self, operator, other)

    def __rxor__(self, other):
        operator = create_operator('^', lambda lhs, rhs: lhs ^ rhs)
        return self.__create_expression(self, operator, other)

    def __ror__(self, other):
        operator = create_operator('|', lambda lhs, rhs: lhs | rhs)
        return self.__create_expression(self, operator, other)

    def __add__(self, other):
        operator = create_operator('+', lambda lhs, rhs: lhs + rhs)
        return self.__create_expression(self, operator, other)

    def __sub__(self, other):
        operator = create_operator('-', lambda lhs, rhs: lhs - rhs)
        return self.__create_expression(self, operator, other)

    def __mul__(self, other):
        operator = create_operator('*', lambda lhs, rhs: lhs * rhs)
        return self.__create_expression(self, operator, other)

    def __truediv__(self, other):
        operator = create_operator('/', lambda lhs, rhs: lhs / rhs)
        return self.__create_expression(self, operator, other)

    def __floordiv__(self, other):
        operator = create_operator('//', lambda lhs, rhs: lhs // rhs)
        return self.__create_expression(self, operator, other)

    def __mod__(self, other):
        operator = create_operator('%', lambda lhs, rhs: lhs % rhs)
        return self.__create_expression(self, operator, other)

    def __divmod__(self, other):
        operator = create_operator('divmod',
                                   lambda lhs, rhs: divmod(lhs << rhs))
        return self.__create_expression(self, operator, other)

    def __pow__(self, other):
        operator = create_operator('**', lambda lhs, rhs: pow(lhs << rhs))
        return self.__create_expression(self, operator, other)

    def __lshift__(self, other):
        operator = create_operator('<<', lambda lhs, rhs: lhs << rhs)
        return self.__create_expression(self, operator, other)

    def __rshift__(self, other):
        operator = create_operator('>>', lambda lhs, rhs: lhs >> rhs)
        return self.__create_expression(self, operator, other)

    def __and__(self, other):
        operator = create_operator('&', lambda lhs, rhs: lhs & rhs)
        return self.__create_expression(self, operator, other)

    def __xor__(self, other):
        operator = create_operator('^', lambda lhs, rhs: lhs ^ rhs)
        return self.__create_expression(self, operator, other)

    def __or__(self, other):
        operator = create_operator('|', lambda lhs, rhs: lhs | rhs)
        return self.__create_expression(self, operator, other)

    def __create_expression(self, lhs, operator, rhs):
        if isinstance(lhs, (int, float, complex)):
            lhs = Constant(lhs)

        if isinstance(rhs, (int, float, complex)):
            rhs = Constant(rhs)

        return Expression((lhs, operator, rhs))


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

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

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


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

    def __str__(self):
        return self.name

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


class Expression(Object):
    def __init__(self, operations):
        self.lhs = self.__side(operations[0])
        self.operator = operations[1]
        self.rhs = self.__side(operations[2])
        self.variable_names = self.__variable_names(operations)

    def evaluate(self, **variables):
        lhs = self.lhs.evaluate(**variables)
        rhs = self.rhs.evaluate(**variables)

        return self.operator.invoke(lhs, rhs)

    def __str__(self):
        return "({0} {1} {2})".format(self.lhs, self.operator, self.rhs)

    def __side(self, input):
        if isinstance(input, collections.Iterable):
            return Expression(input)

        return input

    def __variable_names(self, operations):
        return [str(x) for x in operations if isinstance(x, Variable)]


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

    def __str__(self):
        return self.name

    def invoke(self, lhs, rhs):
        return self.function(lhs, rhs)


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)

Йоан обнови решението на 20.03.2016 23:31 (преди над 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
import collections
import itertools

from functools import wraps
from numbers import Number


def get_function_name(name):
    function_names = {
        '__add__': '+',
        '__radd__': '+',
        '__sub__': '-',
        '__rsub__': '-',
        '__mul__': '*',
        '__rmul__': '*',
        '__truediv__': '/',
        '__rtruediv__': '/',
        '__floordiv__': '//',
        '__rfloordiv__': '//',
        '__mod__': '%',
        '__rmod__': '%',
        '__rdivmod__': 'divmod',
        '__divmod__': 'divmod',
        '__pow__': '**',
        '__rpow__': '**',
        '__lshift__': '<<',
        '__rlshift__': '<<',
        '__rshift__': '>>',
        '__rrshift__': '>>',
        '__and__': '&',
        '__rand__': '&',
        '__or__': '|',
        '__ror__': '|',
        '__xor__': '^',
        '__rxor__': '^'
    }

    if name in function_names:
        return function_names[name]

    return name


def get_value(input):
    if isinstance(input, ArithmeticObject) is False:
        return Constant(input)

    return input


def to_expression(func):
    @wraps(func)
    def wrapper(*args, **kw):
        lhs = get_value(args[0])
        rhs = get_value(args[1])
        operator = Operator(get_function_name(func.__name__), func)

        return Expression((lhs, operator, rhs))

    return wrapper


def decorate_all_functions(function_decorator):
    system_names = ['__new__', '__repr__', '__getattribute__', '__format__',
                    '__str__']

    def decorator(cls):
        for name, obj in vars(int).items():
            if callable(obj) and name not in system_names:
                setattr(cls, name, function_decorator(obj))
        return cls
    return decorator


@decorate_all_functions(to_expression)
class ArithmeticObject(Number):
    def __new__(cls, *args, **kwargs):
        return super(ArithmeticObject, cls).__new__(cls)


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

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

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


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

    def __str__(self):
        return self.name

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


class Expression(ArithmeticObject):
    def __init__(self, operations):
        self.lhs = self.__side(operations[0])
        self.operator = operations[1]
        self.rhs = self.__side(operations[2])
        self.variable_names = self.__variable_names(operations)

    def evaluate(self, **variables):
        lhs = self.lhs.evaluate(**variables)
        rhs = self.rhs.evaluate(**variables)

        return self.operator.function(lhs, rhs)

    def __str__(self):
        return "({0} {1} {2})".format(self.lhs, self.operator, self.rhs)

    def __side(self, input):
        if isinstance(input, collections.Iterable):
            return Expression(input)

        return input

    def __variable_names(self, operations):
        result = []

        for operation in operations:
            if isinstance(operation, Variable):
                result.append(operation.name)

            if isinstance(operation, Expression):
                result.append(operation.variable_names)

        return list(itertools.chain.from_iterable(result))


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

    def __str__(self):
        return self.name

    def __repr__(self):
        return self.name


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)