timeit

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

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

Решение на Аритметични изрази от Мартин Стоев

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

Към профила на Мартин Стоев

Резултати

  • 6 точки от тестове
  • 0 бонус точки
  • 6 точки общо
  • 12 успешни тест(а)
  • 7 неуспешни тест(а)

Код

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


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)


class Arithmetic:
    def __init__(self):
        pass

    def get(self):
        return self.__class__()

    @staticmethod
    def _operation(statemant_1, statemant_2, function):
        if isinstance(statemant_2, numbers.Number):
            return Expression((statemant_1, function, Constant(statemant_2)))
        return Expression((statemant_1, function, statemant_2))

    @staticmethod
    def _roperation(statemant_1, statemant_2, function):
        if isinstance(statemant_2, numbers.Number):
            return Expression((Constant(statemant_2), function, statemant_1))
        return Expression((statemant_2, function, statemant_1))

    def __add__(self, other):
        return Arithmetic._operation(self, other, plus)

    def __radd__(self, other):
        return Arithmetic._roperation(self, other, plus)

    def __sub__(self, other):
        return Arithmetic._operation(self, other, minus)

    def __rsub__(self, other):
        return Arithmetic._roperation(self, other, minus)

    def __mul__(self, other):
        return Arithmetic._operation(self, other, times)

    def __rmul__(self, other):
        return Arithmetic._roperation(self, other, times)

    def __truediv__(self, other):
        return Arithmetic._operation(self, other, divide)

    def __rtruediv__(self, other):
        return Arithmetic._roperation(self, other, divide)


def singleton(cls):
    instances = set()

    def getinstance(symbol, function):
        opr = next((x for x in instances if x.symbol == symbol), None)
        if opr:
            return opr
        new_instance = cls(symbol, function)
        instances.add(new_instance)
        return new_instance
    return getinstance


@singleton
class Operator:
    def __init__(self, symbol, function):
        self.symbol = symbol
        self.function = function

    def __str__(self):
        return self.symbol

    def calculate(self, first, second, **variables):
        return Constant(self.function(first.evaluate(**variables),
                                      second.evaluate(**variables)))


plus = create_operator('+', lambda lhs, rhs: lhs + rhs)
minus = create_operator('-', lambda lhs, rhs: lhs - rhs)
times = create_operator('*', lambda lhs, rhs: lhs * rhs)
divide = create_operator('/', lambda lhs, rhs: lhs / rhs)


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

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

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

    def __int__(self):
        return int(self.value)

    def __float__(self):
        return float(self.value)


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

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

    def __str__(self):
        return self.name


class Expression(Arithmetic):
    def __init__(self, expression_structure):
        self.expression_structure = expression_structure
        self.variable_names = []
        self.take_variables(self.expression_structure, self.variable_names)

    @staticmethod
    def take_variables(expression, names):
        for x in expression:
            if isinstance(x, Variable):
                names.append(x.name)
            elif isinstance(x, tuple):
                Expression.take_variables(x, names)
            elif isinstance(x, Expression):
                Expression.take_variables(x.expression_structure, names)

    def evaluate(self, **variables):
        return (Expression.evaluate_it(list(self.expression_structure),
                                       **variables)).value

    @staticmethod
    def simplify(expr, **variables):
        for index in range(len(expr)):
            if isinstance(expr[index], Expression):
                expr[index] = Constant(expr[index].evaluate(**variables))

    @staticmethod
    def evaluate_it(expression, **variables):
        expr = list(expression)
        Expression.simplify(expr, **variables)

        while len(expr) > 1:
            first = expr.pop(0)
            second = expr.pop(1)
            expr[0] = expr[0].calculate(first, second, **variables)
        return expr[0]

    def __str__(self):
        result = "("
        for x in self.expression_structure:
            if isinstance(x, plus.__class__):
                result += ' ' + str(x) + ' '
            else:
                result += str(x)
        return result + ")"

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

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

======================================================================
ERROR: test_both_nested_operands (test.TestExpressionObjects)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/data/rails/pyfmi-2016/releases/20160307095126/lib/language/python/runner.py", line 67, in thread
    raise result
AttributeError: 'tuple' object has no attribute 'evaluate'

======================================================================
ERROR: test_deep_expression (test.TestExpressionObjects)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/data/rails/pyfmi-2016/releases/20160307095126/lib/language/python/runner.py", line 67, in thread
    raise result
AttributeError: 'tuple' object has no attribute 'evaluate'

======================================================================
ERROR: test_evaluate_with_extra_kwargs (test.TestExpressionObjects)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/data/rails/pyfmi-2016/releases/20160307095126/lib/language/python/runner.py", line 67, in thread
    raise result
AttributeError: 'tuple' object has no attribute 'evaluate'

======================================================================
ERROR: test_one_nested_operand (test.TestExpressionObjects)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/data/rails/pyfmi-2016/releases/20160307095126/lib/language/python/runner.py", line 67, in thread
    raise result
AttributeError: 'tuple' object has no attribute 'evaluate'

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

======================================================================
FAIL: test_deep_string_conversion (test.TestExpressionObjects)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/data/rails/pyfmi-2016/releases/20160307095126/lib/language/python/runner.py", line 67, in thread
    raise result
AssertionError: '(((<solution.Variable object at 0x7f4d267f74[609 chars]>)))' != '(((x - 3) + (5 - y)) * ((y * 2) - (5 + 3)))'
Diff is 707 characters long. Set self.maxDiff to None to see it.

----------------------------------------------------------------------
Ran 19 tests in 0.129s

FAILED (failures=1, errors=6)

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

Мартин обнови решението на 18.03.2016 14:40 (преди над 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
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)


class Operator:
    _all = set()

    def __init__(self, symbol, function):
        found = False
        for x in Operator._all:
            if x.symbol == symbol:
                self = x
                found = True
        if not found:
            Operator._all.add(self)
            self.symbol = symbol
            self.function = function

    def __str__(self):
        return self.symbol


plus = create_operator('+', lambda lhs, rhs: lhs + rhs)
minus = create_operator('-', lambda lhs, rhs: lhs - rhs)
times = create_operator('*', lambda lhs, rhs: lhs * rhs)
divide = create_operator('/', lambda lhs, rhs: lhs / rhs)


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

    def evaluate(self):
        return self.value

    def __str__(self):
        return self.value

    def __int__(self):
        return int(self.value)

    def __float__(self):
        return float(self.value)

    def __add__(self, other):
        if isinstance(other, int) or isinstance(other, float):
            return Expression((self, plus, Constant(other)))
        return Expression((self, plus, other))

    def __sub__(self, other):
        if isinstance(other, int) or isinstance(other, float):
            return Expression((self, minus, Constant(other)))
        return Expression((self, minus, other))

    def __mul__(self, other):
        if isinstance(other, int) or isinstance(other, float):
            return Expression((self, times, Constant(other)))
        return Expression((self, times, other))

    def __truediv__(self, other):
        if isinstance(other, int) or isinstance(other, float):
            return Expression((self, divide, Constant(other)))
        return Expression((self, divide, other))


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

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

    def __str__(self):
        return self.name

    def __add__(self, other):
        if isinstance(other, int) or isinstance(other, float):
            return Expression((self, plus, Constant(other)))
        return Expression((self, plus, other))

    def __sub__(self, other):
        if isinstance(other, int) or isinstance(other, float):
            return Expression((self, minus, Constant(other)))
        return Expression((self, minus, other))

    def __mul__(self, other):
        if isinstance(other, int) or isinstance(other, float):
            return Expression((self, times, Constant(other)))
        return Expression((self, times, other))

    def __truediv__(self, other):
        if isinstance(other, int) or isinstance(other, float):
            return Expression((self, divide, Constant(other)))
        return Expression((self, divide, other))


