用列表模拟堆栈
#用列表模拟堆栈
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()