|
| 1 | +#!/usr/bin/env python |
| 2 | +''' |
| 3 | +$Id$ |
| 4 | +
|
| 5 | +queue.py -- simulate queue data structures using lists |
| 6 | +
|
| 7 | +NOTE: as of the time of publication, there is a bug in JPython1.1 |
| 8 | +that does not recognize arguments for the list pop() method: |
| 9 | +TypeError: pop(): expected 0 args; got 1 |
| 10 | +
|
| 11 | +Exercises: |
| 12 | +
|
| 13 | +13-9) create a Queue class |
| 14 | +
|
| 15 | +13-10) create a class similar to arrays in Perl which have |
| 16 | +both queue- and stack-like qualities and features |
| 17 | +''' |
| 18 | + |
| 19 | +# create our data structure |
| 20 | +queue = [] |
| 21 | + |
| 22 | +# |
| 23 | +# enQ() -- add string to end of queue |
| 24 | +# |
| 25 | +def enQ(): |
| 26 | +queue.append(raw_input('Enter new queue element: ')) |
| 27 | + |
| 28 | +# |
| 29 | +# deQ() -- remove string from front of queue |
| 30 | +# |
| 31 | +def deQ(): |
| 32 | +if len(queue) == 0: |
| 33 | +print 'Cannot dequeue from empty queue!' |
| 34 | +else: |
| 35 | +print 'Removed [', queue.pop(0), ']' |
| 36 | + |
| 37 | +# |
| 38 | +# viewQ() -- display queue contents |
| 39 | +# |
| 40 | +def viewQ(): |
| 41 | +print str(queue) |
| 42 | + |
| 43 | +# |
| 44 | +# showmenu() -- interactive portion of application |
| 45 | +# displays menu to prompt user and takes |
| 46 | +# action based on user response |
| 47 | +# |
| 48 | +def showmenu(): |
| 49 | +prompt = """ |
| 50 | +(E)nqueue |
| 51 | +(D)equeue |
| 52 | +(V)iew |
| 53 | +(Q)uit |
| 54 | +
|
| 55 | +Enter choice: """ |
| 56 | + |
| 57 | +# loop until user quits |
| 58 | +done = 0 |
| 59 | +while not done: |
| 60 | + |
| 61 | +# loop until user choses valid option |
| 62 | +chosen = 0 |
| 63 | +while not chosen: |
| 64 | + |
| 65 | +# if user hits ^C or ^D (EOF), |
| 66 | +# pretend they typed 'q' to quit |
| 67 | +try: |
| 68 | +choice = raw_input(prompt)[0] |
| 69 | +except (IndexError, EOFError, KeyboardInterrupt): |
| 70 | +choice = 'q' |
| 71 | +print '\nYou picked: [%s]' % choice |
| 72 | + |
| 73 | +# validate option chosen |
| 74 | +if choice not in 'devq': |
| 75 | +print 'invalid option, try again' |
| 76 | +else: |
| 77 | +chosen = 1 |
| 78 | + |
| 79 | +# take appropriate action |
| 80 | +if choice == 'q': |
| 81 | +done = 1 |
| 82 | +if choice == 'e': |
| 83 | +enQ() |
| 84 | +if choice == 'd': |
| 85 | +deQ() |
| 86 | +if choice == 'v': |
| 87 | +viewQ() |
| 88 | + |
| 89 | +# run showmenu() as the application |
| 90 | +if __name__ == '__main__': |
| 91 | +showmenu() |
0 commit comments