fork download
  1. # Queue.py
  2. # Mechanical MOOC
  3. # MIT OCW 6.189 Homework 3
  4. # Exercise 3.6 - Your First Class
  5. # Glenn Richard
  6. # July 21, 2013
  7. import random
  8.  
  9. class Queue:
  10. class __Node:
  11. # private class
  12. def __init__(self, cargo):
  13. self.cargo = cargo
  14. self.next = None
  15. def __init__(self):
  16. # Initialize an empty Queue.
  17. # private attributes
  18. self.__front = None
  19. self.__back = None
  20. def insert(self, cargo):
  21. # Add a new node to the front to contain the cargo.
  22. node = self.__Node(cargo)
  23. if self.__front == None:
  24. # The Queue was empty.
  25. self.__front = node
  26. else:
  27. # The Queue was not empty.
  28. self.__back.next = node
  29. self.__back = node
  30.  
  31. def remove(self):
  32. # Remove the front node and return its cargo.
  33. if self.__front == None:
  34. # The Queue was empty, so return None.
  35. return None
  36. # The Queue was not empty, so update the pointers and return the front cargo.
  37. cargo = self.__front.cargo
  38. self.__front = self.__front.next
  39. if self.__front == None:
  40. self.__back = None
  41. return cargo
  42.  
  43. def isEmpty(self):
  44. # Is the Queue empty?
  45. return self.__front == None
  46.  
  47. def __str__(self):
  48. # Return a string representation of all the cargo in the Queue nodes.
  49. qList = []
  50. p = self.__front
  51. while p != None:
  52. qList.append(p.cargo)
  53. p = p.next
  54. return "front: " + str(qList) + " :back"
  55.  
  56. # Create and test a new Queue by adding and removing random integers.
  57. q = Queue()
  58. for i in range(20):
  59. n = random.randint(0, 9)
  60. print("n -> " + str(n))
  61. if n >= 5:
  62. x = q.remove()
  63. print("removed " + str(x))
  64. else:
  65. q.insert(n)
  66. print("inserted " + str(n))
  67. print(q)
Success #stdin #stdout 0.16s 12384KB
stdin
Standard input is empty
stdout
n -> 1
inserted 1
front: [1] :back
n -> 0
inserted 0
front: [1, 0] :back
n -> 1
inserted 1
front: [1, 0, 1] :back
n -> 5
removed 1
front: [0, 1] :back
n -> 5
removed 0
front: [1] :back
n -> 3
inserted 3
front: [1, 3] :back
n -> 8
removed 1
front: [3] :back
n -> 8
removed 3
front: [] :back
n -> 1
inserted 1
front: [1] :back
n -> 9
removed 1
front: [] :back
n -> 2
inserted 2
front: [2] :back
n -> 9
removed 2
front: [] :back
n -> 5
removed None
front: [] :back
n -> 3
inserted 3
front: [3] :back
n -> 9
removed 3
front: [] :back
n -> 0
inserted 0
front: [0] :back
n -> 1
inserted 1
front: [0, 1] :back
n -> 2
inserted 2
front: [0, 1, 2] :back
n -> 0
inserted 0
front: [0, 1, 2, 0] :back
n -> 8
removed 0
front: [1, 2, 0] :back