timeit

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

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

Решение на Аритметични изрази от Яница Велевска

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

Към профила на Яница Велевска

Резултати

  • 6 точки от тестове
  • 1 отнета точка
  • 5 точки общо
  • 11 успешни тест(а)
  • 8 неуспешни тест(а)

Код

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
import collections


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

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

    def __add__(self, other):
        op = operator('+', lambda x, y: x + y)
        return expression((self, op, other))

    def __sub__(self, other):
        op = operator('-', lambda x, y: x - y)
        return expression((self, op, other))

    def __mul__(self, other):
        op = operator('*', lambda x, y: x * y)
        return expression((self, op, other))

    def __truediv__(self, other):
        op = operator('/', lambda x, y: x / y)
        return expression((self, op, other))

    def evaluate(self):
        return self.value


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

    def __str__(self):
        return self.name

    def __add__(self, other):
        op = operator('+', lambda x, y: x + y)
        return expression((self, op, other))

    def __sub__(self, other):
        op = operator('-', lambda x, y: x - y)
        return expression((self, op, other))

    def __mul__(self, other):
        op = operator('*', lambda x, y: x * y)
        return expression((self, op, other))

    def __truediv__(self, other):
        op = operator('/', lambda x, y: x / y)
        return expression((self, op, other))

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


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

    def __str__(self):
        return self.symbol


class expression:
    def __init__(self, exp_struct):
        self.exp_struct = exp_struct

    def __add__(self, other):
        op = operator('+', lambda x, y: x + y)
        return expression((self, op, other))

    def __sub__(self, other):
        op = operator('-', lambda x, y: x - y)
        return expression((self, op, other))

    def __mul__(self, other):
        op = operator('*', lambda x, y: x * y)
        return expression((self, op, other))

    def __truediv__(self, other):
        op = operator('/', lambda x, y: x / y)
        return expression((self, op, other))

    def __str__(self):
        return self.convert()

    def convert(self):
        res = ""
        for a in self.exp_struct:
            if a.__class__ is variable:
                res = res + a.name
            elif a.__class__ is const:
                res = res + str(a.value)
            elif a.__class__ is int:
                res = res + str(a)
            elif a.__class__ is operator:
                res = res + ' ' + a.symbol + ' '
            elif isinstance(a, collections.Iterable):
                exp = create_expression(a)
                res = res + exp.convert()
        return res

    def evaluate(self, **variables):
        for a in self.variable_names:
            exec("{0} = {1}".format(a, variables[a]))
        return eval(self.convert())

    @property
    def variable_names(self):
        res = []
        for a in self.exp_struct:
            if a.__class__ is variable:
                res.append(a.name)
            if isinstance(a, collections.Iterable):
                for b in a:
                    if b.__class__ is variable:
                        res.append(b.name)
        return res


def create_variable(name):
    return variable(name)


def create_constant(value):
    return const(value)


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


def create_expression(exp_struct):
    return expression(exp_struct)

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

..EEE....EF...FEE..
======================================================================
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 'const'

======================================================================
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_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
NameError: name 'x' is not defined

======================================================================
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
  File "<string>", line 1
    -
     ^
SyntaxError: unexpected EOF while parsing

======================================================================
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_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 0.146s

FAILED (failures=2, errors=6)

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

