timeit

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

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

Решение на Аритметични изрази от Николай Бабулков

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

Към профила на Николай Бабулков

Резултати

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

Код

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


class OpeationsAndNames:
    def __init__(self):
        self.variable_names = tuple(self._get_names())

    def __add__(self, other):
        return Expression((self, Operator('+', lambda x, y: x + y), other))

    def __radd__(self, other):
        return self + other

    def __sub__(self, other):
        return Expression((self, Operator('-', lambda x, y: y - x), other))

    def __rsub__(self, other):
        return Expression((other, Operator('-', lambda x, y: y - x), self))

    def __mul__(self, other):
        return Expression((self, Operator('*', lambda x, y: x * y), other))

    def __rmul__(self, other):
        return Expression((other, Operator('*', lambda x, y: x * y), self))

    def __truediv__(self, other):
        return Expression((self, Operator('/', lambda x, y: y / x), other))

    def __rtruediv__(self, other):
        return Expression((other, Operator('/', lambda x, y: y / x), self))

    def __floordiv__(self, other):
        return Expression((other, Operator('//', lambda x, y: x // y), self))

    def __rfloordiv__(self, other):
        return Expression((self, Operator('//', lambda x, y: x // y), other))

    def __mod__(self, other):
        return Expression((other, Operator('%', lambda x, y: x % y), self))

    def __rmod__(self, other):
        return Expression((self, Operator('%', lambda x, y: x % y), other))

    def __pow__(self, other):
        return Expression((other, Operator('**', lambda x, y: x ** y), self))

    def __rpow__(self, other):
        return Expression((self, Operator('**', lambda x, y: x ** y), other))


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

    def __str__(self):
        return self.__symbol

    def get_func(self):
        return self.__function


def transform(expr):
    if type(expr) is tuple:
            return Expression(expr)
    if isinstance(expr, numbers.Number):
            return Constant(expr)
    return expr


class Expression(OpeationsAndNames):
    def __init__(self, expr):
        self.__expr = [transform(expr[0]), expr[1], transform(expr[2])]
        super().__init__()

    def __str__(self):
        left_str = str(self.__expr[0])
        opr_str = str(self.__expr[1])
        right_str = str(self.__expr[2])
        return '({0} {1} {2})'.format(left_str, opr_str, right_str)

    def _get_names(self):
        names = self.__expr[0]._get_names()
        names.extend(self.__expr[2]._get_names())
        return names

    def evaluate(self, **variables):
        func = self.__expr[1].get_func()
        right_expr = self.__expr[0].evaluate(**variables)
        left_expr = self.__expr[2].evaluate(**variables)
        return func(left_expr, right_expr)


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

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

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

    def _get_names(self):
        return []


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

    def __str__(self):
        return self.__name

    def _get_names(self):
        return [self.__name]

    def evaluate(self, **variables):
        if self.__name in variables:
            return variables[self.__name]


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(expr):
    return Expression(expr)

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

........F..FF......
======================================================================
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: -11 != 11

======================================================================
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: -11 != 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: -4 != 8

----------------------------------------------------------------------
Ran 19 tests in 0.142s

FAILED (failures=3)

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

Николай обнови решението на 20.03.2016 18:46 (преди над 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
class Opeations_and_names:
    def __init__(self):
        self.variable_names = tuple(self._get_names())

    def __str__(self):
        pass

    def _get_names(self):
        pass

    def evaluate(self, **variables):
        pass

    def __add__(self, other):
        return Expression((self, Operator('+', lambda x, y: x + y), other))

    def __radd__(self, other):
        return self + other

    def __sub__(self, other):
        return Expression((self, Operator('-', lambda x, y: y - x), other))

    def __rsub__(self, other):
        return Expression((other, Operator('-', lambda x, y: y - x), self))

    def __mul__(self, other):
        return Expression((self, Operator('*', lambda x, y: x * y), other))

    def __rmul__(self, other):
        return Expression((other, Operator('*', lambda x, y: x * y), self))

    def __truediv__(self, other):
        return Expression((self, Operator('/', lambda x, y: y / x), other))

    def __rtruediv__(self, other):
        return Expression((other, Operator('/', lambda x, y: y / x), self))

    def __floordiv__(self, other):
        return Expression((other, Operator('//', lambda x, y: x // y), self))

    def __rfloordiv__(self, other):
        return Expression((self, Operator('//', lambda x, y: x // y), other))

    def __mod__(self, other):
        return Expression((other, Operator('%', lambda x, y: x % y), self))

    def __rmod__(self, other):
        return Expression((self, Operator('%', lambda x, y: x % y), other))

    def __pow__(self, other):
        return Expression((other, Operator('**', lambda x, y: x ** y), self))

    def __rpow__(self, other):
        return Expression((self, Operator('**', lambda x, y: x ** y), other))


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

    def __str__(self):
        return self.__symbol

    def get_func(self):
        return self.__function


def is_number(number):
    is_float = type(number) is float
    is_int = type(number) is int
    is_complex = type(number) is complex
    return is_int or is_float or is_complex


def transform(expr):
    if type(expr) is tuple:
            return Expression(expr)
    if is_number(expr):
            return Constant(expr)
    return expr


class Expression(Opeations_and_names):
    def __init__(self, expr):
        self.__expr = [transform(expr[0]), expr[1], transform(expr[2])]
        super().__init__()

    def __str__(self):
        left_str = str(self.__expr[0])
        opr_str = str(self.__expr[1])
        right_str = str(self.__expr[2])
        return '({0} {1} {2})'.format(left_str, opr_str, right_str)

    def _get_names(self):
        names = self.__expr[0]._get_names()
        names.extend(self.__expr[2]._get_names())
        return names

    def evaluate(self, **variables):
        func = self.__expr[1].get_func()
        right_expr = self.__expr[0].evaluate(**variables)
        left_expr = self.__expr[2].evaluate(**variables)
        return func(left_expr, right_expr)


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

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

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

    def _get_names(self):
        return []


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

    def __str__(self):
        return self.__name

    def _get_names(self):
        return [self.__name]

    def evaluate(self, **variables):
        if self.__name in variables:
            return variables[self.__name]


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(expr):
    return Expression(expr)
  • Класовете в python трябва да се кръщават с UpperCamelCase имена.
  • Вместо is_number може да погледнеш Number от numbers модула.
  • Сигурен ли си че имаш нужда от трите метода, който имат само pass в телата си?

Николай обнови решението на 21.03.2016 00:25 (преди над 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
import numbers


class OpeationsAndNames:
    def __init__(self):
        self.variable_names = tuple(self._get_names())

    def __add__(self, other):
        return Expression((self, Operator('+', lambda x, y: x + y), other))

    def __radd__(self, other):
        return self + other

    def __sub__(self, other):
        return Expression((self, Operator('-', lambda x, y: y - x), other))

    def __rsub__(self, other):
        return Expression((other, Operator('-', lambda x, y: y - x), self))

    def __mul__(self, other):
        return Expression((self, Operator('*', lambda x, y: x * y), other))

    def __rmul__(self, other):
        return Expression((other, Operator('*', lambda x, y: x * y), self))

    def __truediv__(self, other):
        return Expression((self, Operator('/', lambda x, y: y / x), other))

    def __rtruediv__(self, other):
        return Expression((other, Operator('/', lambda x, y: y / x), self))

    def __floordiv__(self, other):
        return Expression((other, Operator('//', lambda x, y: x // y), self))

    def __rfloordiv__(self, other):
        return Expression((self, Operator('//', lambda x, y: x // y), other))

    def __mod__(self, other):
        return Expression((other, Operator('%', lambda x, y: x % y), self))

    def __rmod__(self, other):
        return Expression((self, Operator('%', lambda x, y: x % y), other))

    def __pow__(self, other):
        return Expression((other, Operator('**', lambda x, y: x ** y), self))

    def __rpow__(self, other):
        return Expression((self, Operator('**', lambda x, y: x ** y), other))


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

    def __str__(self):
        return self.__symbol

    def get_func(self):
        return self.__function


def transform(expr):
    if type(expr) is tuple:
            return Expression(expr)
    if isinstance(expr, numbers.Number):
            return Constant(expr)
    return expr


class Expression(OpeationsAndNames):
    def __init__(self, expr):
        self.__expr = [transform(expr[0]), expr[1], transform(expr[2])]
        super().__init__()

    def __str__(self):
        left_str = str(self.__expr[0])
        opr_str = str(self.__expr[1])
        right_str = str(self.__expr[2])
        return '({0} {1} {2})'.format(left_str, opr_str, right_str)

    def _get_names(self):
        names = self.__expr[0]._get_names()
        names.extend(self.__expr[2]._get_names())
        return names

    def evaluate(self, **variables):
        func = self.__expr[1].get_func()
        right_expr = self.__expr[0].evaluate(**variables)
        left_expr = self.__expr[2].evaluate(**variables)
        return func(left_expr, right_expr)


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

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

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

    def _get_names(self):
        return []


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

    def __str__(self):
        return self.__name

    def _get_names(self):
        return [self.__name]

    def evaluate(self, **variables):
        if self.__name in variables:
            return variables[self.__name]


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(expr):
    return Expression(expr)