Добавил:
lovickaaolesa
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз:
Предмет:
Файл:5 курс / lab1
.pyclass Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop() if not self.is_empty() else None
def peek(self):
return self.items[-1] if not self.is_empty() else None
def is_empty(self):
return len(self.items) == 0
def precedence(op):
if op in ('+', '-'):
return 1
if op in ('*', '/', '%'):
return 2
if op == '^':
return 3
return 0
def is_operator(c):
return c in '+-*/^%'
def infix_to_postfix(expression):
stack = Stack()
output = []
i = 0
while i < len(expression):
char = expression[i]
if char == ' ':
i += 1
continue
if char.isdigit() or char == '.':
num = ''
while i < len(expression) and (expression[i].isdigit() or expression[i] == '.'):
num += expression[i]
i += 1
output.append(num)
continue
elif char == '(':
stack.push(char)
elif char == ')':
while not stack.is_empty() and stack.peek() != '(':
output.append(stack.pop())
stack.pop()
elif is_operator(char):
if char == '-' and (i == 0 or expression[i - 1] == '(' or is_operator(expression[i - 1])):
output.append('0')
while (not stack.is_empty() and
stack.peek() != '(' and
precedence(stack.peek()) >= precedence(char)):
output.append(stack.pop())
stack.push(char)
i += 1
while not stack.is_empty():
output.append(stack.pop())
return ' '.join(output)
def evaluate_postfix(expression):
stack = Stack()
tokens = expression.split()
for token in tokens:
if token.replace('.', '', 1).isdigit():
stack.push(float(token))
elif is_operator(token):
if len(stack.items) < 2:
raise ValueError("Недостаточно операндов для оператора")
b = stack.pop()
a = stack.pop()
if token == '+':
result = a + b
elif token == '-':
result = a - b
elif token == '*':
result = a * b
elif token == '/':
if b == 0:
raise ValueError("Деление на ноль")
result = a / b
elif token == '^':
result = a ** b
elif token == '%':
result = a % b
stack.push(result)
if stack.is_empty():
raise ValueError("Некорректное выражение")
return stack.pop()
def evaluate_infix(expression):
postfix = infix_to_postfix(expression)
return evaluate_postfix(postfix)
def main_menu():
while True:
print("\n" + "=" * 50)
print("МЕНЮ:")
print("1. Посчитать выражение в инфиксном виде")
print("2. Посчитать выражение в постфиксном виде")
print("3. Перевести выражение из инфиксного в постфиксный вид")
print("4. Выход")
print("=" * 50)
choice = input("Выберите пункт меню (1-4): ").strip()
if choice == '1':
expression = input("Введите выражение в инфиксном виде: ").strip()
try:
result = evaluate_infix(expression)
print(f"Результат: {result}")
postfix = infix_to_postfix(expression)
print(f"Постфиксная форма: {postfix}")
except Exception as e:
print(f"Ошибка: {e}")
elif choice == '2':
expression = input("Введите выражение в постфиксном виде: ").strip()
try:
result = evaluate_postfix(expression)
print(f"Результат: {result}")
except Exception as e:
print(f"Ошибка: {e}")
elif choice == '3':
expression = input("Введите выражение в инфиксном виде: ").strip()
try:
postfix = infix_to_postfix(expression)
print(f"Постфиксная форма: {postfix}")
except Exception as e:
print(f"Ошибка: {e}")
elif choice == '4':
print("Выход из программы...")
break
else:
print("Неверный выбор. Пожалуйста, выберите пункт от 1 до 4.")
if __name__ == "__main__":
print("Программа для работы с инфиксными и постфиксными выражениями")
print("Поддерживаемые операторы: +, -, *, /, ^, %")
print("Поддерживаются скобки и отрицательные числа")
main_menu()
Соседние файлы в папке 5 курс
