Updated problem solution to use stack's is_empty() method rather than a similar method that used to be in QueueFromStacks.

This commit is contained in:
Donne Martin 2015-05-23 17:04:03 -04:00
parent 273d0efcb4
commit 9fefcd12f0

View File

@ -85,7 +85,7 @@
},
{
"cell_type": "code",
"execution_count": 3,
"execution_count": null,
"metadata": {
"collapsed": true
},
@ -96,7 +96,7 @@
},
{
"cell_type": "code",
"execution_count": 8,
"execution_count": null,
"metadata": {
"collapsed": false
},
@ -107,52 +107,28 @@
" self.left_stack = Stack()\n",
" self.right_stack = Stack()\n",
"\n",
" def is_stack_empty(self, stack):\n",
" return stack.peek() is None\n",
"\n",
" def shift_stacks(self, source, destination):\n",
" while source.peek() is not None:\n",
" destination.push(source.pop())\n",
"\n",
" def enqueue(self, data):\n",
" if self.is_stack_empty(self.left_stack) and not self.is_stack_empty(self.right_stack):\n",
" if self.left_stack.is_empty() and not self.right_stack.is_empty():\n",
" self.shift_stacks(self.right_stack, self.left_stack)\n",
" self.left_stack.push(data)\n",
"\n",
" def dequeue(self):\n",
" if self.is_stack_empty(self.right_stack) and not self.is_stack_empty(self.left_stack):\n",
" if self.right_stack.is_empty() and not self.left_stack.is_empty():\n",
" self.shift_stacks(self.left_stack, self.right_stack)\n",
" return self.right_stack.pop()"
]
},
{
"cell_type": "code",
"execution_count": 14,
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Dequeue on empty stack\n",
"None\n",
"Enqueue on empty stack\n",
"Enqueue on non-empty stack\n",
"Multiple enqueue in a row\n",
"Dequeue on non-empty stack\n",
"Dequeue after an enqueue\n",
"0\n",
"Multiple dequeue in a row\n",
"1\n",
"2\n",
"Enqueue after a dequeue\n",
"5\n",
"None\n"
]
}
],
"outputs": [],
"source": [
"print('Dequeue on empty stack')\n",
"queue = QueueFromStacks()\n",
@ -173,15 +149,6 @@
"queue.enqueue(5)\n",
"print(queue.dequeue())"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {