数据结构__Python实现队列和栈

注:以栈为例,因为队列只要修改popit()函数处代码,和修改相关提示语句即可。

#Python的栈定义与计基本操作
#队列只是改下提示语句和popit()函数

stack=[]

def pushit():
    stack.append(input('输入新的元素并入栈:').strip())

#若是队列只要将第14行改为repr(stack.pop[0])即可
def popit():
    if len(stack)==0:
        print('空栈!!!')
    else:
        print('退栈[',repr(stack.pop()),']')

def viewstack():
    print (stack)

#定义的动作函数,可以用通过代号调用函数
CMDs={'u':pushit,'o':popit,'v':viewstack}

def showmenu():
    pr='''
p(U)sh
 p(O)p
(V)iew
(Q)uit

输入你要的操作:
    '''

    while True:
        while True:
            try:
                choice=input(pr).strip()[0].lower()
            except (EOFError,KeyboardInterrupt,IndexError):
                choice='q'

            #若写成中文print('\n你选择了:[%s]' % choice)将报错
            #因为中文是Unicode而英文是ASCII,只有ASCII可以格式化输出
            print('\nYou picked:[%s]' % choice)
            if choice not in 'uovq':
                print('非法命令,重新输入:')
            else:
                break

        if choice=='q':
            break
        CMDs[choice]()

if __name__=='__main__':
    showmenu()

猜你喜欢

转载自blog.csdn.net/qq_41938259/article/details/86300029