用列表模拟堆栈,队列

 用列表模拟堆栈

#用列表模拟堆栈

stack = []    #新建一个空列表

def pushit():                                      #提示用户输入一个字符到STACK末尾中
    stack.append(input('Enter string:').strip())   #input.strip(chars) 移除输入首尾指定的chars

def popit():                                        #从stack末尾移除一个字符
    if len(stack) == 0:                             #如果列表为空,则返回错误
        print("It's possible since stack is epmty")
    else:
        print('Remove',"'",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
    Enter choices = '''

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

        print("You have picked [%s]" % choice)

        if choice not in 'uovq':
            print("Invalid choice, try again")
        else:
            if choice == 'q':
                break
            else:
                CMDS[choice]()

if __name__ == '__main__':
    showmenu()

注意29行,

    choice = input(pr).strip()[0].lower()           #分别对输入的字符串进行去掉首尾空字符及变换小写操作

若为input().strip().lower(),当输入为空字符或为空时,程序会报错:在CMDS[choice](),出现键值错误。

D:\pythonwokr\venv\Scripts\python.exe D:/pythonwokr/P145.py

    p(u)sh
    p(o)p
    (v)iew
    (q)uit
    Enter choices = 

You have picked []
Traceback (most recent call last):
  File "D:/pythonwokr/P145.py", line 44, in <module>
    showmenu()
  File "D:/pythonwokr/P145.py", line 41, in showmenu
    CMDS[choice]()
KeyError: ''

Process finished with exit code 1

即:

当输入空字符或空时,

choice = input(pr).strip()[0].lower()

        会返回一个IndexError,因为在strip之后为空字符串,索引值为0并不存在指向的字符;

Traceback (most recent call last):
  File "D:/pythonwokr/test.py", line 2, in <module>
    choice = input('1').strip()[0].upper()
IndexError: string index out of range

Process finished with exit code 1

choice = input(pr).strip().lower()

        会创建一个空字符串对象,随后choice指向这个对象;

        在后续的CMDS[choice](),会出现对应的字典键值错误(KeyError)

 

同理,用列表模拟队列:

#用列表模拟队列

queue = []

def enQ():
    queue.append(input('Enter new string').strip())

def deQ():
    if len(queue) == 0:
        print('Can\'t pop from an empty queue!')
    else:
        print('Remove',"'",queue.pop(0),"'")

def viewQ():
    print(queue)

CMDS = {'e':enQ,'d':deQ,'v':viewQ}

def showmenu():
    pr = """
    (E)nqueue
    (D)equeue
    (V)iew
    (Q)uit
    
    Enter choice:"""

    while True:
        try:
            choice = input(pr).strip()[0].lower()
        except (EOFError,KeyboardInterrupt,IndexError):
            choice = "q"
        print("You picked:[%s]" % choice)

        if choice not in 'edvq':
            print("Invalid choice, try again")
        else:
            if choice == 'q':
                break
            else:
                CMDS[choice]()

if __name__ == '__main__':
    showmenu()

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值