 # Introduction to the Tutorials¶

## Organisation of the Tutorials¶

• Coding-Exercises
• Teams of 3
• Turned in using gitlab
• Votier-Exercises
• Everyone on his/her own
• Each tutorial mark the exercises you have done
• Mandatory requirements
• 50% of all Coding-Exercises
• 50% of all Votier-Exercises

## Learning Goals for this Lecture¶

You should be able to complete the AI exercises (from a programming language point of view).

1. "Understand basic Python"
• Be familiar with Python's Unittests and Doctests
• Git pull/push your execises and solutions

There are small programming exercises to give you feedback! Try them!

# Prerequisite¶

## Installation (python)¶

• For Beginners: Anaconda 2 (python 2.7) (All OS supported)
Full featured scientific python distribution. Already contains the important packages.
• Linux users: System python 2 and packages
Use your systems package manager to install python 2 and packages (numpy required).
• Know what your doing?: python virtual environment
Install packages with pip (numpy required). Always up to date
• (Optional) Interactive and REPL: python (installed), ipython, bpython, jupyter notebook

# Python Tutorial¶

## Things to mention¶

• Indentation: use 4 spaces, *do not use tabs*!
• Python is different from Java: you don't need classes
• PEP8 style guide

#### python2 vs python3. $\Rightarrow$ Use python 2.7 for the exercises¶

In [ ]:
help(range)
type?


## Control Flow¶

In [ ]:
# if/elif/else
a = 6
if a > 5:
print "bigger than 5"
elif a == 5:
print "FIVE"
else:
print 'something else: ' + str(a)

In [ ]:
a = 4
a = "bigger" if a > 3 else "smaller"
a

In [ ]:
# Java:
# int n = 6
# for (int i = 2; i < n; i++) {
#   System.out.println(i);
# }
n = 6
for i in range(2,n):
print i

In [ ]:
range(2,10,2)

In [ ]:
movies = ["Her", "Moon", "Pacific Rim", "Robot and Frank"]
print len(movies)
for movie in movies:
print movie

In [ ]:
for i, movie in enumerate(movies):
print i, movie

In [ ]:
for i, movie in zip(range(len(movies)), movies):
print i, movie

In [ ]:
print enumerate(movie)
print zip(range(len(movies)), movies)

In [ ]:
# while
i = 0
while True:
while True:
print i
i += 1
if i > 5:
break
print "outer"
break


## Data Structures¶

In [ ]:
# numbers
print type(1)
print type(.1)

In [ ]:
# Strings
'this is a string'

In [ ]:
"this is also a string"

In [ ]:
"""This is a string as well

A multi-line string
"""

In [ ]:
# list
i = [1, 2, 3, 4]
print list(i)
print [2, 4]

In [ ]:
['something', 5, 5.5]

In [ ]:
movies = ["Her", "Moon", "Pacific Rim", "Robot and Frank"]
movies

In [ ]:
movies.append("Wall-E")
movies

In [ ]:
movies = movies + ["Nummer 5", "I, Robot", "2001"]
movies

In [ ]:
import copy
copy.deepcopy(movies)

In [ ]:
# slicing
print movies
print movies

In [ ]:
print movies

In [ ]:
print movies[0:2]

In [ ]:
print movies[:2]

In [ ]:
print movies[-1]

In [ ]:
print movies[-2]

In [ ]:
print movies[3::2]

In [ ]:
# Dictionaries
print dict()
print {}

In [ ]:
d = {"Her": 4,
"Moon": 5,
"Pacific Rim": 5,
"Robot and Frank": 4.,
}
d

In [ ]:
d["Her"]

In [ ]:
"Her" in movies

In [ ]:
d.keys()

In [ ]:
type(d.values())

In [ ]:
for (key, value) in d.items():
print key, value

In [ ]:
# tuples
3, 4

In [ ]:
(3, 4)

In [ ]:
type((3,4))

In [ ]:
t = 3, 4, 3
print t
print t
print t

In [ ]:
# set
set([3, 0, -4, 15, 3, 2, 2, 1, 15])


## List Comprehensions¶

In [ ]:
[i for i in range(10)]

In [ ]:
[i*i for i in range(10)]

In [ ]:
[i for i in range(10) if i % 2 == 0]


Let's implement the entropy function

$$H(X) = - \sum_i P(x_i) \log P(x_i)$$
In [ ]:
from math import log

X = [.5, .5]

def entropy(X):
return -sum([x * log(x) for x in X])

entropy(X)


Compute Pi using the Wallis product:

$$\pi \approx 2 \prod_{i=1}^{\infty} \frac{4i^2}{4i^2 -1}$$
In [ ]:
import operator

def prod(iterable):
return reduce(operator.mul, iterable, 1)

def pi(n):
# a**b = a to power b
return 2 * prod([(4 * i**2)/(4 * i**2 - 1) for i in range(1, n)])

print pi(2), pi(10), pi(100)


## Numpy & Matplotlib¶

In [ ]:
import numpy as np

In [ ]:
np.zeros((3, 3))

In [ ]:
A = np.ones((3, 3))
B = np.random.random((3, 3))
A + B

In [ ]:
A * B

In [ ]:
A.dot(B)  # matrix multiplication
np.dot(A, B)

In [ ]:
X = np.matrix( ((1,2), (5, -1)) )
Y = np.matrix( ((1,2), (5, -1)) )

X * Y


$\rightarrow$ use arrays

In [ ]:
# Wont be used in the exercises
import matplotlib.pyplot as plt
%matplotlib inline

plt.matshow(B);


## Exercises: project euler¶

These exercises are meant as feedback for you. You should be able to use python to solve the exercises. You could also try and solve some old "Datenstrukturen und Algorithmen" exercises.

In [ ]:
"""
Project Euler Problem #1
=========================

If we list all the natural numbers below 10 that are multiples of 3 or 5,
we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.
"""

In [ ]:
"""
Project Euler Problem #2
=========================

Each new term in the Fibonacci sequence is generated by adding the
previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

Find the sum of all the even-valued terms in the sequence which do not
exceed four million.
"""

In [ ]:
"""
Project Euler Problem #4
=========================

A palindromic number reads the same both ways. The largest palindrome made
from the product of two 2-digit numbers is 9009 = 91 * 99.

Find the largest palindrome made from the product of two 3-digit numbers.
"""


## Python: Functions and Classes¶

In [ ]:
def square(x):
"""Documentation of square."""
return x * x

square(5)

In [ ]:
class Node(object):
"""Doc of the class.

Sometimes the constructor is documented here.

"""
def __init__(self, value=None, left=None, right=None):
self.value = value
self.left = left
self.right = right

def cut(self):
"""Doc of the function cut."""
self.left = None
self.right = None

tree = Node("lecture", Node("python"), Node("git", Node("ki")))
print tree
print tree.value
print tree.right.left.value

In [ ]:
type(None)

In [ ]:
class Node(object):
def __init__(self, value=None, left=None, right=None):
self.value = value
self.left = left
self.right = right

def cut(self):
self.left = None
self.right = None

def children(self):
return self.left, self.right

def __str__(self):
return 'useless str method'

tree = Node("lecture", Node("python"), Node("git"))
print tree


## Doctest and Unittests¶

In [ ]:
# %load fib.py
def fibbonacci(n):
"""
The n-th Fibbonacci number is the sum of the previous two fibbonacci
numbers where the first and second Fibbonacci number are 1.

:math: F_n = F_{n-1} + F_{n-2}

Examples:
---------
>>> fibbonacci(1)
1
>>> fibbonacci(2)
1
>>> fibbonacci(3)
2
>>> fibbonacci(4)
3

"""
if n == 1:
return 1
elif n == 2:
return 1
else:
return fibbonacci(n-1) + fibbonacci(n-2)

In [ ]:
# executing the doctests
!python -m doctest -v fib.py

In [ ]:
# %load test_fib.py
import unittest
from fib import fibbonacci

class TestFibbonacci(unittest.TestCase):
def test_definition(self):
self.assertEqual(fibbonacci(1), 1)
self.assertEqual(fibbonacci(2), 1)

def test_calculated_values(self):
self.assertEqual(fibbonacci(5), 5)
self.assertEqual(fibbonacci(6), 8)

if __name__ == '__main__':
unittest.main()

unitte

In [ ]:
!python test_fib.py

In [ ]:
!python -m unittest discover -v


# Gitlab¶

## Setup Gitlab¶

• Check your mail and confirm your account

## Setup SSH¶

• Create a SSH key(if you don’t already have one)
$ssh-keygen -t rsa -C "<meaningful comment>" • On the gitlab website open "Profile Settings">"SSH Keys">"Add SSH Key". • Copy the entire content of the public key (Linux: ~/.ssh/id_rsa.pub, Windows:$\left<userpath\right>$\.ssh\id_rsa.pub) $ cat ~/.ssh/id_rsa.pub % print to console
• Paste the key into the key text area (gitlab), and choose a title

## Test it¶

• You can test whether it everything is setup correctly using
$ssh [email protected] • You are done ! (It may take a several minutes before a new key is recognized) # Git¶ git pull is the same as a git fetch followed by a git merge. ## Setup git¶ $ git config --global user.name "John Doe"

$git config --global user.email [email protected]$ git config --global color.ui true

## Get Started¶

• Clone a repository
$git clone [email protected]:ai_lecture/group_<GroupNumber>.git ## Workflow¶ • Fetch commits from the remote repo and merge any changes. $ git pull
• Add all new files to the the staging area

$git add . • Commit all changes to the local repository $ git commit -m "Your commit message"
• Push commits to the remote repository.
$git push ## Other Important Commands¶ • Returns the status of the working directory vs the repository (e.g. changes present?, new files?, removed files?) $ git status
• Removes a file from the staging area and working directory.

\$ git rm [-r] <somefile>

## Exercises¶

Github git tutorial