Форум программистов, компьютерный форум, киберфорум
Python: Решение задач
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск  
 
 
Рейтинг 4.75/16: Рейтинг темы: голосов - 16, средняя оценка - 4.75
34
0 / 0 / 0
Регистрация: 10.02.2023
Сообщений: 6

Программа, которая вычисляет выражение, состоящее из чисел, знаков

12.12.2024, 07:24. Показов 5177. Ответов 90
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Уровень D.Напишите программу, которая вычисляет выражение, состоящее из чисел, знаков (допускаются знаки «+», «–», «*» и «/») и круглых скобок. Выражение вводится как символьная строка, все числа целые. Операция «/» выполняется как целочисленное деление (div).
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
12.12.2024, 07:24
Ответы с готовыми решениями:

Напишите программу, которая вычисляет выражение, состоящее из трех чисел и двух знаков
Помогите, пожалуйста. Напишите программу, которая вычисляет выражение, состоящее из трёх чисел и двух знаков (допускаются знаки «+»,...

Напишите программу, которая вычисляет выражение, состоящее из трех чисел и двух знаков
Напишите программу, которая вычисляет выражение, состоящее из трех чисел и двух знаков (допускаются только знаки «+» или «–»). Выражение...

Напишите программу, которая вычисляет выражение, состоящее из трех чисел и двух знаков
Напишите программу, которая вычисляет выражение, состоящее из трех чисел и двух знаков (допускаются только знаки «+» или «–»). Выражение...

90
 Аватар для Aviz__
2762 / 2069 / 510
Регистрация: 17.02.2014
Сообщений: 9,507
16.12.2024, 16:06
Студворк — интернет-сервис помощи студентам
34, идея тут, не самая красивая:
Python
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
def evaluate_expression(expr: str) -> int:
 
    def parse_term(index: int) -> (int, int):
        result, index = parse_factor(index)
 
        while index < len(expr) and expr[index] in ('*', '/'):
            op = expr[index]
            index += 1
            next_factor, index = parse_factor(index)
            if op == '*':
                result *= next_factor
            elif op == '/':
                result //= next_factor
 
        return result, index
 
    def parse_factor(index: int) -> (int, int):
        if expr[index].isdigit():
            num = 0
            while index < len(expr) and expr[index].isdigit():
                num = num * 10 + int(expr[index])
                index += 1
            return num, index
        elif expr[index] == '(':
            index += 1  # Пропускаем '('
            result, index = parse_expression(index)
            index += 1  # Пропускаем ')'
            return result, index
 
    def parse_expression(index: int) -> (int, int):
        result, index = parse_term(index)
 
        while index < len(expr) and expr[index] in ('+', '-'):
            op = expr[index]
            index += 1
            next_term, index = parse_term(index)
            if op == '+':
                result += next_term
            elif op == '-':
                result -= next_term
 
        return result, index
 
    expr = expr.replace(' ', '')
    result, _ = parse_expression(0)
    return result
 
 
if __name__ == "__main__":
    expression = "13 - 15"
    result = evaluate_expression(expression)
    print(f"Результат вычисления: {result}")
0
90 / 125 / 28
Регистрация: 17.10.2010
Сообщений: 1,338
16.12.2024, 17:39
Python
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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
from tkinter import *
 
 
class Window:
    def __init__(self, width, height, title="FirstTK", resizable=(False, True), icon=None):
        self.root = Tk()  # корневая переменная которая хранит с себе экземпляр класса Tk
        self.root.title(title)
        self.root.geometry(f"{width}x{height}+200+200")
        self.root.resizable(resizable[0], resizable[1])
        if icon:
            self.root.iconbitmap(icon)
        self.label_out = Label(self.root, text='0', font=("Verdana", 10, "bold"))
 
    def run(self):
        self.draw_widgets()
        self.root.mainloop()
 
    def draw_widgets(self):
        self.draw_menu()
        self.label_out.place(x=30, y=10)
        Button(self.root, width=3, height=2, text='1', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('1')).place(x=30, y=30)
        Button(self.root, width=3, height=2, text='2', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('2')).place(x=75, y=30)
        Button(self.root, width=3, height=2, text='3', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('3')).place(x=120, y=30)
        Button(self.root, width=3, height=2, text='4', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('4')).place(x=30, y=80)
        Button(self.root, width=3, height=2, text='5', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('5')).place(x=75, y=80)
        Button(self.root, width=3, height=2, text='6', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('6')).place(x=120, y=80)
        Button(self.root, width=3, height=2, text='7', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('7')).place(x=30, y=130)
        Button(self.root, width=3, height=2, text='8', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('8')).place(x=75, y=130)
        Button(self.root, width=3, height=2, text='9', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('9')).place(x=120, y=130)
        Button(self.root, width=3, height=2, text='0', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('0')).place(x=30, y=180)
        Button(self.root, width=3, height=2, text='+', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('+')).place(x=75, y=180)
        Button(self.root, width=3, height=2, text='-', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('-')).place(x=120, y=180)
        Button(self.root, width=3, height=2, text='*', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('*')).place(x=30, y=230)
        Button(self.root, width=3, height=2, text='/', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('/')).place(x=75, y=230)
        Button(self.root, width=3, height=2, text='(', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('(')).place(x=120, y=230)
        Button(self.root, width=3, height=2, text=')', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button(')')).place(x=30, y=280)
        Button(self.root, width=3, height=2, text='=', font=("Verdana", 12, "bold"),
               command=self.output).place(x=75, y=280)
        Button(self.root, width=3, height=2, text='CL', font=("Verdana", 12, "bold"),
               command=self.clear).place(x=120, y=280)
        Button(self.root, width=3, height=2, text='x^y', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('^')).place(x=75, y=230)
 
    def draw_menu(self):
        menu_bar = Menu(self.root)
        file_menu = Menu(menu_bar, tearoff=0)
        color_menu = Menu(file_menu, tearoff=0)
        color_menu.add_command(label='Зеленый', command=lambda: self.change_color('green'))
        color_menu.add_command(label='Красный', command=lambda: self.change_color('red'))
        color_menu.add_command(label='Сброс', command=lambda: self.change_color('white'))
        menu_bar.add_cascade(label='Настройки', menu=file_menu)
        file_menu.add_cascade(label='Цвет фона', menu=color_menu)
        self.root.configure(menu=menu_bar)
 
    def change_color(self, color):
        self.root.configure(bg=color)
 
    def test_button(self, val):
        if self.label_out.cget("text") in ('0', 'ERROR', 'ZERO DIVISION'):
            self.label_out.config(text=val)
        else:
            if (val == '+' and self.label_out.cget("text")[-1] == '+') or (
                    val == '-' and self.label_out.cget("text")[-2] == '-'):
                return
            else:
                old_label_val = self.label_out.cget("text")
                new_val = old_label_val + val
                self.label_out.config(text=new_val)
 
    def solve_main(self):
        try:
            str_ = self.label_out.cget("text")
            token_list = []
            token = []
            for i in range(len(str_)):
                if str_[i].isdigit():
                    token += [str_[i]]
                else:
                    token_list += [token]
                    token = []
                    token += [str_[i]]
                    token_list += [token]
                    token = []
            if len(token):
                token_list += [token]
            result = list(filter(lambda a: a, map(lambda x: ''.join(x), token_list)))
 
            def to_number(x):
                return int(x) if x.isdigit() else x
 
            result2 = list(map(to_number, result))
            for i in range(len(result2) - 1):
                if not isinstance(result2[i], int) and result2[i + 1] == '-':
                    result2[i + 2] = ~result2[i + 2] + 1
                    result2[i + 1] = None
            if result2[0] == '-':
                result2[1] = ~result2[1] + 1
                result2.pop(0)
            final_result1 = list(filter(lambda x: x is not None, result2))
            test_null = False
            for i in range(len(final_result1) - 1):
                if final_result1[i] == '/' and not final_result1[i + 1]:
                    test_null = True
                    break
 
            if test_null:
                return 'ZERO DIVISION'
 
            def solve(s):
                def seek(stack):
                    if stack:
                        return stack[-1]
 
                ops = {
                    '+': 1,
                    '-': 1,
                    '/': 2,
                    '*': 2,
                    '^': 2
                }
 
                stack = []
                out = []
 
                for i in s:
                    if isinstance(i, int):
                        out.append(i)
                    elif i in ops:
                        while stack and seek(stack) != '(' and ops[seek(stack)] >= ops[i]:
                            out.append(stack.pop())
                        stack.append(i)
                    elif i == '(':
                        stack.append(i)
                    elif i == ')':
                        while stack and seek(stack) != '(':
                            out.append(stack.pop())
                        if stack and seek(stack) == '(':
                            stack.pop()
 
                while stack:
                    out.append(stack.pop())
                stack2 = []
                for i in out:
                    if isinstance(i, int):
                        stack2 += [i]
                    else:
                        a = stack2[-2:]
                        stack2.pop()
                        stack2.pop()
                        if i == '+':
                            stack2 += [sum(a)]
                        if i == '*':
                            stack2 += [a[0] * a[1]]
                        if i == '-':
                            stack2 += [a[0] - a[1]]
                        if i == '/':
                            stack2 += [a[0] / a[1]]
                        if i == '^':
                                stack2 += [a[0] ** a[1]]
                return stack2[0]
 
            return solve(final_result1)
        except IndexError:
            return 'ERROR'
        except TypeError:
            return 'ERROR'
 
    def output(self):
        self.label_out.config(text=str(self.solve_main()))
 
    def clear(self):
        self.label_out.config(text='0')
 
 
if __name__ == "__main__":
    window = Window(250, 380)
    window.run()
Добавлено через 10 минут
Вопрос как делать кнопку извлечения корня n-той степени остается открытым.
0
Эксперт PythonЭксперт Java
19530 / 11067 / 2931
Регистрация: 21.10.2017
Сообщений: 23,294
16.12.2024, 17:49
isaak, сначала напиши функцию, которая извлекает корень n-й степени.
Напишешь - помогу оформить это в гуйне.
0
Любознательный
 Аватар для YuS_2
7407 / 2260 / 361
Регистрация: 10.03.2016
Сообщений: 5,216
16.12.2024, 18:06
Цитата Сообщение от isaak Посмотреть сообщение
Вопрос как делать кнопку извлечения корня n-той степени остается открытым.
Так в чем проблема-то?
кнопка делается по аналогии с остальными. Алгоритмы... их полно, начиная от вариантов с модулями и заканчивая вариантами без них.
Пример.
варианты:
Python
1
2
3
pow(x,1/y)
math.pow(x,1/y)
x**(1/y)
0
90 / 125 / 28
Регистрация: 17.10.2010
Сообщений: 1,338
16.12.2024, 22:32
В чем ошибка не понимаю????
Python
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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
from tkinter import *
 
 
class Window:
    def __init__(self, width, height, title="FirstTK", resizable=(False, True), icon=None):
        self.root = Tk()  # корневая переменная которая хранит с себе экземпляр класса Tk
        self.root.title(title)
        self.root.geometry(f"{width}x{height}+200+200")
        self.root.resizable(resizable[0], resizable[1])
        if icon:
            self.root.iconbitmap(icon)
        self.label_out = Label(self.root, text='0', font=("Verdana", 10, "bold"))
 
    def run(self):
        self.draw_widgets()
        self.root.mainloop()
 
    def draw_widgets(self):
        self.draw_menu()
        self.label_out.place(x=30, y=10)
        Button(self.root, width=3, height=2, text='1', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('1')).place(x=30, y=30)
        Button(self.root, width=3, height=2, text='2', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('2')).place(x=75, y=30)
        Button(self.root, width=3, height=2, text='3', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('3')).place(x=120, y=30)
        Button(self.root, width=3, height=2, text='4', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('4')).place(x=30, y=80)
        Button(self.root, width=3, height=2, text='5', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('5')).place(x=75, y=80)
        Button(self.root, width=3, height=2, text='6', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('6')).place(x=120, y=80)
        Button(self.root, width=3, height=2, text='7', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('7')).place(x=30, y=130)
        Button(self.root, width=3, height=2, text='8', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('8')).place(x=75, y=130)
        Button(self.root, width=3, height=2, text='9', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('9')).place(x=120, y=130)
        Button(self.root, width=3, height=2, text='0', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('0')).place(x=30, y=180)
        Button(self.root, width=3, height=2, text='+', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('+')).place(x=75, y=180)
        Button(self.root, width=3, height=2, text='-', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('-')).place(x=120, y=180)
        Button(self.root, width=3, height=2, text='*', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('*')).place(x=30, y=230)
        Button(self.root, width=3, height=2, text='/', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('/')).place(x=75, y=230)
        Button(self.root, width=3, height=2, text='(', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('(')).place(x=120, y=230)
        Button(self.root, width=3, height=2, text=')', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button(')')).place(x=30, y=280)
        Button(self.root, width=3, height=2, text='=', font=("Verdana", 12, "bold"),
               command=self.output).place(x=75, y=280)
        Button(self.root, width=3, height=2, text='CL', font=("Verdana", 12, "bold"),
               command=self.clear).place(x=120, y=280)
        Button(self.root, width=3, height=2, text='x^y', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('^')).place(x=30, y=320)
        Button(self.root, width=3, height=2, text='x^(1/y)', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('^(1/y)')).place(x=320, y=30)
    def draw_menu(self):
        menu_bar = Menu(self.root)
        file_menu = Menu(menu_bar, tearoff=0)
        color_menu = Menu(file_menu, tearoff=0)
        color_menu.add_command(label='Зеленый', command=lambda: self.change_color('green'))
        color_menu.add_command(label='Красный', command=lambda: self.change_color('red'))
        color_menu.add_command(label='Сброс', command=lambda: self.change_color('white'))
        menu_bar.add_cascade(label='Настройки', menu=file_menu)
        file_menu.add_cascade(label='Цвет фона', menu=color_menu)
        self.root.configure(menu=menu_bar)
 
    def change_color(self, color):
        self.root.configure(bg=color)
 
    def test_button(self, val):
        if self.label_out.cget("text") in ('0', 'ERROR', 'ZERO DIVISION'):
            self.label_out.config(text=val)
        else:
            if (val == '+' and self.label_out.cget("text")[-1] == '+') or (
                    val == '-' and self.label_out.cget("text")[-2] == '-'):
                return
            else:
                old_label_val = self.label_out.cget("text")
                new_val = old_label_val + val
                self.label_out.config(text=new_val)
 
    def solve_main(self):
        try:
            str_ = self.label_out.cget("text")
            token_list = []
            token = []
            for i in range(len(str_)):
                if str_[i].isdigit():
                    token += [str_[i]]
                else:
                    token_list += [token]
                    token = []
                    token += [str_[i]]
                    token_list += [token]
                    token = []
            if len(token):
                token_list += [token]
            result = list(filter(lambda a: a, map(lambda x: ''.join(x), token_list)))
 
            def to_number(x):
                return int(x) if x.isdigit() else x
 
            result2 = list(map(to_number, result))
            for i in range(len(result2) - 1):
                if not isinstance(result2[i], int) and result2[i + 1] == '-':
                    result2[i + 2] = ~result2[i + 2] + 1
                    result2[i + 1] = None
            if result2[0] == '-':
                result2[1] = ~result2[1] + 1
                result2.pop(0)
            final_result1 = list(filter(lambda x: x is not None, result2))
            test_null = False
            for i in range(len(final_result1) - 1):
                if final_result1[i] == '/' and not final_result1[i + 1]:
                    test_null = True
                    break
 
            if test_null:
                return 'ZERO DIVISION'
 
            def solve(s):
                def seek(stack):
                    if stack:
                        return stack[-1]
 
                ops = {
                    '+': 1,
                    '-': 1,
                    '/': 2,
                    '*': 2,
                    '^': 2,
                    '^1/y': 2
                }
 
                stack = []
                out = []
 
                for i in s:
                    if isinstance(i, int):
                        out.append(i)
                    elif i in ops:
                        while stack and seek(stack) != '(' and ops[seek(stack)] >= ops[i]:
                            out.append(stack.pop())
                        stack.append(i)
                    elif i == '(':
                        stack.append(i)
                    elif i == ')':
                        while stack and seek(stack) != '(':
                            out.append(stack.pop())
                        if stack and seek(stack) == '(':
                            stack.pop()
 
                while stack:
                    out.append(stack.pop())
                stack2 = []
                for i in out:
                    if isinstance(i, int):
                        stack2 += [i]
                    else:
                        a = stack2[-2:]
                        stack2.pop()
                        stack2.pop()
                        if i == '+':
                            stack2 += [sum(a)]
                        if i == '*':
                            stack2 += [a[0] * a[1]]
                        if i == '-':
                            stack2 += [a[0] - a[1]]
                        if i == '/':
                            stack2 += [a[0] / a[1]]
                        if i == '^':
                            stack2 += [a[0] ** a[1]]
                        if i == '^1/y':
                            stack2 += [a[0] ** 1/(a[1])]
                return stack2[0]
 
            return solve(final_result1)
        except IndexError:
            return 'ERROR'
        except TypeError:
            return 'ERROR'
 
    def output(self):
        self.label_out.config(text=str(self.solve_main()))
 
    def clear(self):
        self.label_out.config(text='0')
 
 
if __name__ == "__main__":
    window = Window(250, 380)
    window.run()
0
Эксперт PythonЭксперт Java
19530 / 11067 / 2931
Регистрация: 21.10.2017
Сообщений: 23,294
16.12.2024, 22:36
То же самое, что было со степенью. Алгоритм подразумевает, что операция - это ОДИН символ. А не ^1/y
1
90 / 125 / 28
Регистрация: 17.10.2010
Сообщений: 1,338
16.12.2024, 22:54
Не понял я как записать здесь корень одним символом?
0
Эксперт PythonЭксперт Java
19530 / 11067 / 2931
Регистрация: 21.10.2017
Сообщений: 23,294
16.12.2024, 22:57
На.
0
90 / 125 / 28
Регистрация: 17.10.2010
Сообщений: 1,338
16.12.2024, 22:58
Координаты какие ставить?
Python
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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
from tkinter import *
 
 
class Window:
    def __init__(self, width, height, title="FirstTK", resizable=(False, True), icon=None):
        self.root = Tk()  # корневая переменная которая хранит с себе экземпляр класса Tk
        self.root.title(title)
        self.root.geometry(f"{width}x{height}+200+200")
        self.root.resizable(resizable[0], resizable[1])
        if icon:
            self.root.iconbitmap(icon)
        self.label_out = Label(self.root, text='0', font=("Verdana", 10, "bold"))
 
    def run(self):
        self.draw_widgets()
        self.root.mainloop()
 
    def draw_widgets(self):
        self.draw_menu()
        self.label_out.place(x=30, y=10)
        Button(self.root, width=3, height=2, text='1', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('1')).place(x=30, y=30)
        Button(self.root, width=3, height=2, text='2', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('2')).place(x=75, y=30)
        Button(self.root, width=3, height=2, text='3', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('3')).place(x=120, y=30)
        Button(self.root, width=3, height=2, text='4', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('4')).place(x=30, y=80)
        Button(self.root, width=3, height=2, text='5', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('5')).place(x=75, y=80)
        Button(self.root, width=3, height=2, text='6', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('6')).place(x=120, y=80)
        Button(self.root, width=3, height=2, text='7', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('7')).place(x=30, y=130)
        Button(self.root, width=3, height=2, text='8', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('8')).place(x=75, y=130)
        Button(self.root, width=3, height=2, text='9', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('9')).place(x=120, y=130)
        Button(self.root, width=3, height=2, text='0', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('0')).place(x=30, y=180)
        Button(self.root, width=3, height=2, text='+', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('+')).place(x=75, y=180)
        Button(self.root, width=3, height=2, text='-', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('-')).place(x=120, y=180)
        Button(self.root, width=3, height=2, text='*', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('*')).place(x=30, y=230)
        Button(self.root, width=3, height=2, text='/', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('/')).place(x=75, y=230)
        Button(self.root, width=3, height=2, text='(', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('(')).place(x=120, y=230)
        Button(self.root, width=3, height=2, text=')', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button(')')).place(x=30, y=280)
        Button(self.root, width=3, height=2, text='=', font=("Verdana", 12, "bold"),
               command=self.output).place(x=75, y=280)
        Button(self.root, width=3, height=2, text='CL', font=("Verdana", 12, "bold"),
               command=self.clear).place(x=120, y=280)
        Button(self.root, width=3, height=2, text='x^y', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('^')).place(x=30, y=320)
        Button(self.root, width=3, height=2, text='x^1/y', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('root')).place(x=75, y=380)
    def draw_menu(self):
        menu_bar = Menu(self.root)
        file_menu = Menu(menu_bar, tearoff=0)
        color_menu = Menu(file_menu, tearoff=0)
        color_menu.add_command(label='Зеленый', command=lambda: self.change_color('green'))
        color_menu.add_command(label='Красный', command=lambda: self.change_color('red'))
        color_menu.add_command(label='Сброс', command=lambda: self.change_color('white'))
        menu_bar.add_cascade(label='Настройки', menu=file_menu)
        file_menu.add_cascade(label='Цвет фона', menu=color_menu)
        self.root.configure(menu=menu_bar)
 
    def change_color(self, color):
        self.root.configure(bg=color)
 
    def test_button(self, val):
        if self.label_out.cget("text") in ('0', 'ERROR', 'ZERO DIVISION'):
            self.label_out.config(text=val)
        else:
            if (val == '+' and self.label_out.cget("text")[-1] == '+') or (
                    val == '-' and self.label_out.cget("text")[-2] == '-'):
                return
            else:
                old_label_val = self.label_out.cget("text")
                new_val = old_label_val + val
                self.label_out.config(text=new_val)
 
    def solve_main(self):
        try:
            str_ = self.label_out.cget("text")
            token_list = []
            token = []
            for i in range(len(str_)):
                if str_[i].isdigit():
                    token += [str_[i]]
                else:
                    token_list += [token]
                    token = []
                    token += [str_[i]]
                    token_list += [token]
                    token = []
            if len(token):
                token_list += [token]
            result = list(filter(lambda a: a, map(lambda x: ''.join(x), token_list)))
 
            def to_number(x):
                return int(x) if x.isdigit() else x
 
            result2 = list(map(to_number, result))
            for i in range(len(result2) - 1):
                if not isinstance(result2[i], int) and result2[i + 1] == '-':
                    result2[i + 2] = ~result2[i + 2] + 1
                    result2[i + 1] = None
            if result2[0] == '-':
                result2[1] = ~result2[1] + 1
                result2.pop(0)
            final_result1 = list(filter(lambda x: x is not None, result2))
            test_null = False
            for i in range(len(final_result1) - 1):
                if final_result1[i] == '/' and not final_result1[i + 1]:
                    test_null = True
                    break
 
            if test_null:
                return 'ZERO DIVISION'
 
            def solve(s):
                def seek(stack):
                    if stack:
                        return stack[-1]
 
                ops = {
                    '+': 1,
                    '-': 1,
                    '/': 2,
                    '*': 2,
                    '^': 2,
                    'root': 2
                }
 
                stack = []
                out = []
 
                for i in s:
                    if isinstance(i, int):
                        out.append(i)
                    elif i in ops:
                        while stack and seek(stack) != '(' and ops[seek(stack)] >= ops[i]:
                            out.append(stack.pop())
                        stack.append(i)
                    elif i == '(':
                        stack.append(i)
                    elif i == ')':
                        while stack and seek(stack) != '(':
                            out.append(stack.pop())
                        if stack and seek(stack) == '(':
                            stack.pop()
 
                while stack:
                    out.append(stack.pop())
                stack2 = []
                for i in out:
                    if isinstance(i, int):
                        stack2 += [i]
                    else:
                        a = stack2[-2:]
                        stack2.pop()
                        stack2.pop()
                        if i == '+':
                            stack2 += [sum(a)]
                        if i == '*':
                            stack2 += [a[0] * a[1]]
                        if i == '-':
                            stack2 += [a[0] - a[1]]
                        if i == '/':
                            stack2 += [a[0] / a[1]]
                        if i == '^':
                            stack2 += [a[0] ** a[1]]
                        if i == '^1/y':
                            stack2 += [a[0] ** 1/a[1]]
                return stack2[0]
 
            return solve(final_result1)
        except IndexError:
            return 'ERROR'
        except TypeError:
            return 'ERROR'
 
    def output(self):
        self.label_out.config(text=str(self.solve_main()))
 
    def clear(self):
        self.label_out.config(text='0')
 
 
if __name__ == "__main__":
    window = Window(250, 380)
    window.run()
0
Эксперт PythonЭксперт Java
19530 / 11067 / 2931
Регистрация: 21.10.2017
Сообщений: 23,294
16.12.2024, 23:00
Я тебе написал как считать координаты
0
90 / 125 / 28
Регистрация: 17.10.2010
Сообщений: 1,338
16.12.2024, 23:00
Цитата Сообщение от iSmokeJC Посмотреть сообщение
Так это же квадратный только, а надо n-корень.
0
Эксперт PythonЭксперт Java
19530 / 11067 / 2931
Регистрация: 21.10.2017
Сообщений: 23,294
16.12.2024, 23:02
Спереди степень, за ней знак корня, за ним искомое число
0
90 / 125 / 28
Регистрация: 17.10.2010
Сообщений: 1,338
16.12.2024, 23:05
Так чтоли: x√y?
0
Эксперт PythonЭксперт Java
19530 / 11067 / 2931
Регистрация: 21.10.2017
Сообщений: 23,294
16.12.2024, 23:08
Да хотя бы и так
0
90 / 125 / 28
Регистрация: 17.10.2010
Сообщений: 1,338
16.12.2024, 23:14
Не понял я как считать координаты по x и по y?
0
Эксперт PythonЭксперт Java
19530 / 11067 / 2931
Регистрация: 21.10.2017
Сообщений: 23,294
16.12.2024, 23:18
isaak, бросай это дело. Не твое это. Совсем не твое
0
90 / 125 / 28
Регистрация: 17.10.2010
Сообщений: 1,338
16.12.2024, 23:19
А здесь правильно:
Python
1
2
if i == 'x√y':
                            stack2 += [a[0] ** 1/a[1]]
0
Эксперт PythonЭксперт Java
19530 / 11067 / 2931
Регистрация: 21.10.2017
Сообщений: 23,294
16.12.2024, 23:19
Нет
0
Любознательный
 Аватар для YuS_2
7407 / 2260 / 361
Регистрация: 10.03.2016
Сообщений: 5,216
16.12.2024, 23:20
Цитата Сообщение от isaak Посмотреть сообщение
Координаты какие ставить?
Просто надо не спешить писать на форум, а потренироваться с материалом
Python
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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
from tkinter import *
 
 
class Window:
    def __init__(self, width, height, title="FirstTK", resizable=(False, True), icon=None):
        self.root = Tk()  # корневая переменная которая хранит с себе экземпляр класса Tk
        self.root.title(title)
        self.root.geometry(f"{width}x{height}+200+200")
        self.root.resizable(resizable[0], resizable[1])
        if icon:
            self.root.iconbitmap(icon)
        self.label_out = Label(self.root, text='0', font=("Verdana", 10, "bold"))
 
    def run(self):
        self.draw_widgets()
        self.root.mainloop()
 
    def draw_widgets(self):
        self.draw_menu()
        self.label_out.place(x=30, y=10)
        Button(self.root, width=3, height=2, text='1', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('1')).place(x=30, y=30)
        Button(self.root, width=3, height=2, text='2', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('2')).place(x=75, y=30)
        Button(self.root, width=3, height=2, text='3', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('3')).place(x=120, y=30)
        Button(self.root, width=3, height=2, text='4', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('4')).place(x=30, y=80)
        Button(self.root, width=3, height=2, text='5', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('5')).place(x=75, y=80)
        Button(self.root, width=3, height=2, text='6', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('6')).place(x=120, y=80)
        Button(self.root, width=3, height=2, text='7', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('7')).place(x=30, y=130)
        Button(self.root, width=3, height=2, text='8', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('8')).place(x=75, y=130)
        Button(self.root, width=3, height=2, text='9', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('9')).place(x=120, y=130)
        Button(self.root, width=3, height=2, text='0', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('0')).place(x=30, y=180)
        Button(self.root, width=3, height=2, text='+', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('+')).place(x=75, y=180)
        Button(self.root, width=3, height=2, text='-', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('-')).place(x=120, y=180)
        Button(self.root, width=3, height=2, text='*', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('*')).place(x=30, y=230)
        Button(self.root, width=3, height=2, text='/', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('/')).place(x=75, y=230)
        Button(self.root, width=3, height=2, text='(', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('(')).place(x=120, y=230)
        Button(self.root, width=3, height=2, text=')', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button(')')).place(x=30, y=280)
        Button(self.root, width=3, height=2, text='=', font=("Verdana", 12, "bold"),
               command=self.output).place(x=75, y=280)
        Button(self.root, width=3, height=2, text='CL', font=("Verdana", 12, "bold"),
               command=self.clear).place(x=120, y=280)
        Button(self.root, width=3, height=2, text='x^y', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('^')).place(x=30, y=330)
        Button(self.root, width=3, height=2, text='ˣ√y', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('√')).place(x=75, y=330)
    def draw_menu(self):
        menu_bar = Menu(self.root)
        file_menu = Menu(menu_bar, tearoff=0)
        color_menu = Menu(file_menu, tearoff=0)
        color_menu.add_command(label='Зеленый', command=lambda: self.change_color('green'))
        color_menu.add_command(label='Красный', command=lambda: self.change_color('red'))
        color_menu.add_command(label='Сброс', command=lambda: self.change_color('white'))
        menu_bar.add_cascade(label='Настройки', menu=file_menu)
        file_menu.add_cascade(label='Цвет фона', menu=color_menu)
        self.root.configure(menu=menu_bar)
 
    def change_color(self, color):
        self.root.configure(bg=color)
 
    def test_button(self, val):
        if self.label_out.cget("text") in ('0', 'ERROR', 'ZERO DIVISION'):
            self.label_out.config(text=val)
        else:
            if (val == '+' and self.label_out.cget("text")[-1] == '+') or (
                    val == '-' and self.label_out.cget("text")[-2] == '-'):
                return
            else:
                old_label_val = self.label_out.cget("text")
                new_val = old_label_val + val
                self.label_out.config(text=new_val)
 
    def solve_main(self):
        try:
            str_ = self.label_out.cget("text")
            token_list = []
            token = []
            for i in range(len(str_)):
                if str_[i].isdigit():
                    token += [str_[i]]
                else:
                    token_list += [token]
                    token = []
                    token += [str_[i]]
                    token_list += [token]
                    token = []
            if len(token):
                token_list += [token]
            result = list(filter(lambda a: a, map(lambda x: ''.join(x), token_list)))
 
            def to_number(x):
                return int(x) if x.isdigit() else x
 
            result2 = list(map(to_number, result))
            for i in range(len(result2) - 1):
                if not isinstance(result2[i], int) and result2[i + 1] == '-':
                    result2[i + 2] = ~result2[i + 2] + 1
                    result2[i + 1] = None
            if result2[0] == '-':
                result2[1] = ~result2[1] + 1
                result2.pop(0)
            final_result1 = list(filter(lambda x: x is not None, result2))
            test_null = False
            for i in range(len(final_result1) - 1):
                if final_result1[i] == '/' and not final_result1[i + 1]:
                    test_null = True
                    break
 
            if test_null:
                return 'ZERO DIVISION'
 
            def solve(s):
                def seek(stack):
                    if stack:
                        return stack[-1]
 
                ops = {
                    '+': 1,
                    '-': 1,
                    '/': 2,
                    '*': 2,
                    '^': 2,
                    '√': 2
                }
 
                stack = []
                out = []
 
                for i in s:
                    if isinstance(i, int):
                        out.append(i)
                    elif i in ops:
                        while stack and seek(stack) != '(' and ops[seek(stack)] >= ops[i]:
                            out.append(stack.pop())
                        stack.append(i)
                    elif i == '(':
                        stack.append(i)
                    elif i == ')':
                        while stack and seek(stack) != '(':
                            out.append(stack.pop())
                        if stack and seek(stack) == '(':
                            stack.pop()
 
                while stack:
                    out.append(stack.pop())
                stack2 = []
                for i in out:
                    if isinstance(i, int):
                        stack2 += [i]
                    else:
                        a = stack2[-2:]
                        stack2.pop()
                        stack2.pop()
                        if i == '+':
                            stack2 += [sum(a)]
                        if i == '*':
                            stack2 += [a[0] * a[1]]
                        if i == '-':
                            stack2 += [a[0] - a[1]]
                        if i == '/':
                            stack2 += [a[0] / a[1]]
                        if i == '^':
                            stack2 += [a[0] ** a[1]]
                        if i == '√':
                            stack2 += [a[1] ** (1/a[0])]
                return stack2[0]
 
            return solve(final_result1)
        except IndexError:
            return 'ERROR'
        except TypeError:
            return 'ERROR'
 
    def output(self):
        self.label_out.config(text=str(self.solve_main()))
 
    def clear(self):
        self.label_out.config(text='0')
 
 
if __name__ == "__main__":
    window = Window(250, 400)
    window.run()
1
90 / 125 / 28
Регистрация: 17.10.2010
Сообщений: 1,338
16.12.2024, 23:21
Python
1
2
Button(self.root, width=3, height=2, text='x√y', font=("Verdana", 12, "bold"),
               command=lambda: self.test_button('x√y')).place(x=75, y=320)
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
16.12.2024, 23:21

Напишите программу, которая вычисляет выражение, состоящее из трех чисел и двух знаков
Напишите программу, которая вычисляет выражение, состоящее из трех чисел и двух знаков (допускаются только знаки «+» или «–»). Выражение...

Напишите программу, которая вычисляет выражение,состоящее из 3-х чисел и 2-х знаков (допускаются знаки + - / *
Напишите программу, которая вычисляет выражение,состоящее из 3-х чисел и 2-х знаков (допускаются знаки + - / *). Выражение вводится как...

Напишите программу, которая вычисляет выражение, состоящее из трех чисел и двух знаков
Pascal ABC Буду очень благодарен, если поможете с решением программы) вот само задание: &quot;Напишите программу, которая вычисляет...

Напишите программу, которая вычисляет выражение, состоящее из чисел, знаков (допускаются знаки «+», «–», «*» и
Напишите программу, которая вычисляет выражение, состоящее из чисел, знаков (допускаются знаки «+», «–», «*» и «/») и круглых скобок....

Напишите программу, которая вычисляет выражение, состоящее из трех чисел и двух знаков (допускаются знаки «+», «–», «*» и «/»)
Здравствуйте. Прошу помощи. Уровень C. Напишите программу, которая вычисляет выражение, состоящее из трех чисел и двух знаков...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
40
Ответ Создать тему
Новые блоги и статьи
Беседа с ИИ о программистах, недопускающих к созданию и правке кода генеративные ИИ и причины этого
zorxor 21.09.2026
Раньше я радовался или получал некоторые эмоции, пусть небольшие, но всё же, от самого процесса написания кода, рекомпиляции и запуска, видя постепенное развитие программы и прочее. А теперь лень. . .
Мобильное приложение ColorStep
pavlinmavlin 17.09.2026
Реализовал приложение Красный, Зеленый, Синий в Unity3d + c#. Название изменил на ColorStep. Приложение прошло модерацию и теперь доступно для скачивания. Делал его сам, шаг за шагом — и вот,. . .
Запрет дублирования строк в табличной части
Maks 13.09.2026
Реализация из решения ниже выполнена на нетиповом справочнике "Нормы ТО" с табличной часть "Виды ТО", разработанного в КА2, со следующими реквизитами: - ВидТО (СправочникСсылка. ВидыТО); - ВидГСМ. . .
Скрипты Tampermonkey для CyberForum, ChatGPT, Claude и пр.
Jin X 06.09.2026
Скрипты Tampermonkey для CyberForum, ChatGPT, Claude и пр. Работая с форумом и нейросетями в браузере часто хочется что-то подкорректировать или добавить какого-то функционала. Ниже прикреплён. . .
Программа опроса у.з. расходомера SLS-720F
Argus19 02.09.2026
Программа опроса у. з. расходомера SLS-720F Программа опрашивает один раз в минуту три ультразвуковых расходомера SLS-720F через интерфейс RS-485 по протоколу Modbus RTU. Опрашиваются регистры. . .
Hyper-V: Компьютер должен поддерживать доверенный платформенный модуль 2.0.
Maks 31.08.2026
При установке Windows 11 на виртуальную машину Hyper-V 2-го поколения вылезла такая ошибка: Решение: в параметрах виртуальной машины, в разделе "Безопасность" (Security) активировать флаг. . .
Архитектура биовида Стива в Майнкрафте: Зачем бонобо кубический каннибализм
anaschu 30.08.2026
Кубический Вагинокапитализм в Minecraft: Математический инвариант ОДУ и рок Стивов-бонобо Главная задача разработанной «Модели Всего» — наглядно продемонстрировать наличие системной «судьбы». . .
Оттачиваю умение писать js программы.
russiannick 30.08.2026
Проектом выходного дня стало написание Книги шифров Виженера. Итогом стала версия 200, синий туман. Синий туман назван так, потому что замораживает текст под собой. Нажатие синих кнопок управляют. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru