1.计算器
import sys
import suanfa
from PyQt6.QtCore import Qt
from PyQt6.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QLineEdit, QPushButton
class Calculator(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("简易计算器")
self.layout = QVBoxLayout()
self.lineEdit = QLineEdit()
self.layout.addWidget(self.lineEdit)
buttons = (
("7", "8", "9", "/"),
("4", "5", "6", "*"),
("1", "2", "3", "-"),
("0", ".", "=", "+"),
("(", ")")
)
for row in buttons:
h_layout = QHBoxLayout() # 使用水平布局 QHBoxLayout
for label in row:
button = QPushButton(label)
button.clicked.connect(self.button_clicked)
h_layout.addWidget(button)
self.layout.addLayout(h_layout)
self.setLayout(self.layout)
def button_clicked(self):
# 处理按钮点击事件的逻辑
pass
def button_clicked(self):
button = self.sender()
text = self.lineEdit.text()
if button.text() == "=":
try:
result = suanfa.calculate(text)
self.lineEdit.setText(str(result))
except Exception as e:
self.lineEdit.setText("Error")
print(e)
else:
self.lineEdit.setText(text + button.text())
if __name__ == "__main__":
app = QApplication(sys.argv)
calculator = Calculator()
calculator.show()
sys.exit(app.exec())
1.1计算器中缀转后缀算法
def infix_to_postfix(expression):
# 定义运算符优先级
precedence = {'+': 1, '-': 1, '*': 2, '/': 2}
postfix = [] # 后缀表达式
stack = [] # 运算符栈
for char in expression:
if char.isnumeric():
postfix.append(char) # 数字直接加入后缀表达式
elif char == '(':
stack.append(char) # 左括号入栈
elif char == ')':
# 弹出栈内左括号之前所有运算符,加入后缀表达式
while stack and stack[-1] != '(':
postfix.append(stack.pop())
stack.pop() # 弹出左括号
else:
# 当前字符是运算符
while stack and stack[-1] != '(' and precedence[char] <= precedence.get(stack[-1], 0):
postfix.append(stack.pop()) # 优先级较高的运算符出栈,加入后缀表达式
stack.append(char) # 当前运算符入栈
# 将栈内剩余运算符加入后缀表达式
while stack:
postfix.append(stack.pop())
return ''.join(postfix)
def evaluate_postfix(expression):
stack = [] # 运算符栈
for char in expression:
if char.isnumeric():
stack.append(int(char)) # 数字入栈
else:
operand2 = stack.pop()
operand1 = stack.pop()
if char == '+':
result = operand1 + operand2
elif char == '-':
result = operand1 - operand2
elif char == '*':
result = operand1 * operand2
elif char == '/':
result = operand1 / operand2
else:
raise ValueError("Invalid operator")
stack.append(result) # 计算结果入栈
return stack.pop() # 栈内最终剩余的值即为计算结果
def calculate(biaodashi):
return evaluate_postfix(inf