用Python的list类实现栈及应用
核心:pop和push
遵循:先进后出
- 先定义好所需的Stack:
class ArrayStack():
def __init__(self):
self._data = []
def __len__(self):
return len(self._data)
def _isEmpty(self):
return len(self._data) == 0
def push(self,element):
self._data.append(element)
def top(self):
if self._isEmpty():
raise Empty("stack is empty")
return self._data[-1] #stack's first push is in the last palce in data list
def pop(self):
if self._isEmpty():
raise Empty("Stack is empty")
return self._data.pop() # pop is in list,which means delect the last one in list
- 应用1:Stack检查括号分隔符的匹配算法
def parcheck(symbolString):
s = ArrayStack()
balance = True
index = 0
while index < len(symbolString)and balance:
if symbolString[index] == "(":
s.push(symbolString[index])
else:
if s._isEmpty():
balance = False
else:
s.pop()
index += 1
if balance and s._isEmpty():
return True
else:
return False
print(parcheck("(((())))"))
print(parcheck("(()))"))
True
False
- 扩展:运用Stack检查常见分隔符的匹配算法
#Methods 1
def uparcheck1(symbolString): #Universual parcheck
s = ArrayStack()
balance = True
index = 0
while index < len(symbolString)and balance:
if symbolString[index] in "([{":
s.push(symbolString[index])
else:
if s._isEmpty():
balance = False
else:
top = s.pop()
if not matches(top,symbolString[index]):
balance = False
index += 1
if balance and s._isEmpty():
return True
else:
return False
def matches(left,right):
lefts = "([{"
rights = ")]}"
return lefts.index(left) == rights.index(right)
print(uparcheck1("{{([[]])}}"))
print(uparcheck1("(}}([])"))
True
False
#Method 2
def uparcheck2(symbolString):
s = ArrayStack()
lefts = "({["
rights= ")}]"
for i in symbolString:
if i in lefts:
s.push(i)
elif i in rights:
if s._isEmpty():
return False
if rights.index(i) != lefts.index(s.pop()):
return False
return s._isEmpty()
print(uparcheck2("{{([[]])}}"))
print(uparcheck2("(}}([])"))
True
False
- 应用2:用Stack实现十进制转换成二进制
def divideBy2(decNumber):
BinaryStack = ArrayStack()
while decNumber > 0:
temp = decNumber % 2
BinaryStack.push(temp)
decNumber = decNumber // 2
binString = ''
while not BinaryStack._isEmpty():
binString += str(BinaryStack.pop())
return binString
print(divideBy2(10))
1010
- 拓展:应用Stack实现16以下的任意进制转换
def divideBy(decNumber,base): #decNumber:需要转换的数;base:目标进制(16进制以下)
expression = '0123456789ABCDEF'
BinaryStack = ArrayStack()
while decNumber > 0:
temp = decNumber % base
BinaryStack.push(temp)
decNumber = decNumber // base
binString = ''
while not BinaryStack._isEmpty():
binString += expression[BinaryStack.pop()]
return binString
print(divideBy(25,2))
11001