class Expression:
    def __init__(self, expression_structure):
        self.expression_structure = expression_structure
        self.variable_names = []
        self.take_variables(self.expression_structure, self.variable_names)

    @staticmethod
    def take_variables(expression, names):
        for x in expression:
            if isinstance(x, Variable):
                names.append(x.name)
            elif isinstance(x, tuple):
                Expression.take_variables(x, names)
            elif isinstance(x, Expression):
                Expression.take_variables(x.expression_structure, names)

    def evaluate(self, **variables):
        return (Expression.evaluate_it(list(self.expression_structure),
                                       variables)).value

    @staticmethod
    def evaluate_it(expression, variables):
        expr = list(expression)
        for index in range(len(expr)):
            if isinstance(expr[index], tuple):
                expr[index] = Expression.evaluate_it(expr[index], variables)
            if isinstance(expr[index], Expression):
                expr[index] = Constant(expr[index].evaluate(variables))
        while len(expr) > 1:
            first = expr.pop(0)
            if isinstance(first, Variable):
                first = variables[first.name]
            else:
                first = first.value
            second = expr.pop(1)
            if isinstance(second, Variable):
                second = variables[second.name]
            else:
                second = second.value
            expr[0] = Constant(expr[0].function(first, second))
        return expr[0]

    def __str__(self):
        result = ""
        for x in self.expression_structure:
            result += x.__str__()
        return result

    def __add__(self, other):
        if isinstance(other, int) or isinstance(other, float):
            return Expression((self, plus, Constant(other)))
        return Expression((self, plus, other))

    def __sub__(self, other):
        if isinstance(other, int) or isinstance(other, float):
            return Expression((self, minus, Constant(other)))
        return Expression((self, minus, other))

    def __mul__(self, other):
        if isinstance(other, int) or isinstance(other, float):
            return Expression((self, times, Constant(other)))
        return Expression((self, times, other))

    def __truediv__(self, other):
        if isinstance(other, int) or isinstance(other, float):
            return Expression((self, divide, Constant(other)))
        return Expression((self, divide, other))
  • Operator.__init__ и Expression.evaluate_it са твърде сложни. Опрости ги.
  • Можеш да опростиш if isinstance(other, int) or isinstance(other, float): като използваш numbers.Number. Всички числа в езика са негови наследници, именно поради тази причина.
  • В този ред на мисли, този if го виждам копиран на много места. Намери начин да избегнеш това.
  • Дефинираш едни и същи оператори в няколко типа. Изнеси това в един базов клас.
  • Винаги предпочитай str(x) пред x.__str__().

edit: Също така, пусни си примерните тестове.

Мартин обнови решението на 20.03.2016 21: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
import numbers


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)


class Arithmetic:
    def __init__(self):
        pass

    def get(self):
        return self.__class__()

    @staticmethod
    def _operation(statemant_1, statemant_2, function):
        if isinstance(statemant_2, numbers.Number):
            return Expression((statemant_1, function, Constant(statemant_2)))
        return Expression((statemant_1, function, statemant_2))

    @staticmethod
    def _roperation(statemant_1, statemant_2, function):
        if isinstance(statemant_2, numbers.Number):
            return Expression((Constant(statemant_2), function, statemant_1))
        return Expression((statemant_2, function, statemant_1))

    def __add__(self, other):
        return Arithmetic._operation(self, other, plus)

    def __radd__(self, other):
        return Arithmetic._roperation(self, other, plus)

    def __sub__(self, other):
        return Arithmetic._operation(self, other, minus)

    def __rsub__(self, other):
        return Arithmetic._roperation(self, other, minus)

    def __mul__(self, other):
        return Arithmetic._operation(self, other, times)

    def __rmul__(self, other):
        return Arithmetic._roperation(self, other, times)

    def __truediv__(self, other):
        return Arithmetic._operation(self, other, divide)

    def __rtruediv__(self, other):
        return Arithmetic._roperation(self, other, divide)


def singleton(cls):
    instances = set()

    def getinstance(symbol, function):
        opr = next((x for x in instances if x.symbol == symbol), None)
        if opr:
            return opr
        new_instance = cls(symbol, function)
        instances.add(new_instance)
        return new_instance
    return getinstance


@singleton
class Operator():
    def __init__(self, symbol, function):
        self.symbol = symbol
        self.function = function

    def __str__(self):
        return self.symbol

    def calculate(self, first, second, **variables):
        if isinstance(first, Variable):
            first = variables[first.name]
        else:
            first = first.value
        if isinstance(second, Variable):
            second = variables[second.name]
        else:
            second = second.value
        return Constant(self.function(first, second))


plus = create_operator('+', lambda lhs, rhs: lhs + rhs)
minus = create_operator('-', lambda lhs, rhs: lhs - rhs)
times = create_operator('*', lambda lhs, rhs: lhs * rhs)
divide = create_operator('/', lambda lhs, rhs: lhs / rhs)


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

    def evaluate(self):
        return self.value

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

    def __int__(self):
        return int(self.value)

    def __float__(self):
        return float(self.value)


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

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

    def __str__(self):
        return self.name


