python棧--字符串反轉,括號匹配


棧的實現:

 1 # 定義一個棧類
 2 class Stack():
 3     # 棧的初始化
 4     def __init__(self):
 5         self.items = []
 6     # 判斷棧是否為空,為空返回True
 7     def isEmpty(self):
 8         return self.items ==[]
 9     # 向棧內壓入一個元素
10     def push(self, item):
11         self.items.append(item)
12     # 從棧內推出最后一個元素
13     def pop(self):
14         return self.items.pop()
15     # 返回棧頂元素
16     def peek(self):
17         return self.items[len(self.items)-1]
18     # 判斷棧的大小
19     def size(self):
20         return len(self.items)

 

字符串反轉:

 1 #字符串反轉
 2 def revstring(str):
 3     s = Stack()
 4     outputstr = ''
 5 
 6     for i in str:
 7         s.push(i)
 8     while not s.isEmpty():
 9         outputstr += s.pop()
10 
11     return outputstr

 

括號匹配:

 1 #括號匹配
 2 def parCheker(str):
 3     s = Stack()
 4     balanced = True
 5     index = 0
 6     while index<len(str) and balanced:
 7         str1 = str[index]
 8         if str1 in '([{':
 9             s.push(str1)
10         else:
11             if s.isEmpty():
12                 balanced = False
13             else:
14                 top = s.pop()
15                 if not matches(top,str1):
16                     balanced = False
17 
18         index += 1
19 
20     if s.isEmpty() and balanced:
21         return True
22     else:
23         return False
24 
25 
26 def matches(open,close):
27     opens = '([{'
28     closes = ')]}'
29     return opens.index(open) == closes.index(close)

 

十進制轉換成二進制:

 1 #十進制轉換為二進制
 2 def Dec2Bin(num):
 3     s = Stack()
 4     while num>0:
 5         temp = num%2
 6         s.push(temp)
 7         num = num // 2
 8 
 9     binString = ''
10     while not s.isEmpty():
11         binString += str(s.pop())
12 
13     return binString

 

 

 

參考:https://github.com/Jack-Lee-Hiter/AlgorithmsByPython/blob/master/Stack.py


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM