timeit

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

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

Решение на Аритметични изрази от Ивелина Христова

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

Към профила на Ивелина Христова

Резултати

  • 7 точки от тестове
  • 1 отнета точка
  • 6 точки общо
  • 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
class Constant:
    def __init__(self, value):
        self.value = value

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

    def __add__(self, other):
        operator = create_operator('+', lambda lhs, rhs: lhs + rhs)
        return create_expression((self, operator, other))

    def __sub__(self, other):
        operator = create_operator('-', lambda lhs, rhs: lhs - rhs)
        return create_expression((self, operator, other))

    def __mul__(self, other):
        operator = create_operator('*', lambda lhs, rhs: lhs * rhs)
        return create_expression((self, operator, other))

    def __truediv__(self, other):
        operator = create_operator('/', lambda lhs, rhs: lhs / rhs)
        return create_expression((self, operator, other))

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


def create_constant(value):
    return Constant(value)

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

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

    def __add__(self, other):
        operator = create_operator('+', lambda lhs, rhs: lhs + rhs)
        return create_expression((self, operator, other))

    def __sub__(self, other):
        operator = create_operator('-', lambda lhs, rhs: lhs - rhs)
        return create_expression((self, operator, other))

    def __mul__(self, other):
        operator = create_operator('*', lambda lhs, rhs: lhs * rhs)
        return create_expression((self, operator, other))

    def __truediv__(self, other):
        operator = create_operator('/', lambda lhs, rhs: lhs / rhs)
        return create_expression((self, operator, other))

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

def create_variable(name):
    return Variable(name)


class Operator:

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

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

def create_operator(symbol, func):
    return Operator(symbol, func)


class Expression:
    variable_names = list()

    def __init__(self, body):
        self.v1 = body[0]
        self.v2 = body[2]
        self.operator = body[1]

    def evaluate(self, **variables):
        value1 = self.v1
        value2 = self.v2

        while isinstance(value1, tuple):
            expr = Expression(value1)
            value1 = expr.evaluate(**variables)
        while isinstance(value2, tuple):
            expr = Expression(value2)
            value2 = expr.evaluate(**variables)

        if isinstance(value1, Constant) or isinstance(value1, Variable):
            if isinstance(value1, Variable):
                self.variable_names.append(value1.name)
            value1 = value1.evaluate(**variables)
            
        if isinstance(value2, Constant) or isinstance(value2, Variable):
            if isinstance(value2, Variable):
                self.variable_names.append(value2.name)
            value2 = value2.evaluate(**variables)

        return self.operator.calc(value1, value2)

    def __str__(self):
        value1 = self.v1
        value2 = self.v2

        string = '('
        while isinstance(value1, tuple):
            expr = Expression(value1)
            value1 = expr.__str__()
        string += '{} {} '.format(value1, self.operator)
        while isinstance(value2, tuple):
            expr = Expression(self.v2)
            value2 = expr.__str__()
        string += '{})'.format(value2)
        return string

def create_expression(body):
    return Expression(body)

plus = create_operator('+', lambda lhs, rhs: lhs + rhs)
x = create_variable('x')
print(plus.calc(5, 6))
print(plus)

expr = create_expression((x, plus, (create_constant(9), plus, x)))
print(expr.evaluate(x=5))
print(expr.variable_names)
print(expr.variable_names == ('x',))
print(expr)

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

11
+
19
['x', 'x']
False
(x + (9 + x))
..EEE..........EE..
======================================================================
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 ** or pow(): 'Variable' and 'Variable'

----------------------------------------------------------------------
Ran 19 tests in 0.116s

FAILED (errors=5)

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

Ивелина обнови решението на 21.03.2016 02: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
class Constant:
    def __init__(self, value):
        self.value = value

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

    def __add__(self, other):
        operator = create_operator('+', lambda lhs, rhs: lhs + rhs)
        return create_expression((self, operator, other))

    def __sub__(self, other):
        operator = create_operator('-', lambda lhs, rhs: lhs - rhs)
        return create_expression((self, operator, other))

    def __mul__(self, other):
        operator = create_operator('*', lambda lhs, rhs: lhs * rhs)
        return create_expression((self, operator, other))

    def __truediv__(self, other):
        operator = create_operator('/', lambda lhs, rhs: lhs / rhs)
        return create_expression((self, operator, other))

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


def create_constant(value):
    return Constant(value)

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

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

    def __add__(self, other):
        operator = create_operator('+', lambda lhs, rhs: lhs + rhs)
        return create_expression((self, operator, other))

    def __sub__(self, other):
        operator = create_operator('-', lambda lhs, rhs: lhs - rhs)
        return create_expression((self, operator, other))

    def __mul__(self, other):
        operator = create_operator('*', lambda lhs, rhs: lhs * rhs)
        return create_expression((self, operator, other))

    def __truediv__(self, other):
        operator = create_operator('/', lambda lhs, rhs: lhs / rhs)
        return create_expression((self, operator, other))

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

def create_variable(name):
    return Variable(name)


class Operator:

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

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

def create_operator(symbol, func):
    return Operator(symbol, func)


class Expression:
    variable_names = list()

    def __init__(self, body):
        self.v1 = body[0]
        self.v2 = body[2]
        self.operator = body[1]

    def evaluate(self, **variables):
        value1 = self.v1
        value2 = self.v2

        while isinstance(value1, tuple):
            expr = Expression(value1)
            value1 = expr.evaluate(**variables)
        while isinstance(value2, tuple):
            expr = Expression(value2)
            value2 = expr.evaluate(**variables)

        if isinstance(value1, Constant) or isinstance(value1, Variable):
            if isinstance(value1, Variable):
                self.variable_names.append(value1.name)
            value1 = value1.evaluate(**variables)
            
        if isinstance(value2, Constant) or isinstance(value2, Variable):
            if isinstance(value2, Variable):
                self.variable_names.append(value2.name)
            value2 = value2.evaluate(**variables)

        return self.operator.calc(value1, value2)

    def __str__(self):
        value1 = self.v1
        value2 = self.v2

        string = '('
        while isinstance(value1, tuple):
            expr = Expression(value1)
            value1 = expr.__str__()
        string += '{} {} '.format(value1, self.operator)
        while isinstance(value2, tuple):
            expr = Expression(self.v2)
            value2 = expr.__str__()
        string += '{})'.format(value2)
        return string

def create_expression(body):
    return Expression(body)

plus = create_operator('+', lambda lhs, rhs: lhs + rhs)
x = create_variable('x')
print(plus.calc(5, 6))
print(plus)

expr = create_expression((x, plus, (create_constant(9), plus, x)))
print(expr.evaluate(x=5))
print(expr.variable_names)
print(expr.variable_names == ('x',))
print(expr)