timeit

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

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

Решение на Аритметични изрази от Славена Теодосиева

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

Към профила на Славена Теодосиева

Резултати

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

Код

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
def create_constant(value):
    return Constant(value)


def create_variable(name):
    return Variable(name)


def create_operator(symbol, function):
    return Binary_operator(symbol, function)


def create_expression(expression_structure):
    return Expression(expression_structure)


class Operations:
    def __add__(self, other):
        plus = create_operator('+', lambda lhs, rhs: lhs + rhs)
        if (isinstance(other, Constant) or isinstance(other, Variable)
                                        or isinstance(other, Expression)):
            return Expression((self, plus, other))
        if isinstance(other, int):
            return Expression((self, plus, Constant(other)))

    def __radd__(self, other):
        plus = create_operator('+', lambda lhs, rhs: lhs + rhs)
        if (isinstance(other, Constant) or isinstance(other, Variable)
                                        or isinstance(other, Expression)):
            return Expression((other, plus, self))
        if isinstance(other, int):
            return Expression((Constant(other), plus, self))

    def __sub__(self, other):
        minus = create_operator('-', lambda lhs, rhs: lhs - rhs)
        if (isinstance(other, Constant) or isinstance(other, Variable)
                                        or isinstance(other, Expression)):
            return Expression((self, minus, other))
        if isinstance(other, int):
            return Expression((self, minus, Constant(other)))

    def __rsub__(self, other):
        minus = create_operator('-', lambda lhs, rhs: lhs - rhs)
        if (isinstance(other, Constant) or isinstance(other, Variable)
                                        or isinstance(other, Expression)):
            return Expression((other, minus, self))
        if isinstance(other, int):
            return Expression((Constant(other), minus, self))

    def __mul__(self, other):
        times = create_operator('*', lambda lhs, rhs: lhs * rhs)
        if (isinstance(other, Constant) or isinstance(other, Variable)
                                        or isinstance(other, Expression)):
            return Expression((self, times, other))
        if isinstance(other, int):
            return Expression((self, times, Constant(other)))

    def __rmul__(self, other):
        times = create_operator('*', lambda lhs, rhs: lhs * rhs)
        if (isinstance(other, Constant) or isinstance(other, Variable)
                                        or isinstance(other, Expression)):
            return Expression((other, times, self))
        if isinstance(other, int):
            return Expression((Constant(other), times, self))

    def __truediv__(self, other):
        div = create_operator('/', lambda lhs, rhs: lhs / rhs)
        if (isinstance(other, Constant) or isinstance(other, Variable)
                                        or isinstance(other, Expression)):
            return Expression((self, div, other))
        if isinstance(other, int):
            return Expression((self, div, Constant(other)))

    def __rtruediv__(self, other):
        div = create_operator('/', lambda lhs, rhs: lhs / rhs)
        if (isinstance(other, Constant) or isinstance(other, Variable)
                                        or isinstance(other, Expression)):
            return Expression((other, div, self))
        if isinstance(other, int):
            return Expression((Constant(other), div, self))
    

class Constant(Operations):
    def __init__(self, value):
        self.value = value
        
    def __str__(self):
        return str(self.value)
    
    def evaluate(self):
        return self.value

   
class Variable(Operations):
    def __init__(self, name):
        self.name = name
        
    def __str__(self):
        return str(self.name)
    
    def evaluate(self, **kwargs):
        keys = kwargs.keys()
        return [kwargs[key] for key in keys if key == self.name][0]
        
    
class Binary_operator:
    def __init__(self, symbol, function):
        self.symbol = symbol
        self.function = function

    def priority(self):
        if self.symbol == '+' or self.symbol == '-':
            priority = 2
        if self.symbol == '*' or self.symbol == '/':
            priority = 1
        return priority

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


class Expression(Operations):
    def __init__(self, expression_structure):
        self.expression_structure = expression_structure

    def infix_to_postfix(self):
        stack = []
        postfix_result = []
        expr = self.expression_structure
        i = 0
        stack.append('(')
        while(i < len(expr)):
            if isinstance(expr[i], Constant) or isinstance(expr[i], Variable):
                postfix_result.append(expr[i])
                i += 1
            elif isinstance(expr[i], Binary_operator):
                top_of_stack = stack.pop()
                while(top_of_stack != '('
                      and top_of_stack.priority() < expr[i].priority()):
                    postfix_result.append(top_of_stack)
                    top_of_stack = stack.pop()
                stack.append(top_of_stack)
                stack.append(expr[i])
                i += 1            
            elif isinstance(expr[i], tuple):
                new_expr = create_expression(expr[i])
                postfix_result = postfix_result + new_expr.infix_to_postfix()
                i += 1
        top_of_stack = stack.pop()
        while(top_of_stack != '('):
            postfix_result.append(top_of_stack)
            top_of_stack = stack.pop()
        return postfix_result

    def evaluate(self, **variables):
        return evaluate_postfix(self.infix_to_postfix(), **variables)

    @property
    def variable_names(self):
        expr_list = self.infix_to_postfix()
        variables = set()
        for element in expr_list:
            if isinstance(element, Variable):
                variables.add(str(element))
        return tuple(variables)

    import string    
    def __str__(self):
        expr = self.expression_structure
        to_string = []
        for i in range(len(expr)):
            if (isinstance(expr[i], Constant) or isinstance(expr[i], Variable)
                or isinstance(expr[i], Binary_operator)):
                to_string.append(str(expr[i]))
            if isinstance(expr[i], tuple):
                new_expr = create_expression(expr[i])
                to_string = to_string + list(new_expr.__str__())
        return '(' + ''.join(to_string) + ')'
    