Яница обнови решението на 19.03.2016 19:50 (преди над 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
import collections


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

    def __add__(self, other):
        op = operator('+', lambda x, y: x + y)
        return expression((self, op, other))

    def __sub__(self, other):
        op = operator('-', lambda x, y: x - y)
        return expression((self, op, other))

    def __mul__(self, other):
        op = operator('*', lambda x, y: x * y)
        return expression((self, op, other))

    def __truediv__(self, other):
        op = operator('/', lambda x, y: x / y)
        return expression((self, op, other))

    def evaluate(self):
        return self.value


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

    def __add__(self, other):
        op = operator('+', lambda x, y: x + y)
        return expression((self, op, other))

    def __sub__(self, other):
        op = operator('-', lambda x, y: x - y)
        return expression((self, op, other))

    def __mul__(self, other):
        op = operator('*', lambda x, y: x * y)
        return expression((self, op, other))

    def __truediv__(self, other):
        op = operator('/', lambda x, y: x / y)
        return expression((self, op, other))

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


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


class expression:
    def __init__(self, exp_struct):
        self.exp_struct = exp_struct

    def __add__(self, other):
        op = operator('+', lambda x, y: x + y)
        return expression((self, op, other))

    def __sub__(self, other):
        op = operator('-', lambda x, y: x - y)
        return expression((self, op, other))

    def __mul__(self, other):
        op = operator('*', lambda x, y: x * y)
        return expression((self, op, other))

    def __truediv__(self, other):
        op = operator('/', lambda x, y: x / y)
        return expression((self, op, other))

    def __str__(self):
        return self.convert()

    def convert(self):
        res = ""
        for a in self.exp_struct:
            if a.__class__ is variable:
                res = res + a.name
            elif a.__class__ is const:
                res = res + str(a.value)
            elif a.__class__ is int:
                res = res + str(a)
            elif a.__class__ is operator:
                res = res + ' ' + a.symbol + ' '
            elif isinstance(a, collections.Iterable):
                exp = create_expression(a)
                res = res + exp.convert()
        return res

    def evaluate(self, **variables):
        for a in self.variable_names:
            exec("{0} = {1}".format(a, variables[a]))
        return eval(self.convert())

    @property
    def variable_names(self):
        res = []
        for a in self.exp_struct:
            if a.__class__ is variable:
                res.append(a.name)
            if isinstance(a, collections.Iterable):
                for b in a:
                    if b.__class__ is variable:
                        res.append(b.name)
        return res


def create_variable(name):
    return variable(name)


def create_constant(value):
    return const(value)


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


def create_expression(exp_struct):
    return expression(exp_struct)

Яница обнови решението на 20.03.2016 13:59 (преди над 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
import collections


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

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

    def __add__(self, other):
        op = operator('+', lambda x, y: x + y)
        return expression((self, op, other))

    def __sub__(self, other):
        op = operator('-', lambda x, y: x - y)
        return expression((self, op, other))

    def __mul__(self, other):
        op = operator('*', lambda x, y: x * y)
        return expression((self, op, other))

    def __truediv__(self, other):
        op = operator('/', lambda x, y: x / y)
        return expression((self, op, other))

    def evaluate(self):
        return self.value


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

    def __str__(self):
        return self.name

    def __add__(self, other):
        op = operator('+', lambda x, y: x + y)
        return expression((self, op, other))

    def __sub__(self, other):
        op = operator('-', lambda x, y: x - y)
        return expression((self, op, other))

    def __mul__(self, other):
        op = operator('*', lambda x, y: x * y)
        return expression((self, op, other))

    def __truediv__(self, other):
        op = operator('/', lambda x, y: x / y)
        return expression((self, op, other))

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


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

    def __str__(self):
        return self.symbol


class expression:
    def __init__(self, exp_struct):
        self.exp_struct = exp_struct

    def __add__(self, other):
        op = operator('+', lambda x, y: x + y)
        return expression((self, op, other))

    def __sub__(self, other):
        op = operator('-', lambda x, y: x - y)
        return expression((self, op, other))

    def __mul__(self, other):
        op = operator('*', lambda x, y: x * y)
        return expression((self, op, other))

    def __truediv__(self, other):
        op = operator('/', lambda x, y: x / y)
        return expression((self, op, other))

    def __str__(self):
        return self.convert()

    def convert(self):
        res = ""
        for a in self.exp_struct:
            if a.__class__ is variable:
                res = res + a.name
            elif a.__class__ is const:
                res = res + str(a.value)
            elif a.__class__ is int:
                res = res + str(a)
            elif a.__class__ is operator:
                res = res + ' ' + a.symbol + ' '
            elif isinstance(a, collections.Iterable):
                exp = create_expression(a)
                res = res + exp.convert()
        return res

    def evaluate(self, **variables):
        for a in self.variable_names:
            exec("{0} = {1}".format(a, variables[a]))
        return eval(self.convert())

    @property
    def variable_names(self):
        res = []
        for a in self.exp_struct:
            if a.__class__ is variable:
                res.append(a.name)
            if isinstance(a, collections.Iterable):
                for b in a:
                    if b.__class__ is variable:
                        res.append(b.name)
        return res


def create_variable(name):
    return variable(name)


def create_constant(value):
    return const(value)


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


def create_expression(exp_struct):
    return expression(exp_struct)
  • Никога не ползвай eval и exec

  • Конвенцията в python е имената на класовете да са в UpperCammelCase, а не в snake_case.

  • В предефинираните ти оператори нямаш нужда от op променливата, можеш директно да inline-неш извикването на operator.
  • В convert expression знае кои класове го наследяват и как да се справи с всеки от тях. А ако това бяха 500 класа? А ако искам да напиша нов клас, който наследява твоя expression и няма как да променя твоя код? За такива неща duck-typing-а помага много.
  • Когато правиш for цикъл по списък само, за да създадеш нов списък с елементи производни на елементите на първия списък почти със сигурност всъщност исках да направиш list comprehension.