timeit

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

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

Решение на Аритметични изрази от Александър Чешмеджиев

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

Към профила на Александър Чешмеджиев

Резултати

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

Код

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
class Evaluable:
    def __init__(self, value):
        self.value = value

    def evaluate(self, **args):
        if self.value in args:
            return args[self.value]
        return self.value

    def __mul__(self, value):
        operator = create_operator('*', lambda first, second: first * second)
        return get_operator_definition(self, operator, value)

    def __add__(self, value):
        operator = create_operator('+', lambda first, second: first + second)
        return get_operator_definition(self, operator, value)

    def __sub__(self, value):
        operator = create_operator('-', lambda first, second: first - second)
        return get_operator_definition(self, operator, value)

    def __truediv__(self, value):
        operator = create_operator('/', lambda first, second: first / second)
        return get_operator_definition(self, operator, value)

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

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


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

    def __setattr__(self, name, value):
        # add checking of assigned values so Contstant value cannot be changed
        if hasattr(self, name) and name == 'value':
            return None
        object.__setattr__(self, name, value)


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


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

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

    def __mul__(self, value):
        operator = create_operator('*', lambda first, second: first * second)
        return get_operator_definition(self.expression_structure,
                                       operator,
                                       value)

    def __add__(self, value):
        operator = create_operator('+', lambda first, second: first + second)
        return get_operator_definition(self.expression_structure,
                                       operator,
                                       value)

    def __sub__(self, value):
        operator = create_operator('-', lambda first, second: first - second)
        return get_operator_definition(self.expression_structure,
                                       operator,
                                       value)

    def __truediv__(self, value):
        operator = create_operator('/', lambda first, second: first / second)
        return get_operator_definition(self.expression_structure,
                                       operator,
                                       value)

    def __str__(self):
        return str(self.expression_structure).replace(',', '')


class Operator:
    _defined_operators = {}

    def __init__(self, symbol, function):
        self.symbol = symbol
        self.function = function

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

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


def create_operator(symbol, function):
    if symbol in Operator._defined_operators:
        return Operator._defined_operators[symbol]
    operator = Operator(symbol, function)
    Operator._defined_operators[symbol] = operator
    return operator


def create_constant(value):
    return Constant(value)


def create_variable(name):
    return Variable(name)


def create_expression(expression_structure):
    return Expression(expression_structure)


def evaluate_expression(exression_structure, variables):
    for first_argument, operator, second_argument in exression_structure:
        left_operand = evaluate_argument(first_argument,
                                         variables,
                                         evaluate_expression)
        right_operand = evaluate_argument(second_argument,
                                          variables,
                                          evaluate_expression)
        return operator.function(left_operand, right_operand)


def evaluate_argument(argument, variables, recursive_callback):
    if isinstance(argument, Variable) and \
           argument.evaluate() in variables:
        return variables[argument.evaluate()]
    elif isinstance(argument, Constant):
        return argument.evaluate()
    elif hasattr(argument, '__iter__'):
        return recursive_callback([argument], variables)


def get_variable_names(expression_structure, result):
    for item in expression_structure:
        if hasattr(item, '__iter__'):
            get_variable_names(item, result)
        elif isinstance(item, Variable):
            if not str(item) in result:
                result.append(str(item))
    return tuple(result)


def get_operator_definition(self_value, operator, value):
    if isinstance(value, Expression):
        value = value.expression_structure
    elif not isinstance(value, Evaluable):
        value = create_constant(value)
    return create_expression((self_value, operator, value))

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

.EEEE...........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
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'

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

----------------------------------------------------------------------
Ran 19 tests in 0.119s

FAILED (errors=5)

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

Александър обнови решението на 20.03.2016 17:23 (преди над 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
class Evaluable:
    def __init__(self, value):
        self.value = value

    def evaluate(self, **args):
        if self.value in args:
            return args[self.value]
        return self.value

    def __mul__(self, value):
        operator = create_operator('*', lambda first, second: first * second)
        return get_operator_definition(self, operator, value)

    def __add__(self, value):
        operator = create_operator('+', lambda first, second: first + second)
        return get_operator_definition(self, operator, value)

    def __sub__(self, value):
        operator = create_operator('-', lambda first, second: first - second)
        return get_operator_definition(self, operator, value)

    def __truediv__(self, value):
        operator = create_operator('/', lambda first, second: first / second)
        return get_operator_definition(self, operator, value)

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

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


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

    def __setattr__(self, name, value):
        # add checking of assigned values so Contstant value cannot be changed
        if hasattr(self, name) and name == 'value':
            return None
        object.__setattr__(self, name, value)


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


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

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

    def __mul__(self, value):
        operator = create_operator('*', lambda first, second: first * second)
        return get_operator_definition(self.expression_structure,
                                       operator,
                                       value)

    def __add__(self, value):
        operator = create_operator('+', lambda first, second: first + second)
        return get_operator_definition(self.expression_structure,
                                       operator,
                                       value)

    def __sub__(self, value):
        operator = create_operator('-', lambda first, second: first - second)
        return get_operator_definition(self.expression_structure,
                                       operator,
                                       value)

    def __truediv__(self, value):
        operator = create_operator('/', lambda first, second: first / second)
        return get_operator_definition(self.expression_structure,
                                       operator,
                                       value)

    def __str__(self):
        return str(self.expression_structure).replace(',', '')


class Operator:
    _defined_operators = {}

    def __init__(self, symbol, function):
        self.symbol = symbol
        self.function = function

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

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


def create_operator(symbol, function):
    if symbol in Operator._defined_operators:
        return Operator._defined_operators[symbol]
    operator = Operator(symbol, function)
    Operator._defined_operators[symbol] = operator
    return operator


def create_constant(value):
    return Constant(value)


def create_variable(name):
    return Variable(name)


def create_expression(expression_structure):
    return Expression(expression_structure)


def evaluate_expression(exression_structure, variables):
    for first_argument, operator, second_argument in exression_structure:
        left_operand = evaluate_argument(first_argument,
                                         variables,
                                         evaluate_expression)
        right_operand = evaluate_argument(second_argument,
                                          variables,
                                          evaluate_expression)
        return operator.function(left_operand, right_operand)


def evaluate_argument(argument, variables, recursive_callback):
    if isinstance(argument, Variable) and \
           argument.evaluate() in variables:
        return variables[argument.evaluate()]
    elif isinstance(argument, Constant):
        return argument.evaluate()
    elif hasattr(argument, '__iter__'):
        return recursive_callback([argument], variables)


def get_variable_names(expression_structure, result):
    for item in expression_structure:
        if hasattr(item, '__iter__'):
            get_variable_names(item, result)
        elif isinstance(item, Variable):
            if not str(item) in result:
                result.append(str(item))
    return tuple(result)


def get_operator_definition(self_value, operator, value):
    if isinstance(value, Expression):
        value = value.expression_structure
    elif not isinstance(value, Evaluable):
        value = create_constant(value)
    return create_expression((self_value, operator, value))
  • Преизползването на value атрибута в константите и променливите не е яко.
  • Защо Expression да не наслдява от Evaluable? Все пак изразите са оценими.
  • evaluate_argument, evaluate_expression и evaluate методите на класовете ти не са ли всъщност един много сложен начин да изразиш нещо, което много елегантно може да се изрази с рекурсия ако разчиташ на duck typing?
  • Защо външна функция get_variable_names вместо property variable_names?