def evaluate_postfix(expr_list, **variables):
        i = 0
        while(i < len(expr_list)):
            while not isinstance(expr_list[i], Binary_operator):
                i += 1
            if isinstance(expr_list[i - 2], Constant):
                left_value = expr_list[i - 2].evaluate()
            elif isinstance(expr_list[i - 2], Variable):
                left_value = expr_list[i - 2].evaluate(**variables)
            else:
                left_value = expr_list[i - 2]
            if isinstance(expr_list[i - 1], Constant):
                right_value = expr_list[i - 1].evaluate()
            elif isinstance(expr_list[i - 1], Variable):
                right_value = expr_list[i - 1].evaluate(**variables)
            else:
                right_value = expr_list[i - 1]
            expr_list[i - 2] = expr_list[i].function(left_value, right_value)
            del expr_list[i - 1], expr_list[i - 1]
            i = i - 1
        return expr_list[0]  

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

.E..F.....F...FEE..
======================================================================
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 63, in thread
    raise TimeoutError
TimeoutError

======================================================================
ERROR: test_variables_and_constants_arithmetics (test.TestNativeOperators)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/data/rails/pyfmi-2016/releases/20160307095126/lib/language/python/runner.py", line 63, in thread
    raise TimeoutError
TimeoutError

======================================================================
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_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) - ((4 * y) * 3))'
- (-)
+ ((x + 5) - ((4 * y) * 3))


======================================================================
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: '(((x-3)+(5-y))*((y*2)-(5+3)))' != '(((x - 3) + (5 - y)) * ((y * 2) - (5 + 3)))'
- (((x-3)+(5-y))*((y*2)-(5+3)))
+ (((x - 3) + (5 - y)) * ((y * 2) - (5 + 3)))
?     + +  + +  + +   + +   + +  + +  + +


======================================================================
FAIL: test_simple_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: '(x+5)' != '(x + 5)'
- (x+5)
+ (x + 5)
?   + +


----------------------------------------------------------------------
Ran 19 tests in 4.137s

FAILED (failures=3, errors=3)

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