class Expression(Arithmetic):
    def __init__(self, expression_structure):
        self.expression_structure = expression_structure
        self.variable_names = []
        self.take_variables(self.expression_structure, self.variable_names)

    @staticmethod
    def take_variables(expression, names):
        for x in expression:
            if isinstance(x, Variable):
                names.append(x.name)
            elif isinstance(x, tuple):
                Expression.take_variables(x, names)
            elif isinstance(x, Expression):
                Expression.take_variables(x.expression_structure, names)

    def evaluate(self, **variables):
        return (Expression.evaluate_it(list(self.expression_structure),
                                       **variables)).value

    @staticmethod
    def simplify(expr, **variables):
        for index in range(len(expr)):
            if isinstance(expr[index], tuple):
                expr[index] = Expression.evaluate_it(expr[index], **variables)
            if isinstance(expr[index], Expression):
                expr[index] = Constant(expr[index].evaluate(**variables))

    @staticmethod
    def evaluate_it(expression, **variables):
        expr = list(expression)
        Expression.simplify(expr, **variables)

        while len(expr) > 1:
            first = expr.pop(0)
            second = expr.pop(1)
            expr[0] = expr[0].calculate(first, second, **variables)
        return expr[0]

    def __str__(self):
        result = "("
        for x in self.expression_structure:
            if isinstance(x, plus.__class__):
                result += ' ' + str(x) + ' '
            else:
                result += str(x)
        return result + ")"

Мартин обнови решението на 20.03.2016 22:13 (преди над 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
import numbers


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)


class Arithmetic:
    def __init__(self):
        pass

    def get(self):
        return self.__class__()

    @staticmethod
    def _operation(statemant_1, statemant_2, function):
        if isinstance(statemant_2, numbers.Number):
            return Expression((statemant_1, function, Constant(statemant_2)))
        return Expression((statemant_1, function, statemant_2))

    @staticmethod
    def _roperation(statemant_1, statemant_2, function):
        if isinstance(statemant_2, numbers.Number):
            return Expression((Constant(statemant_2), function, statemant_1))
        return Expression((statemant_2, function, statemant_1))

    def __add__(self, other):
        return Arithmetic._operation(self, other, plus)

    def __radd__(self, other):
        return Arithmetic._roperation(self, other, plus)

    def __sub__(self, other):
        return Arithmetic._operation(self, other, minus)

    def __rsub__(self, other):
        return Arithmetic._roperation(self, other, minus)

    def __mul__(self, other):
        return Arithmetic._operation(self, other, times)

    def __rmul__(self, other):
        return Arithmetic._roperation(self, other, times)

    def __truediv__(self, other):
        return Arithmetic._operation(self, other, divide)

    def __rtruediv__(self, other):
        return Arithmetic._roperation(self, other, divide)


def singleton(cls):
    instances = set()

    def getinstance(symbol, function):
        opr = next((x for x in instances if x.symbol == symbol), None)
        if opr:
            return opr
        new_instance = cls(symbol, function)
        instances.add(new_instance)
        return new_instance
    return getinstance


@singleton
class Operator:
    def __init__(self, symbol, function):
        self.symbol = symbol
        self.function = function

    def __str__(self):
        return self.symbol

    def calculate(self, first, second, **variables):
        return Constant(self.function(first.evaluate(**variables),
                                      second.evaluate(**variables)))


plus = create_operator('+', lambda lhs, rhs: lhs + rhs)
minus = create_operator('-', lambda lhs, rhs: lhs - rhs)
times = create_operator('*', lambda lhs, rhs: lhs * rhs)
divide = create_operator('/', lambda lhs, rhs: lhs / rhs)


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

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

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

    def __int__(self):
        return int(self.value)

    def __float__(self):
        return float(self.value)


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

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

    def __str__(self):
        return self.name


class Expression(Arithmetic):
    def __init__(self, expression_structure):
        self.expression_structure = expression_structure
        self.variable_names = []
        self.take_variables(self.expression_structure, self.variable_names)

    @staticmethod
    def take_variables(expression, names):
        for x in expression:
            if isinstance(x, Variable):
                names.append(x.name)
            elif isinstance(x, tuple):
                Expression.take_variables(x, names)
            elif isinstance(x, Expression):
                Expression.take_variables(x.expression_structure, names)

    def evaluate(self, **variables):
        return (Expression.evaluate_it(list(self.expression_structure),
                                       **variables)).value

    @staticmethod
    def simplify(expr, **variables):
        for index in range(len(expr)):
            if isinstance(expr[index], Expression):
                expr[index] = Constant(expr[index].evaluate(**variables))

    @staticmethod
    def evaluate_it(expression, **variables):
        expr = list(expression)
        Expression.simplify(expr, **variables)

        while len(expr) > 1:
            first = expr.pop(0)
            second = expr.pop(1)
            expr[0] = expr[0].calculate(first, second, **variables)
        return expr[0]

    def __str__(self):
        result = "("
        for x in self.expression_structure:
            if isinstance(x, plus.__class__):
                result += ' ' + str(x) + ' '
            else:
                result += str(x)
        return result + ")"