前言:
眼前我们对“python里的数据结构”大概比较关切,朋友们都想要学习一些“python里的数据结构”的相关文章。那么小编也在网摘上网罗了一些有关“python里的数据结构””的相关文章,希望小伙伴们能喜欢,咱们一起来学习一下吧!栈Stack:
一种有次序的数据集合,在栈中,数据项的加入和移除都
仅发生在同一端
一端叫栈‘顶top‘,另一端叫栈’底base‘
每个数据顶仅从’栈顶‘一端加入数据集中,从数据集中移除;
栈具有后进先出LIFO的特性
class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self,item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items)-1] def size(self): return len(self.items) s = Stack()print(s.isEmpty())s.push(4)s.push('dog')print(s.peek())栈的应用
1)问题:判断‘()’是不是成对
def parChecker(symbolString):#判断()是否成对 s = Stack() balanced = True index = 0 while index <len(symbolString) and balanced: symbol = symbolString[index] if symbol =='(': s.push(symbol) else: if s.isEmpty(): balanced = True else: s.pop() index = index +1 if balanced and s.isEmpty(): return True else: return False print(parChecker('((())'))
2)问题:{{([])}}不同类型的括号匹配
def parChecker(symbolString): s = Stack() balanced = True index =0 while index <len(symbolString)and balanced: symbol = symbolString[index] if symbol in '([{': s.push(symbol) else: if s.isEmpty(): balanced =False else: top = s.pop() if not matches(top,symbol): balanced = False index = index+1 if balanced and s.isEmpty(): return True else: return False def matches(open,close): opens ='([{' closes=')]}' return opens.index(open) ==closes.index(close)print(parChecker('{{([][])}}'))
3)十进制转二进制
def divideBy2(decNumber): remstack = Stack() while decNumber>0: rem =decNumber%2#求余数 remstack.push(rem) decNumber =decNumber//2#整数除 binString ='' while not remstack.isEmpty(): binString =binString + str(remstack.pop()) return binStringprint(divideBy2(16))
4)十进制转其他进制
def baseConverter(decNumber,base): digits = '0123456789ABCDEF' remstack = Stack() while decNumber>0: rem = decNumber%base remstack.push(rem) decNumber = decNumber//base newString ='' while not remstack.isEmpty(): newString = newString +digits[remstack.pop()] return newStringprint(baseConverter(25, 2))print(baseConverter(25, 16))
版权声明:
本站文章均来自互联网搜集,如有侵犯您的权益,请联系我们删除,谢谢。
标签: #python里的数据结构