Славена обнови решението на 21.03.2016 01:05 (преди над 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
def create_constant(value):
    return Constant(value)


def create_variable(name):
    return Variable(name)


def create_operator(symbol, function):
    return Binary_operator(symbol, function)


def create_expression(expression_structure):
    return Expression(expression_structure)


class Operations:
    def __add__(self, other):
        plus = create_operator('+', lambda lhs, rhs: lhs + rhs)
        if (isinstance(other, Constant) or isinstance(other, Variable)
                                        or isinstance(other, Expression)):
            return Expression((self, plus, other))
        if isinstance(other, int):
            return Expression((self, plus, Constant(other)))

    def __radd__(self, other):
        plus = create_operator('+', lambda lhs, rhs: lhs + rhs)
        if (isinstance(other, Constant) or isinstance(other, Variable)
                                        or isinstance(other, Expression)):
            return Expression((other, plus, self))
        if isinstance(other, int):
            return Expression((Constant(other), plus, self))

    def __sub__(self, other):
        minus = create_operator('-', lambda lhs, rhs: lhs - rhs)
        if (isinstance(other, Constant) or isinstance(other, Variable)
                                        or isinstance(other, Expression)):
            return Expression((self, minus, other))
        if isinstance(other, int):
            return Expression((self, minus, Constant(other)))

    def __rsub__(self, other):
        minus = create_operator('-', lambda lhs, rhs: lhs - rhs)
        if (isinstance(other, Constant) or isinstance(other, Variable)
                                        or isinstance(other, Expression)):
            return Expression((other, minus, self))
        if isinstance(other, int):
            return Expression((Constant(other), minus, self))

    def __mul__(self, other):
        times = create_operator('*', lambda lhs, rhs: lhs * rhs)
        if (isinstance(other, Constant) or isinstance(other, Variable)
                                        or isinstance(other, Expression)):
            return Expression((self, times, other))
        if isinstance(other, int):
            return Expression((self, times, Constant(other)))

    def __rmul__(self, other):
        times = create_operator('*', lambda lhs, rhs: lhs * rhs)
        if (isinstance(other, Constant) or isinstance(other, Variable)
                                        or isinstance(other, Expression)):
            return Expression((other, times, self))
        if isinstance(other, int):
            return Expression((Constant(other), times, self))

    def __truediv__(self, other):
        div = create_operator('/', lambda lhs, rhs: lhs / rhs)
        if (isinstance(other, Constant) or isinstance(other, Variable)
                                        or isinstance(other, Expression)):
            return Expression((self, div, other))
        if isinstance(other, int):
            return Expression((self, div, Constant(other)))

    def __rtruediv__(self, other):
        div = create_operator('/', lambda lhs, rhs: lhs / rhs)
        if (isinstance(other, Constant) or isinstance(other, Variable)
                                        or isinstance(other, Expression)):
            return Expression((other, div, self))
        if isinstance(other, int):
            return Expression((Constant(other), div, self))
    

class Constant(Operations):
    def __init__(self, value):
        self.value = value
        
    def __str__(self):
        return str(self.value)
    
    def evaluate(self):
        return self.value

   
class Variable(Operations):
    def __init__(self, name):
        self.name = name
        
    def __str__(self):
        return str(self.name)
    
    def evaluate(self, **kwargs):
        keys = kwargs.keys()
        return [kwargs[key] for key in keys if key == self.name][0]
        
    
class Binary_operator:
    def __init__(self, symbol, function):
        self.symbol = symbol
        self.function = function

    def priority(self):
        if self.symbol == '+' or self.symbol == '-':
            priority = 2
        if self.symbol == '*' or self.symbol == '/':
            priority = 1
        return priority

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


class Expression(Operations):
    def __init__(self, expression_structure):
        self.expression_structure = expression_structure

    def infix_to_postfix(self):
        stack = []
        postfix_result = []
        expr = self.expression_structure
        i = 0
        stack.append('(')
        while(i < len(expr)):
            if isinstance(expr[i], Constant) or isinstance(expr[i], Variable):
                postfix_result.append(expr[i])
                i += 1
            elif isinstance(expr[i], Binary_operator):
                top_of_stack = stack.pop()
                while(top_of_stack != '('
                      and top_of_stack.priority() < expr[i].priority()):
                    postfix_result.append(top_of_stack)
                    top_of_stack = stack.pop()
                stack.append(top_of_stack)
                stack.append(expr[i])
                i += 1            
            elif isinstance(expr[i], tuple):
                new_expr = create_expression(expr[i])
                postfix_result = postfix_result + new_expr.infix_to_postfix()
                i += 1
        top_of_stack = stack.pop()
        while(top_of_stack != '('):
            postfix_result.append(top_of_stack)
            top_of_stack = stack.pop()
        return postfix_result

    def evaluate(self, **variables):
        return evaluate_postfix(self.infix_to_postfix(), **variables)

    @property
    def variable_names(self):
        expr_list = self.infix_to_postfix()
        variables = set()
        for element in expr_list:
            if isinstance(element, Variable):
                variables.add(str(element))
        return tuple(variables)

    import string    
    def __str__(self):
        expr = self.expression_structure
        to_string = []
        for i in range(len(expr)):
            if (isinstance(expr[i], Constant) or isinstance(expr[i], Variable)
                or isinstance(expr[i], Binary_operator)):
                to_string.append(str(expr[i]))
            if isinstance(expr[i], tuple):
                new_expr = create_expression(expr[i])
                to_string = to_string + list(new_expr.__str__())
        return '(' + ''.join(to_string) + ')'
    

def evaluate_postfix(expr_list, **variables):
        i = 0
        while(i < len(expr_list)):
            while not isinstance(expr_list[i], Binary_operator):
                i += 1
            if isinstance(expr_list[i - 2], Constant):
                left_value = expr_list[i - 2].evaluate()
            elif isinstance(expr_list[i - 2], Variable):
                left_value = expr_list[i - 2].evaluate(**variables)
            else:
                left_value = expr_list[i - 2]
            if isinstance(expr_list[i - 1], Constant):
                right_value = expr_list[i - 1].evaluate()
            elif isinstance(expr_list[i - 1], Variable):
                right_value = expr_list[i - 1].evaluate(**variables)
            else:
                right_value = expr_list[i - 1]
            expr_list[i - 2] = expr_list[i].function(left_value, right_value)
            del expr_list[i - 1], expr_list[i - 1]
            i = i - 1
        return expr_list[0]