python代数式括号有效性检验示例代码
思路:
利用栈实现代数式中括号有效行的的检验:
代码:
classmychain(object):#利用链表建立栈,链表为父类
length=0
def__init__(self,value=None,next=None):#创建链表,长度并不包含头部
self.value=value
self.next=next
#mychain.length=mychain.length+1
defappend(self,value=None):
whileself.next!=None:
self=self.next
self.next=mychain(value)
mychain.length=mychain.length+1#追加时,链表长度增加
deftravle(self):#遍历链表
print(self.value)
ifself.next!=None:
self.next.travle()
defdrop(self,value):#删除特定值的第一个匹配节点
whileself.next!=None:
ifself.next.value!=value:
self=self.next
else:
self.next=self.next.next
mychain.length=mychain.length-1#删除时,链表长度减小
break
defpop(self):#删除未节点
ifself.next!=None:#并不删除头结点
whileself.next.next!=None:
self=self.next
self.next=None
mychain.length=mychain.length-1#弹出为节点,并减小长度,头结点不弹出
classstock(mychain):#栈类
bottom=None#栈底
top=None#栈顶
n_count=0#计数
defMax(self):#占中最大值
ifself.next!=None:
tmp=self.next.value
whileself.next.next!=None:
self=self.next
ifself.next.value>tmp:
tmp=self.next.value
returntmp
else:
print('栈为空!')
defMin(self):#栈中的最小值
ifself.next!=None:
tmp=self.next.value
whileself.next.next!=None:
self=self.next
ifself.next.value
运行:
bstr='([{((({{}})))}]){{}}{{}{}{}[][]()(123)(((sin5)))}'
f=solution()
print(f.validationofbrackets(bstr))
总结
到此这篇关于python代数式括号有效性检验的文章就介绍到这了,更多相关python代数式括号有效性检验内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!