Implementation of Python data structure queues
- 2020-05-24 05:45:07
- OfStack
Python queue
An Queue queue is a first-in, first-out (FIFO) data type. New elements are added to the end of Queue by joining the queue, which removes elements from the head of Queue.
Queue with lists:
queue = [] # Initialize the 1 List data type objects , As a 1 A queue
def enQ(): # define 1 A push method
queue.append(raw_input('Enter New String: ').strip())
# prompt 1 A team of String object , call Str.strip() Guaranteed input String The value does not contain extra Spaces
def deQ(): # define 1 Out of the team method
if len(queue) == 0:
print "Cannot pop from an empty queue!"
else:
print 'Remove [', `queue.pop(0)`, ']'
# Use inverted single quotes (` `) To take the place of repr(), the String Is enclosed in quotation marks , Instead of just showing String The value of the
# queue.pop(0) Always pop the first element in the queue
def viewQ(): # define 1 Method to display the contents of a queue
print queue
CMDs = {'u':enQ, 'o':deQ, 'v':viewQ}
# define 1 a Dict Type of object , Map the character to the corresponding function . You can do this by entering characters
def showmenu(): # define 1 Action menu prompt method
pr = """
(E)nqueue
(D)equeue
(V)iew
(Q)uit
Enter choice: """
while True:
while True:
try:
choice = raw_input(pr).strip()[0].lower()
# Str.strip() Get rid of String Extra space before and after the object
# Str.lower() Converts multiple inputs to lowercase , It is convenient for the later unification 1 judge
# The input ^D(EOF, produce 1 a EOFError abnormal )
# The input ^C( Break out , produce 1 a keyboardInterrupt abnormal )
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]()
# To obtain Dict Corresponding to the Chinese character functionName, Implement function calls
if __name__ == '__main__':
showmenu()
Queues and stacks are implemented in a similar way, except that the queue always pops the first element first and the stack always pops the last element first.
Thank you for reading, I hope to help you, thank you for your support of this site!