Skip to content

Instantly share code, notes, and snippets.

@jabooth
Created March 8, 2015 17:08
Show Gist options
  • Select an option

  • Save jabooth/1deddfe2a913a3a688ad to your computer and use it in GitHub Desktop.

Select an option

Save jabooth/1deddfe2a913a3a688ad to your computer and use it in GitHub Desktop.
Advanced Python - 2. Containers
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"###Data structures - choosing the right tool for the job\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"####Scenario 1.\n",
"\n",
"Store an ordered collection of employee names. Names are added each time an employee wins a chess game."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"all chess winners in order ['Patrick', 'James', 'James']\n",
"winner of the second chess game: James\n"
]
}
],
"source": [
"# list is the perfect choice:\n",
"# - ordered\n",
"# - efficient to extend\n",
"chess_winners = ['Patrick', 'James']\n",
"chess_winners.append('James') # James is on a winning streak!\n",
"print('all chess winners in order {}'.format(chess_winners))\n",
"print('winner of the second chess game: {}'.format(chess_winners[1]))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"####Scenario 2.\n",
"\n",
"Store a collection of employee's who work on a given team"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# we know that employees should be unique - a set is the natural choice.\n",
"executive_employees = {'Jack', 'Jill', 'Joan'}\n",
"dodgeball_employees = {'Carrie', 'Martina', 'Jack'}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"####Scenario 3.\n",
"\n",
"For each location a company operates, store a collection of employee's names.\n",
"\n",
"In future you will want to efficiently retrieve a given offices' employees."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"employees working in Bristol are: {'Hannah', 'Joan', 'Jack', 'Martina'}\n"
]
}
],
"source": [
"# dictionary's are perfect for relationships.\n",
"# notice we are filling the dictionary in with more sets.\n",
"employees_in_region = {'london': {'Carrie', 'John', 'Bob', 'Lisa'},\n",
" 'leeds': {'Patrick', 'George', 'Martina'},\n",
" 'bristol': {'Hannah', 'Jack', 'Martina', 'Joan'}}\n",
"\n",
"print('employees working in Bristol '\n",
" 'are: {}'.format(employees_in_region['bristol']))"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"whos in 'brxxistol'?: None\n"
]
}
],
"source": [
"# get can be used when you don't want an Exception thrown\n",
"# when a key is missing...\n",
"print(\"whos in 'brxxistol'?: {}\".format(employees_in_region.get('brxxistol')))"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": true,
"internals": {
"slide_type": "subslide"
},
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"####Scenario 4.\n",
"\n",
"Find all the employees that are on the executive team and working in bristol, but don't play dodgeball."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false,
"internals": {
"slide_helper": "subslide_end"
},
"slide_helper": "slide_end",
"slideshow": {
"slide_type": "-"
}
},
"outputs": [
{
"data": {
"text/plain": [
"{'Joan'}"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# sets make solving relational problems trivial.\n",
"(employees_in_region['bristol'] & executive_employees) - dodgeball_employees"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"####Scenario 5.\n",
"\n",
"Store the state of the battleships board game."
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# classes are simple to define\n",
"class BattleShip:\n",
" \n",
" def __init__(self, size):\n",
" self.size = size\n",
" \n",
" def __str__(self):\n",
" return \"Ship of size {}\".format(self.size)\n",
" \n",
"# tuples are perfect for storing the ships positions.\n",
"# they can be used to form compound datastructures. \n",
"# As long as their contents, are hashable, they are hashable.\n",
"player1_board = {\n",
" (0, 1): BattleShip(2),\n",
" (4, 2): BattleShip(5)\n",
"}\n",
"\n",
"player2_board = {\n",
" (2, 3): BattleShip(2),\n",
" (4, 2): BattleShip(5)\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Player 1's board\n",
"(0, 1): Ship of size 2\n",
"(4, 2): Ship of size 5\n",
"\n",
"Player 2's board\n",
"(4, 2): Ship of size 5\n",
"(2, 3): Ship of size 2\n"
]
}
],
"source": [
"print(\"Player 1's board\")\n",
"for position in player1_board:\n",
" print(\"{}: {}\".format(position, player1_board[position]))\n",
" \n",
" \n",
"print(\"\\nPlayer 2's board\")\n",
"for position in player2_board:\n",
" print(\"{}: {}\".format(position, player2_board[position]))"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.4.2"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment