Skip to content
Snippets Groups Projects
Commit 2ebeb5b6 authored by Mihai Lefter's avatar Mihai Lefter
Browse files

Add exercises for 2nd introduction session.

parent 932c7678
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id: tags:
<span style="font-size: 200%">Introduction to Python (2)</span>
===
%% Cell type:markdown id: tags:
Sequence types
===
Lists
---
Mutable sequences of values.
%% Cell type:code id: tags:
``` python
l = [2, 5, 2, 3, 7]
type(l)
```
%% Output
list
%% Cell type:markdown id: tags:
Lists can be heterogeneous, but we typically don't use that.
%% Cell type:code id: tags:
``` python
a = 'spezi'
[3, 'abc', 1.3e20, [a, a, 2]]
```
%% Output
[3, 'abc', 1.3e+20, ['spezi', 'spezi', 2]]
%% Cell type:markdown id: tags:
Sequence types
===
Tuples
---
Immutable sequences of values.
%% Cell type:code id: tags:
``` python
t = 'white', 77, 1.5
type(t)
```
%% Output
tuple
%% Cell type:code id: tags:
``` python
color, width, scale = t
width
```
%% Output
77
%% Cell type:markdown id: tags:
Sequence types
===
Strings (1/2)
---
Immutable sequences of characters.
%% Cell type:code id: tags:
``` python
'a string can be written in single quotes'
```
%% Output
'a string can be written in single quotes'
%% Cell type:markdown id: tags:
Strings can also be written with double quotes, or over multiple lines with triple-quotes.
%% Cell type:code id: tags:
``` python
"this makes it easier to use the ' character"
```
%% Output
"this makes it easier to use the ' character"
%% Cell type:code id: tags:
``` python
"""This is a multiline string.
You see? I continued after a blank line."""
```
%% Output
'This is a multiline string.\n\nYou see? I continued after a blank line.'
%% Cell type:markdown id: tags:
Sequence types
===
Strings (2/2)
---
A common operation is formatting strings using argument substitutions.
%% Cell type:code id: tags:
``` python
'{} times {} equals {:.2f}'.format('pi', 2, 6.283185307179586)
```
%% Output
'pi times 2 equals 6.28'
%% Cell type:markdown id: tags:
Accessing arguments by position or name is more readable.
%% Cell type:code id: tags:
``` python
'{1} times {0} equals {2:.2f}'.format('pi', 2, 6.283185307179586)
```
%% Output
'2 times pi equals 6.28'
%% Cell type:code id: tags:
``` python
'{number} times {amount} equals {result:.2f}'.format(number='pi', amount=2,
result=6.283185307179586)
```
%% Output
'pi times 2 equals 6.28'
%% Cell type:markdown id: tags:
Sequence types
===
Common operations (1/2)
---
All sequence types support concatenation, membership/substring tests, indexing, and slicing.
%% Cell type:code id: tags:
``` python
[1, 2, 3] + [4, 5, 6]
```
%% Output
[1, 2, 3, 4, 5, 6]
%% Cell type:code id: tags:
``` python
'bier' in 'we drinken bier vanaf half 5'
```
%% Output
True
%% Cell type:code id: tags:
``` python
'abcdefghijkl'[5]
```
%% Output
'f'
%% Cell type:markdown id: tags:
Sequence types
===
Slicing
---
Slice `s` from `i` to `j` with `s[i:j]`.
%% Cell type:code id: tags:
``` python
'abcdefghijkl'[4:8]
```
%% Output
'efgh'
%% Cell type:code id: tags:
``` python
'abcdefghijkl'[:3]
```
%% Output
'abc'
%% Cell type:markdown id: tags:
We can also define the step `k` with `s[i:j:k]`.
%% Cell type:code id: tags:
``` python
'abcdefghijkl'[7:3:-1]
```
%% Output
'hgfe'
%% Cell type:markdown id: tags:
Sequence types
===
Common operations (2/2)
---
Contrary to strings and tuples, lists are mutable. We can also get their length, smallest/largest item, and number/position of certain items.
%% Cell type:code id: tags:
``` python
len('attacgataggcatccgt')
```
%% Output
18
%% Cell type:code id: tags:
``` python
max([17, 86, 34, 51])
```
%% Output
86
%% Cell type:code id: tags:
``` python
('atg', 22, True, 'atg').count('atg')
```
%% Output
2
%% Cell type:markdown id: tags:
Sequence types
===
Additional operations with lists
---
We can replace, add, remove, reverse and sort items in-place.
%% Cell type:code id: tags:
``` python
l = [1, 2, 3, 4]
l[3] = 7
l.append(1)
l[1:3] = [3, 2]
l.sort()
l.reverse()
```
%% Cell type:code id: tags:
``` python
l
```
%% Output
[7, 3, 2, 1, 1]
%% Cell type:markdown id: tags:
Dictionaries
===
Dictionaries map *hashable* values to arbitrary objects
---
* All built-in immutable objects are hashable.
* No built-in mutable objects are hashable.
%% Cell type:code id: tags:
``` python
d = {'a': 27, 'b': 18, 'c': 12}
type(d)
```
%% Output
dict
%% Cell type:code id: tags:
``` python
d['e'] = 17
'e' in d
```
%% Output
True
%% Cell type:code id: tags:
``` python
d.update({'a': 18, 'f': 2})
d
```
%% Output
{'a': 18, 'b': 18, 'c': 12, 'e': 17, 'f': 2}
%% Cell type:markdown id: tags:
Dictionaries
===
Accessing dictionary content
---
%% Cell type:code id: tags:
``` python
d['b']
```
%% Output
18
%% Cell type:code id: tags:
``` python
d.keys()
```
%% Output
['a', 'c', 'b', 'e', 'f']
%% Cell type:code id: tags:
``` python
d.values()
```
%% Output
[18, 12, 18, 17, 2]
%% Cell type:code id: tags:
``` python
d.items()
```
%% Output
[('a', 18), ('c', 12), ('b', 18), ('e', 17), ('f', 2)]
%% Cell type:markdown id: tags:
Sets
===
Mutable unordered collections of hashable values without duplication
---
%% Cell type:code id: tags:
``` python
x = {12, 28, 21, 17}
type(x)
```
%% Output
set
%% Cell type:code id: tags:
``` python
x.add(12)
x
```
%% Output
{12, 17, 21, 28}
%% Cell type:code id: tags:
``` python
x.discard(21)
x
```
%% Output
{12, 17, 28}
%% Cell type:markdown id: tags:
Sets
===
Operations with sets
---
We can test for membership and apply many common set operations such as union and intersect.
%% Cell type:code id: tags:
``` python
17 in {12, 28, 21, 17}
```
%% Output
True
%% Cell type:code id: tags:
``` python
{12, 28, 21, 17} | {12, 18, 11}
```
%% Output
{11, 12, 17, 18, 21, 28}
%% Cell type:code id: tags:
``` python
{12, 28, 21, 17} & {12, 18, 11}
```
%% Output
{12}
%% Cell type:markdown id: tags:
Booleans
===
Boolean values and operations
---
The two boolean values are written `False` and `True`.
%% Cell type:code id: tags:
``` python
True or False
```
%% Output
True
%% Cell type:code id: tags:
``` python
True and False
```
%% Output
False
%% Cell type:code id: tags:
``` python
not False
```
%% Output
True
%% Cell type:markdown id: tags:
Booleans
===
Comparisons
---
Comparisons can be done on all objects and return a boolean value.
%% Cell type:code id: tags:
``` python
22 * 3 > 66
```
%% Output
False
%% Cell type:markdown id: tags:
We have two equivalence relations: value equality (`==`) and object identity (`is`).
%% Cell type:code id: tags:
``` python
a, b = [1, 2, 3], [1, 2, 3]
a == b
```
%% Output
True
%% Cell type:code id: tags:
``` python
a is b
```
%% Output
False
%% Cell type:markdown id: tags:
Booleans
===
`if` statements
---
(The `print` statement writes a string representation of the given value.)
%% Cell type:code id: tags:
``` python
if 26 <= 17:
print 'Fact: 26 is less than or equal to 17'
elif (26 + 8 > 14) == True:
print 'Did we need the ` == True` part here?'
else:
print 'Nothing seems true'
```
%% Output
Did we need the ` == True` part here?
%% Cell type:markdown id: tags:
Booleans
===
`while` statements
---
Our first looping control structure just repeats until the given expression evaluates to `False`.
%% Cell type:code id: tags:
``` python
i = 0
while i < 5:
print i
i += 1
```
%% Output
0
1
2
3
4
%% Cell type:markdown id: tags:
Notes about syntax
===
Indentation
---
Python uses indentation to delimit blocks
* Instead of `begin ... end` or `{ ... }` in other languages.
* Always increase indentation by *4 spaces*, never use tabs.
* In any case, be consistent.
%% Cell type:code id: tags:
``` python
if False:
if False:
print 'Why am I here?'
else:
while True:
print 'When will it stop?'
print "And we're back to the first indentation level"
```
%% Cell type:markdown id: tags:
Some editors can be configured to behave just like that.
%% Cell type:markdown id: tags:
Notes about syntax
===
Comments
---
Comments are prepended by `#` and completely ignored.
%% Cell type:code id: tags:
``` python
# Add 42 to this list.
l.append(42)
```
%% Cell type:markdown id: tags:
`pass` statements
---
If you ever need a statement syntactically but don't want to do anything, use `pass`.
%% Cell type:code id: tags:
``` python
while False:
# This is never executed anyway.
pass
```
%% Cell type:markdown id: tags:
Useful built-ins
===
Getting help
---
You can get help on almost any object with `help`.
%% Cell type:code id: tags:
``` python
help(range)
```
%% Output
Help on built-in function range in module __builtin__:
range(...)
range([start,] stop[, step]) -> list of integers
Return a list containing an arithmetic progression of integers.
range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
When step is given, it specifies the increment (or decrement).
For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!
These are exactly the valid indices for a list of 4 elements.
%% Cell type:markdown id: tags:
In IPython you can do it faster by typing:
%% Cell type:code id: tags:
``` python
range?
```
%% Cell type:markdown id: tags:
Useful built-ins
===
We'll shortly use the following built-in functions.
%% Cell type:code id: tags:
``` python
range(5, 16)
```
%% Output
[5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
%% Cell type:code id: tags:
``` python
zip(['red', 'white', 'blue'], range(3))
```
%% Output
[('red', 0), ('white', 1), ('blue', 2)]
%% Cell type:code id: tags:
``` python
list('abcdefghijk')
```
%% Output
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']
%% Cell type:markdown id: tags:
Iteration
===
Iterating over a sequence
---
%% Cell type:code id: tags:
``` python
colors = ['red', 'white', 'blue', 'orange']
cities = ['leiden', 'utrecht', 'warmond', 'san francisco']
```
%% Cell type:markdown id: tags:
The `for` statement can iterate over sequence items.
%% Cell type:code id: tags:
``` python
for color in colors:
print color
```
%% Output
red
white
blue
orange
%% Cell type:code id: tags:
``` python
for character in 'blue':
print character
```
%% Output
b
l
u
e
%% Cell type:markdown id: tags:
Iteration
===
Python anti-patterns
---
These are common for programmers coming from other languages.
%% Cell type:code id: tags:
``` python
i = 0
while i < len(colors):
print colors[i]
i += 1
```
%% Output
red
white
blue
orange
%% Cell type:code id: tags:
``` python
for i in range(len(colors)):
print colors[i]
```
%% Output
red
white
blue
orange
%% Cell type:markdown id: tags:
We call them *unpythonic*.
%% Cell type:markdown id: tags:
Iteration
===
Using values *and* indices
---
%% Cell type:code id: tags:
``` python
for i, color in enumerate(colors):
print i, '->', color
```
%% Output
0 -> red
1 -> white
2 -> blue
3 -> orange
%% Cell type:markdown id: tags:
Taking two sequences together
---
%% Cell type:code id: tags:
``` python
for city, color in zip(cities, colors):
print city, '->', color
```
%% Output
leiden -> red
utrecht -> white
warmond -> blue
san francisco -> orange
%% Cell type:markdown id: tags:
Iteration
===
Other iterables
---
Iterating over a dictionary yields keys.
%% Cell type:code id: tags:
``` python
for key in {'a': 33, 'b': 17, 'c': 18}:
print key
```
%% Output
a
c
b
%% Cell type:markdown id: tags:
Iterating over a file yields lines.
%% Cell type:code id: tags:
``` python
for line in open('data/short_file.txt'):
print line
```
%% Output
this short file has two lines
it is used in the example code
%% Cell type:markdown id: tags:
There are many more useful iterables in Python.
%% Cell type:markdown id: tags:
<div class="alert alert-success">
<h1>Hands on!</h1>
<ol>
<li>Make a list with 10 integer elements. Sum all the items in the list.</li>
<li>Make a new list from the above one that does not include the 0th, 4th and 5th elements.
<li>Sum only the elements from the first list which are between the 2nd and 6th elements.
<li>Make a new list that includes only the elements that are greater than 10 from the first list.
<li>Food.
<ul>
<li>Create a dictionary for food products called "prices" and put some values in it, e.g., "apples": 2, "oranges": 1.5, "pears": 3, ...</li>
<li>Create a corresponding dictionary called "stocks" and put the stock values in it, e.g., "apples": 0, "oranges": 1, "pears": 10, ...</li>
<li>Print stock and price information for each food item.</li>
<li>Determine and print how much money you would make if you sold all of your food products.
</ul>
</li>
</ol>
</div>
%% Cell type:markdown id: tags:
Homework assignment
===
https://classroom.github.com/a/QU2iPYKn
%% Cell type:markdown id: tags:
$\S$ Exercise: Iterate over a list
===
First we are going to make a list and fill it with a simple sequence. Then we are going to use this list to print something.
* Make a list containing the numbers 0, 1, ... 9.
* Print the last 10 lines of the song ''99 bottles of beer'' using this list.
%% Cell type:markdown id: tags:
$\S$ Exercise: Analyse a repeat structure
===
We are going to make a repeating DNA sequence and extract some subsequences from it.
* Make a short tandem repeat that consists of three "ACGT" units and five "TTATT" units.
* Print all suffixes of the repeat structure.
**Note:** A suffix is an ending. For example, the word "spam" has five suffixes: "spam", "pam", "am", "m" and "".
* Print all substrings of length 3.
* Print all unique substrings of length 3.
**Hint:** All elements in a set are unique.
%% Cell type:markdown id: tags:
$\S$ Exercise: Boolean comparison
===
Try to guess the outcome of the following statements:
2 * 3 > 4
2 * (3 > 4)
2 * (4 > 3)
%% Cell type:markdown id: tags:
$\S$ Exercise: Combining lists
===
Calculate all coordinates of the line x=y with x < 100.
**Note:** This is the sequence (0, 0), (1, 1), ... (99, 99)
%% Cell type:markdown id: tags:
$\S$ Exercise: Dictionaries
===
We are going to store the output of a function ($f(x) = x^2$) together with its input in a dictionary.
* Make a dictionary containing all squares smaller than 100.
* Print the content of this dictionary in english, e.g., "4 is the square of 2".
%% Cell type:code id: tags:
``` python
from IPython.display import HTML
def css_styling():
styles = open('styles/custom.css', 'r').read()
return HTML('<style>' + styles + '</style>')
css_styling()
```
%% Output
<IPython.core.display.HTML at 0x1873a50>
%% Cell type:markdown id: tags:
Acknowledgements
========
Martijn Vermaat
[Jeroen Laros](mailto:j.f.j.laros@lumc.nl)
Based on
---------
[Python Scientific Lecture Notes](http://scipy-lectures.github.io/)
License
--------
[Creative Commons Attribution 3.0 License (CC-by)](http://creativecommons.org/licenses/by/3.0)
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment