Commit 046828c7 authored by Ben Glocker's avatar Ben Glocker
Browse files

renamed intro notebook

parent aacb7519
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "source": [
"# Introduction to Python for Algorithms 202" "# Introduction to Python (for Algorithms 2)"
] ]
}, },
{ {
...@@ -28,43 +28,6 @@ ...@@ -28,43 +28,6 @@
"This notebook is by no means a comprehensive introduction to the Python programming language. It covers the essential language features required to implement, test and validate the Algorithms 202 courseworks. It is strongly advised to complement this tutorial with additional reading such as the [official Python documentation](https://docs.python.org/3/), [Python 101](https://leanpub.com/python_101) or the excellent [Hitchhiker's guide to Python](http://docs.python-guide.org/en/latest/)." "This notebook is by no means a comprehensive introduction to the Python programming language. It covers the essential language features required to implement, test and validate the Algorithms 202 courseworks. It is strongly advised to complement this tutorial with additional reading such as the [official Python documentation](https://docs.python.org/3/), [Python 101](https://leanpub.com/python_101) or the excellent [Hitchhiker's guide to Python](http://docs.python-guide.org/en/latest/)."
] ]
}, },
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Getting set up"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To use this notebook, you'll first need to install miniconda. To get set up you can follow the start of the [instructions given here for Windows, OS X, and Linux](http://www.menpo.org/installation/). Only go as far as 'Setting Up A Fresh Environment' then jump back here to install the stuff we need (not menpo).\n",
"\n",
"- Create a Python environment with all the code we need in it\n",
"\n",
"```\n",
"> conda create -n algo202 python=3 pip setuptools wheel matplotlib jupyter\n",
"```\n",
"- Activate the environment. On OS X/Linux, simply run:\n",
"```\n",
"> source activate algo202\n",
"```\n",
"on Windows:\n",
"```\n",
"> activate algo202\n",
"```\n",
"- Finally install the line_profiler tool (you can read more about that at our [blog post](http://www.menpo.org/blog/2014/05/line_profiler_ipython/))\n",
"```\n",
"(algo202) > pip install line_profiler\n",
"```\n",
"- Now we are all set up. In the future you only need to reactivate the environment to get to work. To run this notebook, launch a Jupyter notebook server, and browse to this downloaded file\n",
"```\n",
"(algo202) > jupyter notebook\n",
"```\n",
"- To navigate through the notebook, have a look at this [cheatsheet](https://www.cheatography.com/weidadeyue/cheat-sheets/jupyter-notebook/)"
]
},
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
...@@ -278,9 +241,7 @@ ...@@ -278,9 +241,7 @@
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {},
"collapsed": true
},
"outputs": [], "outputs": [],
"source": [ "source": [
"# simple branching\n", "# simple branching\n",
...@@ -312,9 +273,7 @@ ...@@ -312,9 +273,7 @@
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {},
"collapsed": true
},
"outputs": [], "outputs": [],
"source": [ "source": [
"# loop until\n", "# loop until\n",
...@@ -601,7 +560,9 @@ ...@@ -601,7 +560,9 @@
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": {}, "metadata": {
"collapsed": true
},
"outputs": [], "outputs": [],
"source": [ "source": [
"def bubble_sort(L):\n", "def bubble_sort(L):\n",
...@@ -635,7 +596,9 @@ ...@@ -635,7 +596,9 @@
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": {}, "metadata": {
"collapsed": true
},
"outputs": [], "outputs": [],
"source": [ "source": [
"test_cases = [\n", "test_cases = [\n",
...@@ -722,10 +685,12 @@ ...@@ -722,10 +685,12 @@
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": {}, "metadata": {
"collapsed": true
},
"outputs": [], "outputs": [],
"source": [ "source": [
"sizes = list(range(1, 1000, 100)) + list(range(1000, 10000, 500))\n", "sizes = list(range(1, 1000, 100)) + list(range(1000, 10000, 1000))\n",
"timings = [timed(my_sorted, case) for case in [randlist(size) for size in sizes]]" "timings = [timed(my_sorted, case) for case in [randlist(size) for size in sizes]]"
] ]
}, },
...@@ -739,7 +704,9 @@ ...@@ -739,7 +704,9 @@
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": {}, "metadata": {
"collapsed": true
},
"outputs": [], "outputs": [],
"source": [ "source": [
"%matplotlib inline\n", "%matplotlib inline\n",
...@@ -751,9 +718,7 @@ ...@@ -751,9 +718,7 @@
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {},
"collapsed": true
},
"outputs": [], "outputs": [],
"source": [ "source": [
"plt.plot(sizes, timings, linewidth=4)\n", "plt.plot(sizes, timings, linewidth=4)\n",
...@@ -773,7 +738,9 @@ ...@@ -773,7 +738,9 @@
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": {}, "metadata": {
"collapsed": true
},
"outputs": [], "outputs": [],
"source": [ "source": [
"from numpy import polyfit\n", "from numpy import polyfit\n",
...@@ -786,7 +753,9 @@ ...@@ -786,7 +753,9 @@
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": {}, "metadata": {
"collapsed": true
},
"outputs": [], "outputs": [],
"source": [ "source": [
"from numpy import polyval\n", "from numpy import polyval\n",
......
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
# Introduction to Python for Algorithms 202 # Introduction to Python (for Algorithms 2)
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
by *James Booth* and *Ghislain Antony Vaillant* by *James Booth* and *Ghislain Antony Vaillant*
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Disclaimer ### Disclaimer
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
This notebook is by no means a comprehensive introduction to the Python programming language. It covers the essential language features required to implement, test and validate the Algorithms 202 courseworks. It is strongly advised to complement this tutorial with additional reading such as the [official Python documentation](https://docs.python.org/3/), [Python 101](https://leanpub.com/python_101) or the excellent [Hitchhiker's guide to Python](http://docs.python-guide.org/en/latest/). This notebook is by no means a comprehensive introduction to the Python programming language. It covers the essential language features required to implement, test and validate the Algorithms 202 courseworks. It is strongly advised to complement this tutorial with additional reading such as the [official Python documentation](https://docs.python.org/3/), [Python 101](https://leanpub.com/python_101) or the excellent [Hitchhiker's guide to Python](http://docs.python-guide.org/en/latest/).
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Getting set up
%% Cell type:markdown id: tags:
To use this notebook, you'll first need to install miniconda. To get set up you can follow the start of the [instructions given here for Windows, OS X, and Linux](http://www.menpo.org/installation/). Only go as far as 'Setting Up A Fresh Environment' then jump back here to install the stuff we need (not menpo).
- Create a Python environment with all the code we need in it
```
> conda create -n algo202 python=3 pip setuptools wheel matplotlib jupyter
```
- Activate the environment. On OS X/Linux, simply run:
```
> source activate algo202
```
on Windows:
```
> activate algo202
```
- Finally install the line_profiler tool (you can read more about that at our [blog post](http://www.menpo.org/blog/2014/05/line_profiler_ipython/))
```
(algo202) > pip install line_profiler
```
- Now we are all set up. In the future you only need to reactivate the environment to get to work. To run this notebook, launch a Jupyter notebook server, and browse to this downloaded file
```
(algo202) > jupyter notebook
```
- To navigate through the notebook, have a look at this [cheatsheet](https://www.cheatography.com/weidadeyue/cheat-sheets/jupyter-notebook/)
%% Cell type:markdown id: tags:
## Language basics ## Language basics
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Syntax and features ### Syntax and features
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### Hello world #### Hello world
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
print("Hello, world!") print("Hello, world!")
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### Built-in [functions](https://docs.python.org/3/library/functions.html) #### Built-in [functions](https://docs.python.org/3/library/functions.html)
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
print("Hello, world!") print("Hello, world!")
print("Hello,", "world!") print("Hello,", "world!")
print("{}, {}!".format("Hello", "world")) print("{}, {}!".format("Hello", "world"))
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
help(print) help(print)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
type(1.0) type(1.0)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
assert(2 % 2 == 0) assert(2 % 2 == 0)
#assert(2 / 2 == 0) #assert(2 / 2 == 0)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### Built-in [types](https://docs.python.org/3/library/stdtypes.html) #### Built-in [types](https://docs.python.org/3/library/stdtypes.html)
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# Booleans # Booleans
B = True B = True
print(type(B)) print(type(B))
# Numeric types # Numeric types
N = 1 N = 1
print(type(N)) print(type(N))
N = 1.0 N = 1.0
print(type(N)) print(type(N))
N = 1j N = 1j
print(type(N)) print(type(N))
# Strings # Strings
N = "Hello, word" N = "Hello, word"
print(type(N)) print(type(N))
# Lists # Lists
L = [False, 1.0, "Hello"] L = [False, 1.0, "Hello"]
print(type(L)) print(type(L))
# Ranges # Ranges
R = range(10) R = range(10)
print(type(R)) print(type(R))
# None # None
print(type(None)) print(type(None))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### Dynamic typing #### Dynamic typing
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
x = 3 # Defines a binding a variable named "x", x = 3 # Defines a binding a variable named "x",
# to an object of type integer with value 3. # to an object of type integer with value 3.
print('x is of type {} with value {}'.format(type(x), x)) print('x is of type {} with value {}'.format(type(x), x))
x = 2.0 # Redefine the binding between "x" and an x = 2.0 # Redefine the binding between "x" and an
# object of type float with value 2.0. # object of type float with value 2.0.
print('x is of type {} with value {}'.format(type(x), x)) print('x is of type {} with value {}'.format(type(x), x))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### Strong typing #### Strong typing
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
print(1 + '2') # What is the intent here? print(1 + '2') # What is the intent here?
# "Explicit is better than implicit." # "Explicit is better than implicit."
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
print(str(1) + '2') # String concatenation. print(str(1) + '2') # String concatenation.
print(1 + int('2')) # Integer summation. print(1 + int('2')) # Integer summation.
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### Variables and scopes #### Variables and scopes
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
a = 0 a = 0
if False: if False:
b = 1 b = 1
def my_function(c): def my_function(c):
d = 3 d = 3
print(a) # a is global print(a) # a is global
print(b) # b is global print(b) # b is global
print(c) # c is local print(c) # c is local
print(d) # d is local print(d) # d is local
my_function(2) my_function(2)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Control flow ### Control flow
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### `if` statements #### `if` statements
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# simple branching # simple branching
if condition: if condition:
do_something() do_something()
# 2-way branching # 2-way branching
if condition: if condition:
do_something() do_something()
else: else:
do_other_thing() do_other_thing()
# switch-case style # switch-case style
if condition: if condition:
do_something() do_something()
elif other_condition: elif other_condition:
do_other_thing() do_other_thing()
else: else:
do_default_thing() do_default_thing()
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### `while` statements #### `while` statements
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# loop until # loop until
while condition: while condition:
do_something() do_something()
# loop until with break clause # loop until with break clause
while condition: while condition:
do_something() do_something()
if specific_condition: if specific_condition:
break # exit while loop regardless break # exit while loop regardless
do_other_thing() do_other_thing()
# loop until with break clause # loop until with break clause
while condition: while condition:
do_something() do_something()
if specific_condition: if specific_condition:
continue # loop-back regardless continue # loop-back regardless
do_other_thing() do_other_thing()
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### `for` statements #### `for` statements
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
for n in range(10): for n in range(10):
print(n) print(n)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
numbers = [1, 2, 3] numbers = [1, 2, 3]
for number in numbers: for number in numbers:
print(number) print(number)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
ingredients = ['carrots', 'leeks', 'potatoes'] ingredients = ['carrots', 'leeks', 'potatoes']
for index, ingredient in enumerate(ingredients): for index, ingredient in enumerate(ingredients):
print(index, ingredient) print(index, ingredient)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Data structures ### Data structures
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### Common concepts #### Common concepts
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# literals # literals
vowels = ['a', 'e', 'i', 'o', 'u', 'y'] vowels = ['a', 'e', 'i', 'o', 'u', 'y']
print('vowels: {}'.format(vowels)) print('vowels: {}'.format(vowels))
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# indexing # indexing
print('the first vowel is: ' + vowels[0]) print('the first vowel is: ' + vowels[0])
print('the last vowel is: ' + vowels[-1]) print('the last vowel is: ' + vowels[-1])
print('the second-to-last vowel is: ' + vowels[-2]) print('the second-to-last vowel is: ' + vowels[-2])
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# slicing # slicing
print('first three: {}'.format(vowels[:3])) print('first three: {}'.format(vowels[:3]))
print('last two: {}'.format(vowels[-2:])) print('last two: {}'.format(vowels[-2:]))
print('middle ones: {}'.format(vowels[1:-1])) print('middle ones: {}'.format(vowels[1:-1]))
print('one each two: {}'.format(vowels[::2])) print('one each two: {}'.format(vowels[::2]))
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# iteration # iteration
for vowel in vowels: for vowel in vowels:
print(vowel.upper()) print(vowel.upper())
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# enumeration # enumeration
for index, vowel in enumerate(vowels): for index, vowel in enumerate(vowels):
print("vowel {} is {}".format(1+index, vowel)) print("vowel {} is {}".format(1+index, vowel))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### Immutable sequences #### Immutable sequences
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
vowels = ('a', 'e', 'i', 'o', 'u', 'y') vowels = ('a', 'e', 'i', 'o', 'u', 'y')
print(type(vowels)) print(type(vowels))
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
vowels[1] = 'b' vowels[1] = 'b'
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### Mutable sequences #### Mutable sequences
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
vowels = ['a', 'e', 'i', 'o', 'u', 'y'] vowels = ['a', 'e', 'i', 'o', 'u', 'y']
print(type(vowels)) print(type(vowels))
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
vowels[1] = 'b' vowels[1] = 'b'
print(vowels) print(vowels)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### Dictionaries #### Dictionaries
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# build using literal construct: {k1: v1, k2:v2} # build using literal construct: {k1: v1, k2:v2}
D = {"one": 1, D = {"one": 1,
"two": 2, "two": 2,
"three": 3} "three": 3}
print('D: {}'.format(D)) print('D: {}'.format(D))
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# indexing # indexing
print(D["one"]) print(D["one"])
print(D["two"]) print(D["two"])
print(D["three"]) print(D["three"])
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# iterating # iterating
for item in D.items(): for item in D.items():
print(item) print(item)
for key in D.keys(): for key in D.keys():
print(key) print(key)
for value in D.values(): for value in D.values():
print(value) print(value)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Functions ### Functions
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# Standard definiton # Standard definiton
def my_function(arg1, arg2): def my_function(arg1, arg2):
# Do something with arg1, arg2 # Do something with arg1, arg2
# ... # ...
return result return result
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# Lambda definition # Lambda definition
x_power_x = lambda x: x**x x_power_x = lambda x: x**x
print(x_power_x(2)) print(x_power_x(2))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Application: Complexity analysis of bubble sort ## Application: Complexity analysis of bubble sort
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Implementation ### Implementation
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
def bubble_sort(L): def bubble_sort(L):
""" """
Sorts the input list inplace using a deterministic version of the bubble sort algorithm [1]. Sorts the input list inplace using a deterministic version of the bubble sort algorithm [1].
[1] https://en.wikipedia.org/wiki/Bubble_sort [1] https://en.wikipedia.org/wiki/Bubble_sort
""" """
max_pass = len(L) - 1 max_pass = len(L) - 1
for pass_num in range(max_pass): for pass_num in range(max_pass):
for i in range(max_pass-pass_num): for i in range(max_pass-pass_num):
if L[i+1] < L[i]: if L[i+1] < L[i]:
L[i], L[i+1] = L[i+1], L[i] L[i], L[i+1] = L[i+1], L[i]
return L return L
def my_sorted(iterable): def my_sorted(iterable):
""" """
Returns the sorted elements of the iterable as a list. Returns the sorted elements of the iterable as a list.
""" """
return bubble_sort(list(iterable)) return bubble_sort(list(iterable))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Unit testing ### Unit testing
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
test_cases = [ test_cases = [
[3, 2, 1, 6, 5, 4], [3, 2, 1, 6, 5, 4],
[6, 5, 4, 3, 2, 1], # Worst case [6, 5, 4, 3, 2, 1], # Worst case
[1, 3, 2, 4, 6, 5], # One pass required [1, 3, 2, 4, 6, 5], # One pass required
] ]
for case in test_cases: for case in test_cases:
# Validate against built-in sorted # Validate against built-in sorted
#print(my_sorted(case), sorted(case)) #print(my_sorted(case), sorted(case))
assert(my_sorted(case) == sorted(case)) assert(my_sorted(case) == sorted(case))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Complexity analysis ### Complexity analysis
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### Data generation #### Data generation
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
from random import randint from random import randint
help(randint) help(randint)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
randlist = lambda n: [randint(1e1, 1e6) for i in range(n)] randlist = lambda n: [randint(1e1, 1e6) for i in range(n)]
print(randlist(10)) print(randlist(10))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### Timing method #### Timing method
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
def timed(f, *args, **kwargs): def timed(f, *args, **kwargs):
from time import clock from time import clock
before = clock() before = clock()
result = f(*args, **kwargs) result = f(*args, **kwargs)
after = clock() after = clock()
return after-before return after-before
# Collect enough time samples # Collect enough time samples
timings = [timed(my_sorted, case) for case in [randlist(6) for n in range(1000)]] timings = [timed(my_sorted, case) for case in [randlist(6) for n in range(1000)]]
from statistics import mean from statistics import mean
print("min = {}, max = {}, mean = {}".format( print("min = {}, max = {}, mean = {}".format(
min(timings), max(timings), mean(timings))) min(timings), max(timings), mean(timings)))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### Experiment #### Experiment
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
sizes = list(range(1, 1000, 100)) + list(range(1000, 10000, 500)) sizes = list(range(1, 1000, 100)) + list(range(1000, 10000, 1000))
timings = [timed(my_sorted, case) for case in [randlist(size) for size in sizes]] timings = [timed(my_sorted, case) for case in [randlist(size) for size in sizes]]
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### Plotting #### Plotting
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
%matplotlib inline %matplotlib inline
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
# Uncomment for details about the plot function # Uncomment for details about the plot function
#help(plt.plot) #help(plt.plot)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
plt.plot(sizes, timings, linewidth=4) plt.plot(sizes, timings, linewidth=4)
plt.xlabel('size') plt.xlabel('size')
plt.ylabel('time (s)') plt.ylabel('time (s)')
plt.xlim(0) plt.xlim(0)
plt.ylim(0) plt.ylim(0)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### Fitting #### Fitting
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
from numpy import polyfit from numpy import polyfit
# Uncomment for details about polyfit # Uncomment for details about polyfit
#help(polyfit) #help(polyfit)
poly = polyfit(sizes, timings, deg=2) poly = polyfit(sizes, timings, deg=2)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
from numpy import polyval from numpy import polyval
# Uncomment for details about polyval # Uncomment for details about polyval
#help(polyval) #help(polyval)
fitted = polyval(poly, sizes) fitted = polyval(poly, sizes)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
plt.plot(sizes, timings, '-', linewidth=4) plt.plot(sizes, timings, '-', linewidth=4)
plt.plot(sizes, fitted, '--', linewidth=4) plt.plot(sizes, fitted, '--', linewidth=4)
plt.xlabel('size') plt.xlabel('size')
plt.ylabel('time (s)') plt.ylabel('time (s)')
plt.xlim(0) plt.xlim(0)
plt.ylim(0) plt.ylim(0)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Going further ### Going further
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
- Provide an alternative implementation of bubble sort with the optimization tricks explained in the Wikipedia article. - Provide an alternative implementation of bubble sort with the optimization tricks explained in the Wikipedia article.
- Modify the `my_sorted` function to allow users to choose between the deterministic and the optimized implementations. By default, `my_sorted` should still be using the determinisitic version. - Modify the `my_sorted` function to allow users to choose between the deterministic and the optimized implementations. By default, `my_sorted` should still be using the determinisitic version.
- Run the experiment above with the optimized bubble sort implementation. - Run the experiment above with the optimized bubble sort implementation.
- Compare the deterministic and optimized implementations with a plot. - Compare the deterministic and optimized implementations with a plot.
- Draw some conclusions from this analysis. - Draw some conclusions from this analysis.
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment