您好,欢迎访问三七文档
当前位置:首页 > 行业资料 > 造纸印刷 > python 栈的两个应用举例
数制转换:1.硬编码实现#--coding:utf-8--N=input(Pleaseinputanumber::)while(N):print**@**N-=1N=input(输入十进制数字(换算为八进制)::)stack=[]string8=while(N):#求余stack.append(N%8)#求商N=N//8while(len(stack)0):string8+=str(stack.pop())print转换为八进制:+string82.构建stack类,来实现Stack1.py#--coding:utf-8--classStack(object):def__init__(self):self.items=[]defisEmpty(self):returnself.items==[]defpush(self,item):self.items.append(item)defpop(self):returnself.items.pop()defGetTop(self):returnself.items[len(self.items)-1]moshi.py#--coding:utf-8--importstack1shiyan=stack1.Stack()stringu=temp=input(请输入一个十进制数字::)while(temp):shiyan.push(temp%8)temp=temp/8while(notshiyan.isEmpty()):stringu+=str(shiyan.pop())print八进制为::+stringu括号匹配硬编码实现#--coding:utf-8--print****括号匹配****print输入原则:每当你输入一个括号,你需要再输入一个‘,’进行区分,例如:(,[,],(,),)输入的可识别括号有(),[],{}strpp=raw_input(请输入一段括号表达式:)basestr=strpp.split(',')pstack=[]suoyin={'(':')','[':']','{':'}'}foreinbasestr:if(e=='('ore=='['ore=='}'):pstack.append(e)else:iflen(pstack)==0:print右括号多余breakelse:ife==suoyin[pstack[len(pstack)-1]]:pstack.pop()else:print不匹配print右括号多余breakiflen(pstack)==0:print匹配正确else:print左括号多余
本文标题:python 栈的两个应用举例
链接地址:https://www.777doc.com/doc-4209987 .html