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
class Operand:
    def __add__(self, expr):
        op = create_operator('+', lambda x, y: x + y)
        return create_expression([self, op, expr])

    def __mul__(self, expr):
        op = create_operator('*', lambda x, y: x * y)
        return create_expression([self, op, expr])

    def __div__(self, expr):
        op = create_operator('/', lambda x, y: x / y)
        return create_expression([self, op, expr])

    def __sub__(self, expr):
        op = create_operator('-', lambda x, y: x - y)
        return create_expression([self, op, expr])


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

    def evaluate(self):
        return self.__value

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


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

    def __str__(self):
        return self.name

    def evaluate(self, **kwargs):
        if self.name in kwargs:
            self.value = kwargs[self.name]
        return self.value


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

    def __str__(self):
        return " " + self.symbol + " "

    def evaluate(self, arg1, arg2):
        return self.function(arg1, arg2)


class Expression(Operand):
    def __init__(self, expr):
        self.expr = []
        variables = []
        for item in expr:
            if isinstance(item, Variable):
                variables.append(item)
                self.expr.append(item)
            elif isinstance(item, Operand) or isinstance(item, Operator):
                self.expr.append(item)
            else:
                new_expr = create_expression(item)
                variables += new_expr.variables
                self.expr.append(new_expr)
            self.variables = []
            self.variables = [var for var in variables
                              if var not in self.variables]
            self.variable_names = filter(lambda x: x.name, self.variables)

    def __str__(self):
        to_string = str()
        to_string += "("
        for item in self.expr:
                to_string += str(item)
        to_string += ")"
        return to_string

    def evaluate(self, **variables):
        for variable in self.variables:
            if variable.name in variables:
                variable.value = variables[variable.name]
        for i in range(0, len(self.expr), 2):
            if isinstance(self.expr[i], Expression):
                operand = self.expr[i].evaluate(**variables)
            else:
                operand = self.expr[i].evaluate()
            if i == 0:
                result = operand
            else:
                result = self.expr[i - 1].evaluate(result, operand)
        return result


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)

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

EEEEEE..........E..
======================================================================
ERROR: 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
TypeError: 'int' object is not iterable

======================================================================
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: 'int' object is not iterable

======================================================================
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: 'int' object is not iterable

======================================================================
ERROR: 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
TypeError: 'int' object is not iterable

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

FAILED (errors=7)

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

Александрина обнови решението на 16.03.2016 18:03 (преди почти 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
class Constant:

    def __init__(self, value):
        self.__value = value

    def evaluate(self):
        return self.__value

    def __add__(self, expr):
        op = create_operator('+', lambda x, y: x + y)
        return create_expression([self, op, expr])

    def __mul__(self, expr):
        op = create_operator('*', lambda x, y: x * y)
        return create_expression([self, op, expr])

    def __div__(self, expr):
        op = create_operator('/', lambda x, y: x / y)
        return create_expression([self, op, expr])

    def __sub__(self, expr):
        op = create_operator('-', lambda x, y: x - y)
        return create_expression([self, op, expr])


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

    def evaluate(self, **kwargs):
        if self.name in kwargs:
            self.value = kwargs[self.name]
        return self.value

    def __add__(self, expr):
        op = create_operator('+', lambda x, y: x + y)
        return create_expression([self, op, expr])

    def __mul__(self, expr):
        op = create_operator('*', lambda x, y: x * y)
        return create_expression([self, op, expr])

    def __div__(self, expr):
        op = create_operator('/', lambda x, y: x / y)
        return create_expression([self, op, expr])

    def __sub__(self, expr):
        op = create_operator('-', lambda x, y: x - y)
        return create_expression([self, op, expr])


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

    def evaluate(self, arg1, arg2):
        return self.function(arg1, arg2)


class Expression:
    def __init__(self, expr):
        self.expr = []
        self.variables = []
        self.variable_names = []

        for item in expr:
            if isinstance(item, Variable):
                self.variables.append(item)
                self.variable_names.append(item.name)
                self.expr.append(item)
            elif isinstance(item, Constant) or isinstance(item, Operator):
                self.expr.append(item)
            else:
                new_expr = create_expression(item)
                self.variables += new_expr.variables
                self.variable_names += new_expr.variable_names
                self.expr.append(new_expr)

    def helper(self, l):
        print(l)
        print(self.variables)
        if len(l) == 1:
            if isinstance(l[0], Variable):
                print(l[0].value)
            return l[0].evaluate()
        else:
            return l[1].evaluate(l[0].evaluate(),
                                 self.helper(l[2:len(l)]))

    def evaluate(self, **variables):
        for variable in self.variables:
            if variable.name in variables:
                variable.value = variables[variable.name]

        return self.helper(self.expr)

    def __add__(self, expr):
        op = create_operator('+', lambda x, y: x + y)
        return create_expression([self, op, expr])

    def __mul__(self, expr):
        op = create_operator('*', lambda x, y: x * y)
        return create_expression([self, op, expr])

    def __div__(self, expr):
        op = create_operator('/', lambda x, y: x / y)
        return create_expression([self, op, expr])

    def __sub__(self, expr):
        op = create_operator('-', lambda x, y: x - y)
        return create_expression([self, op, expr])


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


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)
  • Variable и Constant имат доста общи неща, това трябва да те наведе на мисълта, че можеш да изнесеш общите неща в родителски клас.
  • for-а с if/else-а в __init__-а на Expression не е много як. Помисли какво можеш да направиш по въпроса.
  • наличието на нещо, което се казва helper обикновено е симптом на кофти дизайн. Първия пас, който трябва да направиш, за да сетнеш value атрибутите на променливите е ненужен, можеш да ги оценяваш докато правиш самата сметка.
  • print-овете са полезни за дебъгване, но ги махай като предаваш решението си :)

