python代数式括号有效性检验示例代码

python代数式括号有效性检验示例代码,第1张

python代数式括号有效性检验示例代码

思路:

利用栈实现代数式中括号有效行的的检验:

代码:

class mychain(object): #利用链表建立栈,链表为父类
 length=0
 def __init__(self,value=None,next=None):#创建链表,长度并不包含头部
  self.value=value
  self.next=next
  #mychain.length=mychain.length+1
 def append(self,value=None):
  while self.next!=None:
   self=self.next
  self.next=mychain(value)
  mychain.length=mychain.length+1 #追加时,链表长度增加
 def travle(self):#遍历链表
  print(self.value)
  if self.next!=None:
   self.next.travle()
 def drop (self,value):#删除特定值的第一个匹配节点
  while self.next!=None:
   if self.next.value!=value:
    self=self.next
   else:
    self.next=self.next.next
    mychain.length=mychain.length-1 #删除时,链表长度减小
    break
 def pop(self):#删除未节点
  if self.next!=None:#并不删除头结点
   while self.next.next!=None:
    self=self.next
   self.next=None
   mychain.length=mychain.length-1#d出为节点,并减小长度,头结点不d出



class stock(mychain):#栈类
 bottom=None   #栈底
 top=None     #栈顶
 n_count=0    #计数
 def Max(self):  #占中最大值
  if self.next!=None:
   tmp = self.next.value
   while self.next.next!=None:
    self=self.next
    if self.next.value>tmp:
     tmp=self.next.value
   return tmp
  else:
   print('栈为空!')
 def Min(self):#栈中的最小值
  if self.next!=None:
   tmp = self.next.value
   while self.next.next!=None:
    self=self.next
    if self.next.value

运行:

bstr='([{((({{}})))}]){{}}{{}{}{}[][]()(123)(((sin5)))}'
f=solution()
print(f.validationofbrackets(bstr))

总结

到此这篇关于python代数式括号有效性检验的文章就介绍到这了,更多相关python代数式括号有效性检验内容请搜索考高分网以前的文章或继续浏览下面的相关文章希望大家以后多多支持考高分网!

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/3207179.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-10-03
下一篇 2022-10-03

发表评论

登录后才能评论

评论列表(0条)

保存