timeit

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

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

Решение на Аритметични изрази от Марианна Владимирова

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

Към профила на Марианна Владимирова

Резултати

  • 2 точки от тестове
  • 1 отнета точка
  • 1 точка общо
  • 3 успешни тест(а)
  • 16 неуспешни тест(а)

Код

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
class Operator:
    def __init__(self, symbol, function):
        self.symbol = symbol
        self.function = function

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


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

    def __add__(self, other):
        return Expression((self.value, Operator('+', lambda lhs, rhs:
                                                lhs + rhs), other))

    def __sub__(self, other):
        return Expression((self.value, Operator('-', lambda lhs, rhs:
                                                lhs - rhs), other))

    def __mul__(self, other):
        return Expression((self.value, Operator('*', lambda lhs, rhs:
                                                lhs * rhs), other))

    def __truediv__(self, other):
        return Expression((self.value, Operator('/', lambda lhs, rhs:
                                                lhs / rhs), other))

    def __floordiv__(self, other):
        return Expression((self.value, Operator('//', lambda lhs, rhs:
                                                lhs // rhs), other))

    def __mod__(self, other):
        return Expression((self.value, Operator('%', lambda lhs, rhs:
                                                lhs % rhs), other))

    def __pow__(self, other):
        return Expression((self.value, Operator('**', lambda lhs, rhs:
                                                lhs ** rhs), other))

    def __and__(self, other):
        return Expression((self.value, Operator('&', lambda lhs, rhs:
                                                lhs & rhs), other))

    def __xor__(self, other):
        return Expression((self.value, Operator('^', lambda lhs, rhs:
                                                lhs ^ rhs), other))

    def __or__(self, other):
        return Expression((self.value, Operator('|', lambda lhs, rhs:
                                                lhs | rhs), other))

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

    def evaluate(self):
        return self.value


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

    def __add__(self, other):
        return Expression((self, Operator('+', lambda lhs, rhs:
                                          lhs + rhs), other))

    def __sub__(self, other):
        return Expression((self, Operator('-', lambda lhs, rhs:
                                          lhs - rhs), other))

    def __mul__(self, other):
        return Expression((self, Operator('*', lambda lhs, rhs:
                                          lhs * rhs), other))

    def __truediv__(self, other):
        return Expression((self, Operator('/', lambda lhs, rhs:
                                          lhs / rhs), other))

    def __floordiv__(self, other):
        return Expression((self, Operator('//', lambda lhs, rhs:
                                          lhs // rhs), other))

    def __mod__(self, other):
        return Expression((self, Operator('%', lambda lhs, rhs:
                                          lhs % rhs), other))

    def __pow__(self, other):
        return Expression((self, Operator('**', lambda lhs, rhs:
                                          lhs ** rhs), other))

    def __and__(self, other):
        return Expression((self, Operator('&', lambda lhs, rhs:
                                          lhs & rhs), other))

    def __xor__(self, other):
        return Expression((self, Operator('^', lambda lhs, rhs:
                                          lhs ^ rhs), other))

    def __or__(self, other):
        return Expression((self, Operator('|', lambda lhs, rhs:
                                          lhs | rhs), other))

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

    def evaluate(self, **variables):
        for key, value in variables.items():
            if key == self.name:
                self.value = value
        return self.value


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

    def getVariables(self):
        variable_names = [variable.name for variable
                          in self.expression_structure
                          if isinstance(variable, Variable)]
        return variable_names

    def evaluate(self, **variables):
        rhs = 0
        lhs = 0
        result = 0
        for element in self.expression_structure:
            if isinstance(element, Operator):
                operator = element
            if isinstance(element, Variable):
                if element.name in self.variable_names:
                    for key, value in variables.items():
                        if key == element.name:
                            element.value = value
                if lhs == 0:
                    lhs = element.value
                else:
                    rhs = element.value
            if isinstance(element, Constant):
                if lhs == 0:
                    lhs = element.value
                else:
                    rhs = element.value
            if lhs != 0 and rhs != 0 and isinstance(operator, Operator):
                result = operator.function(lhs, rhs)
        return result


def create_constant(value):
    constant = Constant(value)
    return constant


def create_variable(name):
    variable = Variable(name)
    return variable


def create_operator(symbol, function):
    operator = Operator(symbol, function)
    return operator


def create_expression(expression_structure):
    expression = Expression(expression_structure)
    return expression

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

FFEEEFF.FFFFF.FEEF.
======================================================================
ERROR: test_left_hand_side_literal_and_constant (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
TypeError: unsupported operand type(s) for +: 'int' and 'Constant'

======================================================================
ERROR: test_left_hand_side_literal_and_variable (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
TypeError: unsupported operand type(s) for +: 'int' and 'Variable'

======================================================================
ERROR: 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
TypeError: unsupported operand type(s) for *: 'int' and 'Variable'

======================================================================
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 67, in thread
    raise result
TypeError: unsupported operand type(s) for -: 'Expression' and 'Expression'

======================================================================
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 %: 'Expression' and 'Constant'

======================================================================
FAIL: test_constant_and_right_hand_side_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
AssertionError: 0 != 8

======================================================================
FAIL: 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
AssertionError: 0 != 10

======================================================================
FAIL: test_variable_and_right_hand_side_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
AssertionError: 0 != 7

======================================================================
FAIL: test_constants (test.TestConstants)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/data/rails/pyfmi-2016/releases/20160307095126/lib/language/python/runner.py", line 67, in thread
    raise result
AssertionError: 0 != 8

======================================================================
FAIL: 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
AssertionError: 0 != 11

======================================================================
FAIL: 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
AssertionError: 0 != -24

======================================================================
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.Expression object at 0x7f9fc4207a20>' != '(((x - 3) + (5 - y)) * ((y * 2) - (5 + 3)))'
- <solution.Expression object at 0x7f9fc4207a20>
+ (((x - 3) + (5 - y)) * ((y * 2) - (5 + 3)))


======================================================================
FAIL: 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
AssertionError: 0 != 11

======================================================================
FAIL: 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
AssertionError: 0 != 8

======================================================================
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: '<solution.Expression object at 0x7f9fc4207a20>' != '(x + 5)'
- <solution.Expression object at 0x7f9fc4207a20>
+ (x + 5)


======================================================================
FAIL: test_string_conversion (test.TestVariables)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/data/rails/pyfmi-2016/releases/20160307095126/lib/language/python/runner.py", line 67, in thread
    raise result
AssertionError: '0' != 'x'
- 0
+ x


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

FAILED (failures=11, errors=5)

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

Марианна обнови решението на 20.03.2016 22:00 (преди над 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
class Operator:
    def __init__(self, symbol, function):
        self.symbol = symbol
        self.function = function

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


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

    def __add__(self, other):
        expression = Expression((self.value, Operator('+', lambda lhs, rhs:
                                                      lhs + rhs), other))
        return expression

    def __sub__(self, other):
        expression = Expression((self.value, Operator('-', lambda lhs, rhs:
                                                      lhs - rhs), other))
        return expression

    def __mul__(self, other):
        expression = Expression((self.value, Operator('*', lambda lhs, rhs:
                                                      lhs * rhs), other))
        return expression

    def __truediv__(self, other):
        expression = Expression((self.value, Operator('/', lambda lhs, rhs:
                                                      lhs / rhs), other))
        return expression

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

    def evaluate(self):
        return self.value


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

    def __add__(self, other):
        expression = Expression((self, Operator('+', lambda lhs, rhs:
                                                lhs + rhs), other))
        return expression

    def __sub__(self, other):
        expression = Expression((self, Operator('-', lambda lhs, rhs:
                                                lhs - rhs), other))
        return expression

    def __mul__(self, other):
        expression = Expression((self, Operator('*', lambda lhs, rhs:
                                                lhs * rhs), other))
        return expression

    def __truediv__(self, other):
        expression = Expression((self, Operator('/', lambda lhs, rhs:
                                                lhs / rhs), other))
        return expression

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

    def evaluate(self, **variables):
        for key, value in variables.items():
            if key == self.name:
                self.value = value
        return self.value


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

    def getVariables(self):
        variable_names = [variable.name for variable
                          in self.expression_structure
                          if type(variable) is Variable]
        return variable_names

    def evaluate(self, **variables):
        rhs = 0
        lhs = 0
        result = 0
        for element in self.expression_structure:
            if type(element) is Operator:
                operator = element
            if type(element) is Variable:
                if element.name in self.variable_names:
                    for key, value in variables.items():
                        if key == element.name:
                            element.value = value
                if lhs == 0:
                    lhs = element.value
                else:
                    rhs = element.value
            if type(element) is Constant:
                if lhs == 0:
                    lhs = element.value
                else:
                    rhs = element.value
            if lhs != 0 and rhs != 0 and type(operator) is Operator:
                result = operator.function(lhs, rhs)
        return result


def create_constant(value):
    constant = Constant(value)
    return constant


def create_variable(name):
    variable = Variable(name)
    return variable


def create_operator(symbol, function):
    operator = Operator(symbol, function)
    return operator


def create_expression(expression_structure):
    expression = Expression(expression_structure)
    return expression
  • Дефинираш едни и същи оператори в два различни класа.
  • Липсват ти оператори за предефиниране.
  • Expression.evaluate може да се опрости малко.
  • На няколко места дефинираш променлива, само за да я върнеш на следващия ред, вместо да върнеш самия израз.
  • Предпочитай да сравняваш типове с isinstance, вместо с type.

Марианна обнови решението на 21.03.2016 14: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
class Operator:
    def __init__(self, symbol, function):
        self.symbol = symbol
        self.function = function

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


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

    def __add__(self, other):
        return Expression((self.value, Operator('+', lambda lhs, rhs:
                                                lhs + rhs), other))

    def __sub__(self, other):
        return Expression((self.value, Operator('-', lambda lhs, rhs:
                                                lhs - rhs), other))

    def __mul__(self, other):
        return Expression((self.value, Operator('*', lambda lhs, rhs:
                                                lhs * rhs), other))

    def __truediv__(self, other):
        return Expression((self.value, Operator('/', lambda lhs, rhs:
                                                lhs / rhs), other))

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

    def evaluate(self):
        return self.value


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

    def __add__(self, other):
        return Expression((self, Operator('+', lambda lhs, rhs:
                                          lhs + rhs), other))

    def __sub__(self, other):
        return Expression((self, Operator('-', lambda lhs, rhs:
                                          lhs - rhs), other))

    def __mul__(self, other):
        return Expression((self, Operator('*', lambda lhs, rhs:
                                          lhs * rhs), other))

    def __truediv__(self, other):
        return Expression((self, Operator('/', lambda lhs, rhs:
                                          lhs / rhs), other))

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

    def evaluate(self, **variables):
        for key, value in variables.items():
            if key == self.name:
                self.value = value
        return self.value


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

    def getVariables(self):
        variable_names = [variable.name for variable
                          in self.expression_structure
                          if isinstance(variable, Variable)]
        return variable_names

    def evaluate(self, **variables):
        rhs = 0
        lhs = 0
        result = 0
        for element in self.expression_structure:
            if isinstance(element, Operator):
                operator = element
            if isinstance(element, Variable):
                if element.name in self.variable_names:
                    for key, value in variables.items():
                        if key == element.name:
                            element.value = value
                if lhs == 0:
                    lhs = element.value
                else:
                    rhs = element.value
            if isinstance(element, Constant):
                if lhs == 0:
                    lhs = element.value
                else:
                    rhs = element.value
            if lhs != 0 and rhs != 0 and isinstance(operator, Operator):
                result = operator.function(lhs, rhs)
        return result


def create_constant(value):
    constant = Constant(value)
    return constant


def create_variable(name):
    variable = Variable(name)
    return variable


def create_operator(symbol, function):
    operator = Operator(symbol, function)
    return operator


def create_expression(expression_structure):
    expression = Expression(expression_structure)
    return expression

Марианна обнови решението на 21.03.2016 16:03 (преди над 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
class Operator:
    def __init__(self, symbol, function):
        self.symbol = symbol
        self.function = function

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


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

    def __add__(self, other):
        return Expression((self.value, Operator('+', lambda lhs, rhs:
                                                lhs + rhs), other))

    def __sub__(self, other):
        return Expression((self.value, Operator('-', lambda lhs, rhs:
                                                lhs - rhs), other))

    def __mul__(self, other):
        return Expression((self.value, Operator('*', lambda lhs, rhs:
                                                lhs * rhs), other))

    def __truediv__(self, other):
        return Expression((self.value, Operator('/', lambda lhs, rhs:
                                                lhs / rhs), other))

    def __floordiv__(self, other):
        return Expression((self.value, Operator('//', lambda lhs, rhs:
                                                lhs // rhs), other))

    def __mod__(self, other):
        return Expression((self.value, Operator('%', lambda lhs, rhs:
                                                lhs % rhs), other))

    def __pow__(self, other):
        return Expression((self.value, Operator('**', lambda lhs, rhs:
                                                lhs ** rhs), other))

    def __and__(self, other):
        return Expression((self.value, Operator('&', lambda lhs, rhs:
                                                lhs & rhs), other))

    def __xor__(self, other):
        return Expression((self.value, Operator('^', lambda lhs, rhs:
                                                lhs ^ rhs), other))

    def __or__(self, other):
        return Expression((self.value, Operator('|', lambda lhs, rhs:
                                                lhs | rhs), other))

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

    def evaluate(self):
        return self.value


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

    def __add__(self, other):
        return Expression((self, Operator('+', lambda lhs, rhs:
                                          lhs + rhs), other))

    def __sub__(self, other):
        return Expression((self, Operator('-', lambda lhs, rhs:
                                          lhs - rhs), other))

    def __mul__(self, other):
        return Expression((self, Operator('*', lambda lhs, rhs:
                                          lhs * rhs), other))

    def __truediv__(self, other):
        return Expression((self, Operator('/', lambda lhs, rhs:
                                          lhs / rhs), other))

    def __floordiv__(self, other):
        return Expression((self, Operator('//', lambda lhs, rhs:
                                          lhs // rhs), other))

    def __mod__(self, other):
        return Expression((self, Operator('%', lambda lhs, rhs:
                                          lhs % rhs), other))

    def __pow__(self, other):
        return Expression((self, Operator('**', lambda lhs, rhs:
                                          lhs ** rhs), other))

    def __and__(self, other):
        return Expression((self, Operator('&', lambda lhs, rhs:
                                          lhs & rhs), other))

    def __xor__(self, other):
        return Expression((self, Operator('^', lambda lhs, rhs:
                                          lhs ^ rhs), other))

    def __or__(self, other):
        return Expression((self, Operator('|', lambda lhs, rhs:
                                          lhs | rhs), other))

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

    def evaluate(self, **variables):
        for key, value in variables.items():
            if key == self.name:
                self.value = value
        return self.value


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

    def getVariables(self):
        variable_names = [variable.name for variable
                          in self.expression_structure
                          if isinstance(variable, Variable)]
        return variable_names

    def evaluate(self, **variables):
        rhs = 0
        lhs = 0
        result = 0
        for element in self.expression_structure:
            if isinstance(element, Operator):
                operator = element
            if isinstance(element, Variable):
                if element.name in self.variable_names:
                    for key, value in variables.items():
                        if key == element.name:
                            element.value = value
                if lhs == 0:
                    lhs = element.value
                else:
                    rhs = element.value
            if isinstance(element, Constant):
                if lhs == 0:
                    lhs = element.value
                else:
                    rhs = element.value
            if lhs != 0 and rhs != 0 and isinstance(operator, Operator):
                result = operator.function(lhs, rhs)
        return result


def create_constant(value):
    constant = Constant(value)
    return constant


def create_variable(name):
    variable = Variable(name)
    return variable


def create_operator(symbol, function):
    operator = Operator(symbol, function)
    return operator


def create_expression(expression_structure):
    expression = Expression(expression_structure)
    return expression