把Python的基础语法过了一遍,写个计算器练练手。这个计算器很简陋,只支持正整数的加、减、乘、除运算,可带小括号。
计算器是“栈”的一个小应用,需要用到栈,所以先写栈,我选择用链表实现。
代码如下:
"""
文件名:Stack.py
功能:栈(链表实现)
日期:2020.1.22
作者:CBB
"""
class Node:
"""链表结点"""
def __init__(self, items):
"""items为结点中的数据"""
self.items = items
self.next = None
class Stack:
"""栈"""
def __init__(self):
"""初始化链表,第一个结点为空节点"""
self.head = Node(None)
self.count = 0
def is_empty(self):
"""栈是否为空,为空返回1,否则返回-1"""
if self.count == 0:
return 1
def get_top(self):
"""获取栈顶元素"""
if self.is_empty() == 1:
return -1
else:
return self.head.next.items
def push(self, items):
"""压栈"""
node = Node(items)
node.next = self.head.next
self.head.next = node
self.count += 1
def pop(self):
"""出栈"""
if self.is_empty() == 1:
return -1
self.head.next = self.head.next.next
self.count -= 1
def stack_print(self):
"""打印栈中的元素"""
lst = []
head_t = self.head
while head_t.next is not None:
head_t = head_t.next
lst.append(head_t.items)
print(lst)
有了栈,就可以做计算器了。
代码如下:
"""
文件名:Calculator.py
功能:计算器(用栈实现),支持正整数的加减乘除及括号运算
日期:2020.1.22
作者:CBB
"""
from Stack import *
class Calculator:
"""计算器"""
def __init__(self):
"""初始化计算器"""
self.exp = "" # 表达式
self.ns = Stack() # number_stack 数字栈
self.ss = Stack() # symbol_stack 符号栈
def symbol_level(self, symbol):
"""返回符号的等级"""
if symbol == "#":
return 0
elif symbol in ["(", ")"]:
return 1
elif symbol in ["+", "-"]:
return 2
elif symbol in ["*", "/"]:
return 3
def symbol_level_compare(self, symbol1, symbol2):
"""比较两符号的等级,前者高于后者,返回1,否则返回-1"""
if self.symbol_level(symbol1) > self.symbol_level(symbol2):
return 1
else:
return -1
def calculate(self, exp):
"""根据表达式计算结果"""
self.exp = exp + "#" # 预处理表达式
self.ss.push("#") # 先将“#”入栈
index = 0 # 当前处理到表达式的哪个字符
st = self.exp[index]
while not (st == "#" and self.ss.get_top() == "#"):
if st.isdigit() is True: # 数字直接入栈
self.ns.push(float(st))
elif st == "(": # 左括号直接入栈
self.ss.push(st)
else: # 符号进行判断
if self.symbol_level_compare(st, self.ss.get_top()) == 1: # 级别高于符号栈栈顶符号
self.ss.push(st) # 直接入栈
elif self.ss.get_top() == "(" and st == ")":
self.ss.pop()
else: # 否则对栈中符号进行计算
operator = self.ss.get_top() # 获取运算符
self.ss.pop()
operand2 = self.ns.get_top() # 操作数2
self.ns.pop()
operand1 = self.ns.get_top() # 操作数1
self.ns.pop()
if operator == "+": # 计算结果并将其入栈
self.ns.push(operand1 + operand2)
elif operator == "-":
self.ns.push(operand1 - operand2)
elif operator == "*":
self.ns.push(operand1 * operand2)
elif operator == "/":
self.ns.push(operand1 / operand2)
continue
index += 1 # 获取新的符号
st = self.exp[index]
return self.ns.get_top()
cal = Calculator()
exp = input("请输入表达式(输入q退出):")
while exp != "q":
print(cal.calculate(exp))
exp = input("请输入表达式(输入q退出):")
将上面的两个文件:Stack.py和Calculator.py,放在同一个文件夹中,运行Calculator.py即可。