AI Class Homepage, This document (non-interactive version): https://goo.gl/wpedFn
You should be able to complete the AI exercises (from a programming language point of view).
There are small programming exercises to give you feedback! Try them!
Full featured scientific python distribution. Already contains the important packages.
Use your systems package manager to install python 2 and packages (numpy required).
Install packages with pip (numpy required). Always up to date
help(range)
type?
# if/elif/else
a = 6
if a > 5:
print "bigger than 5"
elif a == 5:
print "FIVE"
else:
print 'something else: ' + str(a)
a = 4
a = "bigger" if a > 3 else "smaller"
a
# 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
range(2,10,2)
movies = ["Her", "Moon", "Pacific Rim", "Robot and Frank"]
print len(movies)
for movie in movies:
print movie
for i, movie in enumerate(movies):
print i, movie
for i, movie in zip(range(len(movies)), movies):
print i, movie
print enumerate(movie)
print zip(range(len(movies)), movies)
# while
i = 0
while True:
while True:
print i
i += 1
if i > 5:
break
print "outer"
break
# numbers
print type(1)
print type(.1)
# Strings
'this is a string'
"this is also a string"
"""This is a string as well
A multi-line string
"""
# list
i = [1, 2, 3, 4]
print list(i)
print [2, 4]
['something', 5, 5.5]
movies = ["Her", "Moon", "Pacific Rim", "Robot and Frank"]
movies
movies.append("Wall-E")
movies
movies = movies + ["Nummer 5", "I, Robot", "2001"]
movies
import copy
copy.deepcopy(movies)
# slicing
print movies
print movies[0]
print movies[1]
print movies[0:2]
print movies[:2]
print movies[-1]
print movies[-2]
print movies[3::2]
# Dictionaries
print dict()
print {}
d = {"Her": 4,
"Moon": 5,
"Pacific Rim": 5,
"Robot and Frank": 4.,
}
d
d["Her"]
"Her" in movies
d.keys()
type(d.values())
for (key, value) in d.items():
print key, value
# tuples
3, 4
(3, 4)
type((3,4))
t = 3, 4, 3
print t[0]
print t[1]
print t[2]
# set
set([3, 0, -4, 15, 3, 2, 2, 1, 15])
[i for i in range(10)]
[i*i for i in range(10)]
[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) $$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} $$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)
import numpy as np
np.zeros((3, 3))
A = np.ones((3, 3))
B = np.random.random((3, 3))
A + B
A * B
A.dot(B) # matrix multiplication
np.dot(A, B)
X = np.matrix( ((1,2), (5, -1)) )
Y = np.matrix( ((1,2), (5, -1)) )
X * Y
$\rightarrow$ use arrays
# Wont be used in the exercises
import matplotlib.pyplot as plt
%matplotlib inline
plt.matshow(B);
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.
"""
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.
"""
"""
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.
"""
"""
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.
"""
def square(x):
"""Documentation of square."""
return x * x
square(5)
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
type(None)
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
# %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)
# executing the doctests
!python -m doctest -v fib.py
# %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
!python test_fib.py
!python -m unittest discover -v
Check your mail and confirm your account
Change your password on the login site (Forgot your password?)
Login to gitlab using your username and new password
$ 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
$ ssh git@animal.informatik.uni-stuttgart.de
git pull is the same as a git fetch followed by a git merge.
$ git config --global user.name "John Doe"
$ git config --global user.email johndoe@example.com
$ git config --global color.ui true
$ git clone git@animal.informatik.unistuttgart.de:ai_lecture/group_<GroupNumber>.git
$ git pull
$ git add .
$ git commit -m "Your commit message"
$ git push
$ git status
$ git rm [-r] <somefile>