您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

Python 数据结构之堆栈实例代码

2024/10/27 23:46:13发布35次查看
python 堆栈
堆栈是一个后进先出(lifo)的数据结构. 堆栈这个数据结构可以用于处理大部分具有后进先出的特性的程序流 .
在堆栈中, push 和 pop 是常用术语:
push: 意思是把一个对象入栈.
pop: 意思是把一个对象出栈.
下面是一个由 python 实现的简单的堆栈结构:
stack = [] # 初始化一个列表数据类型对象, 作为一个栈 def pushit(): # 定义一个入栈方法 stack.append(raw_input('enter new string: ').strip()) # 提示输入一个入栈的 string 对象, 调用 str.strip() 保证输入的 string 值不包含多余的空格 def popit(): # 定义一个出栈方法 if len(stack) == 0: print "cannot pop from an empty stack!" else: print 'remove [', `stack.pop()`, ']' # 使用反单引号(` `)来代替 repr(), 把 string 的值用引号扩起来, 而不仅显示 string 的值 def viewstack(): # 定义一个显示堆栈中的内容的方法 print stack cmds = {'u':pushit, 'o':popit, 'v':viewstack} # 定义一个 dict 类型对象, 将字符映射到相应的 function .可以通过输入字符来执行相应的操作 def showmenu(): # 定义一个操作菜单提示方法 pr = """ p(u)sh p(o)p (v)iew (q)uit enter choice: """ while true: while true: try: choice = raw_input(pr).strip()[0].lower() # str.strip() 去除 string 对象前后的多余空格 # str.lower() 将多有输入转化为小写, 便于后期的统一判断 # 输入 ^d(eof, 产生一个 eoferror 异常) # 输入 ^c(中断退出, 产生一个 keyboardinterrupt 异常) except (eoferror, keyboardinterrupt, indexerror): choice = 'q' print '\nyou picked: [%s]' % choice if choice not in 'uovq': print 'invalid option, try again' else: break if choice == 'q': break cmds[choice]() # 获取 dict 中字符对应的 functionname, 实现函数调用 if __name__ == '__main__': showmenu()
note: 在堆栈数据结构中, 主要应用了 list 数据类型对象的 容器 和 可变 等特性, 表现在 list.append() 和 list.pop() 这两个列表类型内建函数的调用.
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
更多python 数据结构之堆栈实例代码。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product