用Python的list类实现栈及应用

用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
  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值