Numbers, Strings, and Dictionaries

Exercise 1

In [1]:
4 ** 3  # output is int
Out[1]:
64
In [2]:
2 + 3.4 ** 2  # output is float
Out[2]:
13.559999999999999
In [3]:
(1 + 1j) ** 2  # output is complex
Out[3]:
2j

Exercise 2

In [4]:
# Define string
a = "Hello, egg world!"

# Find position of 'egg' word
pos = a.index('egg')

# Make new string
new_string = a[:pos] + a[pos+4:]

# Print out to check
print(new_string)
Hello, world!

Exercise 3

In [5]:
s = "CAGTACCAAGTGAAAGAT"
s.count("A")
Out[5]:
8
In [6]:
a = [1, 2, 3]
b = [4, 5, 6]
a + b
Out[6]:
[1, 2, 3, 4, 5, 6]

Booleans, Tuples, and Dictionaries

Exercise 1

In [7]:
x = 3.7
(x > 3.4 and x <= 6.6) or x == 2
Out[7]:
True

Exercise 2

In [8]:
words = {}
words['Table'] = 'Tisch'
words['Chair'] = 'Stuhl'
words['Snake'] = 'Schlange'
In [9]:
words['Chair']
Out[9]:
'Stuhl'

Control Flow

Exercise 1 and 2

In [10]:
for i in range(2, 51):  # just to 50 for this example

    # Set is_prime 'flag' to initial value
    is_prime = True

    # Try and divide i by all values between 2 and i-1, and if none of them
    # work, then the value is prime.
    for j in range(2, i):

        # Check if i is divisible by j
        if i % j == 0:
            is_prime = False
            break


    if is_prime:
        print(i)
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47

There are other ways of doing this, e.g.:

In [11]:
for i in range(2, 51):
    for j in range(2, i):
        if i % j == 0:
            break
    else:  # this gets executed if break is not called
        print(i)
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47

Exercise 3

In [12]:
a = 0
b = 1
while a < 100000:
    print(a)
    c = a  # save a to old variable
    a = b
    b = c + b
0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765
10946
17711
28657
46368
75025

Even simpler:

In [13]:
a, b = 0, 1
while a < 100000:
    print(a)
    a, b = b, a + b
0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765
10946
17711
28657
46368
75025

With a list:

In [14]:
fib = [0, 1]
while fib[-1] + fib[-2] < 100000:
    fib.append(fib[-1] + fib[-2])
print(fib)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025]

Functions

Exercise 1

In [15]:
def is_prime(x):
    for j in range(2, x):
        if x % j == 0:
            return False
    return True
In [16]:
is_prime(7)
Out[16]:
True

Exercise 2

With loop

In [17]:
def factorial(x):
    fact = 1
    for i in range(1,x+1):
        fact = fact * i
    return fact

Without loop

In [18]:
def factorial(x):
    if x > 0:
        return x * factorial(x - 1)
    else:
        return 1

Exercise 3

In [19]:
def mean(x):
    return sum(x) / float(len(x))
In [20]:
mean([1, 3, 4, 5, 6, 7])
Out[20]:
4.333333333333333

Modules

In [21]:
import math
In [22]:
math.cos(math.radians(60))
Out[22]:
0.5000000000000001
In [23]:
math.sin(math.pi / 6)
Out[23]:
0.49999999999999994

Introduction to Numpy

Exercise 1

In [24]:
import numpy as np
np.logspace(-20, -10, 11)
Out[24]:
array([  1.00000000e-20,   1.00000000e-19,   1.00000000e-18,
         1.00000000e-17,   1.00000000e-16,   1.00000000e-15,
         1.00000000e-14,   1.00000000e-13,   1.00000000e-12,
         1.00000000e-11,   1.00000000e-10])
In [25]:
np.repeat(2, 10)
Out[25]:
array([2, 2, 2, 2, 2, 2, 2, 2, 2, 2])
In [26]:
np.empty(10)  # sometimes returns values != 0 because uninitialized
Out[26]:
array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])
In [27]:
np.zeros(5, dtype=np.float32)
Out[27]:
array([ 0.,  0.,  0.,  0.,  0.], dtype=float32)

Exercise 2

In [28]:
x = np.random.random(10)
In [29]:
x[1:] - x[:-1]
Out[29]:
array([ 0.30405148, -0.31716464,  0.01466258, -0.05792893, -0.58369353,
        0.88535054, -0.22194112, -0.33465424, -0.2066631 ])
In [30]:
np.diff(x)
Out[30]:
array([ 0.30405148, -0.31716464,  0.01466258, -0.05792893, -0.58369353,
        0.88535054, -0.22194112, -0.33465424, -0.2066631 ])

Exercise 3

In [31]:
filename = "data/vienna_daily_temperatures_with_bad_data.txt"
date, tmin, tmax = np.loadtxt(filename, unpack=True)
In [32]:
keep = np.abs(tmax) < 50
In [33]:
date_good = date[keep]
tmax_good = tmax[keep]

Introduction to Matplotlib

Exercise 1

In [34]:
# The following code reads in the file and removes bad values
date, tmin, tmax = np.loadtxt('data/vienna_daily_temperatures_with_bad_data.txt', unpack=True)
keep = np.abs(tmax) < 90
date = date[keep]
tmax = tmax[keep]
In [35]:
%matplotlib inline
import matplotlib.pyplot as plt
In [36]:
plt.plot(date, tmax, '.')
Out[36]:
[<matplotlib.lines.Line2D at 0x109239898>]
In [37]:
plt.plot(date % 1, tmax, '.')
Out[37]:
[<matplotlib.lines.Line2D at 0x109337b38>]

Exercise 2

In [38]:
def gaussian(x, amplitude, offset, sigma):
    return 1. / np.sqrt(2 * np.pi) / sigma * np.exp(-0.5 * (x - offset) ** 2 / sigma ** 2)
In [39]:
values = np.random.normal(0, 1, 100000)
In [40]:
h = plt.hist(values, bins=100, normed=True)
x = np.linspace(-5, 5, 100)
plt.plot(x, gaussian(x, 1, 0, 1), color='red', lw=2)
Out[40]:
[<matplotlib.lines.Line2D at 0x10940b198>]

Exercise 3

In [41]:
total = np.zeros(10000)
In [42]:
values = np.random.random(10000)
total = total + values
In [43]:
h = plt.hist(total, bins=30)
In [44]:
values = np.random.random(10000)
total = total + values
In [45]:
h = plt.hist(total / 2., bins=30)
In [46]:
for iter in range(8):  # already did it twice
    values = np.random.random(10000)
    total = total + values
In [47]:
h = plt.hist(total / 10., bins=30)