温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python模拟队列和堆栈(列表练习)

发布时间:2020-06-05 01:27:33 来源:网络 阅读:795 作者:大陌 栏目:软件技术
##################################queue#########################################
#!/usr/bin/env python

'use list as a queue'

#define a void list as a void queue
queue = []

#define in queue function
def enQ():
    queue.append(raw_input('Enter New String: ').strip())

#define out queue function
def deQ():
    #judge queue whether viod
    if len(queue) == 0:
        print('Can not pop from an empty queue!')
    else:
        print('Removed' ,queue.pop(0))

#define show queue function
def viewQ():
    print(queue)

#define a dictionary to chose opration function
cmds = {'e':enQ,'d':deQ,'v':viewQ}

#define a funtion to show menu
def showMenu():
    pr = '''
    (E)nqueue
    (D)equeue
    (V)iew
    (Q)uit
    
    Enter choice:'''

    #double while circle make program always run
    while True:
        while True:
            try:
                #use to print menu information and get valid choice number(no space, just one bit , lower)
                choice = raw_input(pr).strip()[0].lower()
            except(EOFError,KeyboardInterrupt,IndexError):
                #if get a invalid value,return 'q'
                choice = 'q'
                
            print('You picked: %s '% choice)
            if choice not in 'devq':
                print('Invalid option, try again!')
            else:
                break

        if choice == 'q':
            break
        #call functions by dictionary
        cmds[choice]()

#main function
if __name__ == '__main__':
    showMenu()
    
    
 ##################################stack######################################
 #!/usr/bin/env python

'this program use list as a stack'

stack = []

def pushit():
    'input stack '
    stack.append(raw_input('Enter New Strings: ').strip())

def popit():
    'output stack'
    if len(stack) == 0:
        print('Can not pop from an empty stack!')
    else:
        print('removed [',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 Choice:
 
'''
    while True:
        while True:
            try:
                choice = raw_input(pr).strip()[0].lower()
                print(choice)
            except(EOFError.KeyboardInterrupt,IndexError):
                choice = 'q'
            print('you picked: %s ' % choice) 
            if choice not in 'uovq':
                print('Invalid option, try again')
            else:
                break

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

if __name__ == '__main__':
    showMenu()


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI