XKCD about python:
www.python.org about python:
Python is a programming language that lets you work more quickly and integrate your systems more effectively."
Wikipedia about python:
Python is a widely used general-purpose, high-level programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than would be possible in languages such as C. The language provides constructs intended to enable clear programs on both a small and large scale.
Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive standard library."
Notes:
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 = 7
# for (int i = 2; i < n; i++) {
# System.out.println(i);
# }
n = 7
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 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)
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
# executing the doctests
!python -m doctest -v fib.py
%load test_fib.py
!python test_fib.py
!python -m unittest discover -v
import numpy as np
np.zeros((3, 3))
A = np.ones((3, 3))
B = np.random.random((3, 3))
A + B
A * B # element wise multiplication
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
%matplotlib inline
import matplotlib.pyplot as plt
plt.matshow(A);
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.
Again, if you have problems, ASK ME NOW, (or see me after one of the tutorials).
a, b = b, a+b
)The exercises are taken from project euler.
"""
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.
"""