Александрина обнови решението на 18.03.2016 00:21 (преди почти 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
class Operand:
    def __add__(self, expr):
        op = create_operator('+', lambda x, y: x + y)
        return create_expression([self, op, expr])

    def __mul__(self, expr):
        op = create_operator('*', lambda x, y: x * y)
        return create_expression([self, op, expr])

    def __div__(self, expr):
        op = create_operator('/', lambda x, y: x / y)
        return create_expression([self, op, expr])

    def __sub__(self, expr):
        op = create_operator('-', lambda x, y: x - y)
        return create_expression([self, op, expr])


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

    def evaluate(self):
        return self.__value

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


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

    def __str__(self):
        return self.name

    def evaluate(self, **kwargs):
        if self.name in kwargs:
            self.value = kwargs[self.name]
        return self.value


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

    def __str__(self):
        return " " + self.symbol + " "

    def evaluate(self, arg1, arg2):
        return self.function(arg1, arg2)


class Expression(Operand):
    def __init__(self, expr):
        self.expr = []
        variables = []
        for item in expr:
            if isinstance(item, Variable):
                variables.append(item)
                self.expr.append(item)
            elif isinstance(item, Operand) or isinstance(item, Operator):
                self.expr.append(item)
            else:
                new_expr = create_expression(item)
                variables += new_expr.variables
                self.expr.append(new_expr)
            self.variables = []
            self.variables = [var for var in variables
                              if var not in self.variables]
            self.variable_names = filter(lambda x: x.name, self.variables)

    def __str__(self):
        print(self.expr)
        to_string = str()
        to_string += "("
        for item in self.expr:
                to_string += str(item)
        to_string += ")"
        return to_string

    def evaluate(self, **variables):
        for variable in self.variables:
            if variable.name in variables:
                variable.value = variables[variable.name]
        for i in range(0, len(self.expr), 2):
            if isinstance(self.expr[i], Expression):
                operand = self.expr[i].evaluate(**variables)
            else:
                operand = self.expr[i].evaluate()
            if i == 0:
                result = operand
            else:
                result = self.expr[i - 1].evaluate(result, operand)
        return result


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)

Александрина обнови решението на 21.03.2016 00:27 (преди над 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
class Operand:
    def __add__(self, expr):
        op = create_operator('+', lambda x, y: x + y)
        return create_expression([self, op, expr])

    def __mul__(self, expr):
        op = create_operator('*', lambda x, y: x * y)
        return create_expression([self, op, expr])

    def __div__(self, expr):
        op = create_operator('/', lambda x, y: x / y)
        return create_expression([self, op, expr])

    def __sub__(self, expr):
        op = create_operator('-', lambda x, y: x - y)
        return create_expression([self, op, expr])


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

    def evaluate(self):
        return self.__value

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


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

    def __str__(self):
        return self.name

    def evaluate(self, **kwargs):
        if self.name in kwargs:
            self.value = kwargs[self.name]
        return self.value


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

    def __str__(self):
        return " " + self.symbol + " "

    def evaluate(self, arg1, arg2):
        return self.function(arg1, arg2)


class Expression(Operand):
    def __init__(self, expr):
        self.expr = []
        variables = []
        for item in expr:
            if isinstance(item, Variable):
                variables.append(item)
                self.expr.append(item)
            elif isinstance(item, Operand) or isinstance(item, Operator):
                self.expr.append(item)
            else:
                new_expr = create_expression(item)
                variables += new_expr.variables
                self.expr.append(new_expr)
            self.variables = []
            self.variables = [var for var in variables
                              if var not in self.variables]
            self.variable_names = filter(lambda x: x.name, self.variables)

    def __str__(self):
        to_string = str()
        to_string += "("
        for item in self.expr:
                to_string += str(item)
        to_string += ")"
        return to_string

    def evaluate(self, **variables):
        for variable in self.variables:
            if variable.name in variables:
                variable.value = variables[variable.name]
        for i in range(0, len(self.expr), 2):
            if isinstance(self.expr[i], Expression):
                operand = self.expr[i].evaluate(**variables)
            else:
                operand = self.expr[i].evaluate()
            if i == 0:
                result = operand
            else:
                result = self.expr[i - 1].evaluate(result, operand)
        return result


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)