Browse Source

Adjust Python code to follow PEP8

Martin Thoma 9 years ago
parent
commit
de1ad26035

+ 7 - 6
documents/Numerik/Klausur6/aufgabe2.py

@@ -1,13 +1,14 @@
-from math import exp, log
+from math import exp
+
 
 def iterate(x, times=1):
-    #x = x - (2.0*x - exp(-x))/(2.0+exp(-x)) #Newton
-    x = 0.5*exp(-x) #F_1
-    #x = (-1)*log(2.0*x) #F_2
+    # x = x - (2.0*x - exp(-x))/(2.0+exp(-x)) #Newton
+    x = 0.5*exp(-x)  # F_1
+    # x = (-1)*log(2.0*x) #F_2
 
     if times > 0:
         x = iterate(x, times-1)
-    
+
     return x
 
-print(iterate(0.5,6))
+print(iterate(0.5, 6))

+ 8 - 4
documents/Programmierparadigmen/scripts/python/n-damen.py

@@ -1,12 +1,13 @@
 #!/usr/bin/env python
 # -*- coding: utf-8 -*-
 
+
 def get_next(n, i, damen_pos):
     for i in range(n):
-        candidates  = set(list(range(n)))
+        candidates = set(list(range(n)))
         candidates -= set(damen_pos)
         candidates -= set(list(range(damen_pos[i]+1)))
-        candidates  = list(candidates)
+        candidates = list(candidates)
         if len(candidates) > 0:
             damen_pos[i] = candidates[0]
             return i, damen_pos
@@ -14,6 +15,7 @@ def get_next(n, i, damen_pos):
             damen_pos = damen_pos[0:i] + [0]*(n-i)
             i -= 1
 
+
 def is_attacked(damen, x, y):
     """ Wird das Feld (x,y) von einer der Damen angegriffen? """
     for dy, dx in enumerate(damen[:y]):
@@ -21,9 +23,10 @@ def is_attacked(damen, x, y):
             return True
     return False
 
+
 def finde_loesung(n):
     """ Platziere n Damen so auf einem n×n Feld,
-        sodass sich keine Damen schlagen. 
+        sodass sich keine Damen schlagen.
     """
     # damen[i] ist die x-position von Dame i in Zeile i
     damen = [0]*n
@@ -37,8 +40,9 @@ def finde_loesung(n):
             i += 1
         i, damen = get_next(n, i, damen)
 
+
 def alle_loesungen(n):
     generator = finde_loesung(n)
     return list(generator)
 
-print(len(alle_loesungen(11)))
+print(len(alle_loesungen(11)))

+ 19 - 14
documents/math-minimal-distance-to-cubic-function/calcMinDist.py

@@ -2,31 +2,36 @@
 
 import numpy
 
+
 class Point:
+    """Represents a point in 2D."""
     def __init__(self, x, y):
         self.x = x
         self.y = y
 
-def euclideanDist(p1, p2):
+
+def euclidean_dist(p1, p2):
+    """Euclidean distance of two 2D points."""
     from math import sqrt
     return sqrt((p1.x-p2.x)**2 + (p1.y-p2.y)**2)
 
-def getMinDist(p1, precision=0.001, startX=0, endX=3):
+
+def get_min_dist(p1, precision=0.001, start_x=0, end_x=3):
     """Get x of point on (x,x^2) that has minimal distance to given Point p."""
-    minDist = -1
-    for x in numpy.arange(startX, endX, precision):
+    min_dist = -1
+    for x in numpy.arange(start_x, end_x, precision):
         p2 = Point(x, x**2)
-        dist = euclideanDist(p1, p2)
-        if minDist == -1 or dist < minDist:
-            minDist = dist
-    return minDist
+        dist = euclidean_dist(p1, p2)
+        if min_dist == -1 or dist < min_dist:
+            min_dist = dist
+    return min_dist
 
 """for i in numpy.arange(0, 3, 0.01):
-    minDist = getMinDist(Point(0, i))
-    if abs(i-minDist) < 0.005:
-        print(i, minDist)"""
+    min_dist = get_min_dist(Point(0, i))
+    if abs(i-min_dist) < 0.005:
+        print(i, min_dist)"""
 
-print(getMinDist(Point(0,4.25), precision=0.001, startX=0, endX=3))
-#print(euclideanDist(Point(0,5),Point(2, 2**2)))
+print(get_min_dist(Point(0, 4.25), precision=0.001, start_x=0, end_x=3))
+# print(euclidean_dist(Point(0,5),Point(2, 2**2)))
 
-#print(getMinDist(5, 0.00001, 2, 3))
+# print(get_min_dist(5, 0.00001, 2, 3))

+ 40 - 34
presentations/ICPC-Referat/Material/kosaraju.py

@@ -1,28 +1,29 @@
 #!/usr/bin/python
 # -*- coding: utf-8 -*-
 
-""" 
-    @source: http://codehiker.wordpress.com/2012/04/06/kosarajus-scc/
-    I made minor changs
+"""
+@source: http://codehiker.wordpress.com/2012/04/06/kosarajus-scc/
+I made minor changs
 """
 
 import sys
 sys.setrecursionlimit(300000)
 
-source  = 'SCC.txt'
-N       = 875714
+source = 'SCC.txt'
+N = 875714
 
-#globals
+# globals
 visited = {}
-finish  = {}
-leader  = {}
+finish = {}
+leader = {}
+
 
-def getG(source):
+def get_g(source):
     """ Read the Graph from a textfile """
-    G    = {}
+    G = {}
     Grev = {}
-    for i in range(1,N+1):
-        G[i]    = []
+    for i in range(1, N+1):
+        G[i] = []
         Grev[i] = []
     fin = open(source)
     for line in fin:
@@ -33,56 +34,61 @@ def getG(source):
     fin.close()
     return G, Grev
 
+
 def init():
-    for i in range(1,N+1):
-        visited[i]  = 0
-        finish[i]   = 0
-        leader[i]   = 0
+    for i in range(1, N+1):
+        visited[i] = 0
+        finish[i] = 0
+        leader[i] = 0
+
 
 def dfs(G, i):
     global t
-    visited[i]  = 1
-    leader[i]   = s
+    visited[i] = 1
+    leader[i] = s
     for j in G[i]:
-        if(visited[j]==0): dfs(G,j)
+        if(visited[j] == 0):
+            dfs(G, j)
     t = t + 1
     finish[i] = t
 
+
 def dfs_loop(G):
     global t
     global s
-    t = 0 #number of nodes processed so far
-    s = 0 #current source vertex
+    t = 0  # number of nodes processed so far
+    s = 0  # current source vertex
     i = N
-    while(i>0):
-        if(visited[i]==0):
-            s=i
-            dfs(G,i)
-        i=i-1
+    while(i > 0):
+        if(visited[i] == 0):
+            s = i
+            dfs(G, i)
+        i = i-1
 
 if __name__ == "__main__":
     init()
-    g, grev=getG()
-    dfs_loop(grev) #THE FIRST LOOP ON REVERSE GRAPH
+    g, grev = get_g()
+    dfs_loop(grev)  # THE FIRST LOOP ON REVERSE GRAPH
 
     # construct new graph
     newGraph = {}
     for i in range(1, N+1):
         temp = []
-        for x in g[i]: temp.append(finish[x])
+        for x in g[i]:
+            temp.append(finish[x])
         newGraph[finish[i]] = temp
 
     init()
-    dfs_loop(newGraph) #THE SECOND LOOP 
+    dfs_loop(newGraph)  # THE SECOND LOOP
 
     # statistics
-    lst  = sorted(leader.values())
+    lst = sorted(leader.values())
     stat = []
-    pre  = 0
-    for i in range(0,N-1):
+    pre = 0
+    for i in range(0, N-1):
         if lst[i] != lst[i+1]:
             stat.append(i + 1 - pre)
-            pre=i+1
+            pre = i+1
     stat.append(N-pre)
     L = sorted(stat)
     L.reverse()

+ 88 - 83
presentations/ICPC-Referat/Material/tarjans-algorithm.py

@@ -1,93 +1,98 @@
 def strongly_connected_components(graph):
-	"""
-	Tarjan's Algorithm (named for its discoverer, Robert Tarjan) is a 
-	graph theory algorithm for finding the strongly connected 
-	components of a graph.
-	
-	Based on: http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
-	@author: Dries Verdegem, some minor edits by Martin Thoma
-	@source: http://www.logarithmic.net/pfh/blog/01208083168
-	"""
+    """
+    Tarjan's Algorithm (named for its discoverer, Robert Tarjan) is a
+    graph theory algorithm for finding the strongly connected
+    components of a graph.
 
-	index_counter = 0
-	stack = []
-	lowlinks = {}
-	index = {}
-	result = []
-	
-	def strongconnect(node, index_counter):
-		print("Start with node: %s###########################" % node)
-		# set the depth index for this node to the smallest unused index
-		print("lowlinks:\t%s" % lowlinks)
-		print("index:\t%s" % index)
-		print("stack:\t%s" % stack)
+    Based on: http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
+    @author: Dries Verdegem, some minor edits by Martin Thoma
+    @source: http://www.logarithmic.net/pfh/blog/01208083168
+    """
 
-		index[node] = index_counter
-		lowlinks[node] = index_counter
-		index_counter += 1
-		stack.append(node)
-	
-		# Consider successors of `node`
-		try:
-			successors = graph[node]
-		except:
-			successors = []
+    index_counter = 0
+    stack = []
+    lowlinks = {}
+    index = {}
+    result = []
 
-		# Depth first search
-		for successor in successors:
-			# Does the current node point to a node that was already
-			# visited?
-			if successor not in lowlinks:
-				print("successor not in lowlinks: %s -> %s (node, successor)" % (node, successor))
-				# Successor has not yet been visited; recurse on it
-				strongconnect(successor, index_counter)
-				lowlinks[node] = min(lowlinks[node],lowlinks[successor])
-			elif successor in stack:
-			#else:
-				print("successor in stack: %s -> %s" % (node, successor));
-				# the successor is in the stack and hence in the 
-				# current strongly connected component (SCC)
-				lowlinks[node] = min(lowlinks[node],index[successor])
-			else:
-				print("This happens sometimes. node: %s, successor: %s" % (node, successor))
-				print("Lowlinks: %s" %lowlinks)
-				print("stack: %s" % stack)
-		
-		# If `node` is a root node, pop the stack and generate an SCC
-		if lowlinks[node] == index[node]:
-			print("Got root node: %s (index/lowlink: %i)" % (node, lowlinks[node]))
-			connected_component = []
-			
-			while True:
-				successor = stack.pop()
-				print("pop: %s" % successor)
-				connected_component.append(successor)
-				if successor == node: break
+    def strongconnect(node, index_counter):
+        print("Start with node: %s###########################" % node)
+        # set the depth index for this node to the smallest unused index
+        print("lowlinks:\t%s" % lowlinks)
+        print("index:\t%s" % index)
+        print("stack:\t%s" % stack)
 
-			component = tuple(connected_component)
+        index[node] = index_counter
+        lowlinks[node] = index_counter
+        index_counter += 1
+        stack.append(node)
 
-			# storing the result
-			result.append(component)
-		else:
-			print("Node: %s, lowlink: %i, index: %i" % (node, lowlinks[node], index[node]))
-	
-	for node in graph:
-		if node not in lowlinks:
-			strongconnect(node, index_counter)
-	
-	return result
+        # Consider successors of `node`
+        try:
+            successors = graph[node]
+        except:
+            successors = []
+
+        # Depth first search
+        for successor in successors:
+            # Does the current node point to a node that was already
+            # visited?
+            if successor not in lowlinks:
+                print("successor not in lowlinks: %s -> %s (node, successor)" %
+                      (node, successor))
+                # Successor has not yet been visited; recurse on it
+                strongconnect(successor, index_counter)
+                lowlinks[node] = min(lowlinks[node], lowlinks[successor])
+            elif successor in stack:
+                # else:
+                print("successor in stack: %s -> %s" % (node, successor))
+                # the successor is in the stack and hence in the
+                # current strongly connected component (SCC)
+                lowlinks[node] = min(lowlinks[node], index[successor])
+            else:
+                print("This happens sometimes. node: %s, successor: %s" %
+                      (node, successor))
+                print("Lowlinks: %s" % lowlinks)
+                print("stack: %s" % stack)
+
+        # If `node` is a root node, pop the stack and generate an SCC
+        if lowlinks[node] == index[node]:
+            print("Got root node: %s (index/lowlink: %i)" %
+                  (node, lowlinks[node]))
+            connected_component = []
+
+            while True:
+                successor = stack.pop()
+                print("pop: %s" % successor)
+                connected_component.append(successor)
+                if successor == node:
+                    break
+
+            component = tuple(connected_component)
+
+            # storing the result
+            result.append(component)
+        else:
+            print("Node: %s, lowlink: %i, index: %i" %
+                  (node, lowlinks[node], index[node]))
+
+    for node in graph:
+        if node not in lowlinks:
+            strongconnect(node, index_counter)
+
+    return result
 
 graph = {'a': ['b'],
-		'b': ['c'],
-		'c': ['d', 'e'],
-		'd': ['a', 'e', 'h'],
-		'e': ['c', 'f'],
-		'f': ['g', 'i'],
-		'g': ['h', 'f'],
-		'h': ['j'],
-		'i': ['g', 'f'],
-		'j': ['i'],
-		'k': [],
-		'h': []}
+         'b': ['c'],
+         'c': ['d', 'e'],
+         'd': ['a', 'e', 'h'],
+         'e': ['c', 'f'],
+         'f': ['g', 'i'],
+         'g': ['h', 'f'],
+         'h': ['j'],
+         'i': ['g', 'f'],
+         'j': ['i'],
+         'k': [],
+         'h': []}
 
 print strongly_connected_components(graph)

+ 50 - 49
presentations/ICPC-Referat/Material/tarjans-short.py

@@ -1,50 +1,51 @@
 def strongly_connected_components(graph):
-	index_counter = 0
-	stack = []
-	lowlinks = {}
-	index = {}
-	result = []
-	
-	def strongconnect(node, index_counter):
-		index[node] = index_counter
-		lowlinks[node] = index_counter
-		index_counter += 1
-		stack.append(node)
-	
-		try:
-			successors = graph[node]
-		except:
-			successors = []
-
-		# Depth first search
-		for successor in successors:
-			# Does the current node point to a node that was already
-			# visited?
-			if successor not in lowlinks:
-				# Successor has not yet been visited; recurse on it
-				strongconnect(successor, index_counter)
-				lowlinks[node] = min(lowlinks[node],lowlinks[successor])
-			elif successor in stack:
-				# the successor is in the stack and hence in the 
-				# current strongly connected component (SCC)
-				lowlinks[node] = min(lowlinks[node],index[successor])
-		
-		# If `node` is a root node, pop the stack and generate an SCC
-		if lowlinks[node] == index[node]:
-			connected_component = []
-			
-			while True:
-				successor = stack.pop()
-				connected_component.append(successor)
-				if successor == node: break
-
-			component = tuple(connected_component)
-
-			# storing the result
-			result.append(component)
-	
-	for node in graph:
-		if node not in lowlinks:
-			strongconnect(node, index_counter)
-	
-	return result
+    index_counter = 0
+    stack = []
+    lowlinks = {}
+    index = {}
+    result = []
+
+    def strongconnect(node, index_counter):
+        index[node] = index_counter
+        lowlinks[node] = index_counter
+        index_counter += 1
+        stack.append(node)
+
+        try:
+            successors = graph[node]
+        except:
+            successors = []
+
+        # Depth first search
+        for successor in successors:
+            # Does the current node point to a node that was already
+            # visited?
+            if successor not in lowlinks:
+                # Successor has not yet been visited; recurse on it
+                strongconnect(successor, index_counter)
+                lowlinks[node] = min(lowlinks[node], lowlinks[successor])
+            elif successor in stack:
+                # the successor is in the stack and hence in the
+                # current strongly connected component (SCC)
+                lowlinks[node] = min(lowlinks[node], index[successor])
+
+        # If `node` is a root node, pop the stack and generate an SCC
+        if lowlinks[node] == index[node]:
+            connected_component = []
+
+            while True:
+                successor = stack.pop()
+                connected_component.append(successor)
+                if successor == node:
+                    break
+
+            component = tuple(connected_component)
+
+            # storing the result
+            result.append(component)
+
+    for node in graph:
+        if node not in lowlinks:
+            strongconnect(node, index_counter)
+
+    return result

+ 6 - 6
presentations/Programmieren-Tutorium/Misc/tutoriumTermine.py

@@ -1,10 +1,10 @@
 #!/usr/bin/env python
 import datetime
 
-tmpDay  = datetime.date.today()     # von
-lastday = datetime.date(2014,2,10)  # bis (Vorlesungsende?)
+tmp_day = datetime.date.today()       # von
+lastday = datetime.date(2014, 2, 10)  # bis (Vorlesungsende?)
 
-while tmpDay < lastday:
-    if tmpDay.weekday() == 0:
-        print tmpDay.strftime('%d.%m.%Y')
-    tmpDay += datetime.timedelta(days=1)
+while tmp_day < lastday:
+    if tmp_day.weekday() == 0:
+        print tmp_day.strftime('%d.%m.%Y')
+    tmp_day += datetime.timedelta(days=1)

+ 21 - 17
presentations/Programmieren-Tutorium/Tutorium-04/euler28.py

@@ -1,40 +1,44 @@
 #!/usr/bin/python
 # -*- coding: utf-8 -*-
 
-def printArr(a):
+
+def print_arr(a):
     for line in a:
         print(line)
 
+
 def initialise(n):
-    array = [[0  for j in xrange(0,n)] for i in xrange(0,n)]
+    array = [[0 for j in xrange(0, n)] for i in xrange(0, n)]
     return array
 
-def spiralFill(a):
+
+def spiral_fill(a):
     n = len(a)
     x = y = n/2
     number = 1
-            # r      u       l      o
-    order = [(1,0), (0,1), (-1,0), (0,-1)]
-    iOrder = 0
+    #         r       u       l        o
+    order = [(1, 0), (0, 1), (-1, 0), (0, -1)]
+    i_order = 0
     length = 1
     a[y][x] = number
     while not (x == (n-1) and y == 0):
         for j in xrange(0, length):
-            xAdd, yAdd = order[iOrder]
+            xAdd, yAdd = order[i_order]
             x += xAdd
             y += yAdd
             number += 1
             a[y][x] = number
-            if x == (n-1) and y==0:
+            if x == (n-1) and y == 0:
                 break
-        if iOrder == 1 or iOrder == 3:
+        if i_order == 1 or i_order == 3:
             length += 1
-        iOrder = (iOrder+1) % 4
+        i_order = (i_order+1) % 4
     return a
 
-def diagonalSum(a):
+
+def diagonal_sum(a):
     n = len(a)
-    sum = -1 # you will have the element in the middle (1) twice
+    sum = -1  # you will have the element in the middle (1) twice
     for i in xrange(0, n):
         sum += a[i][i]
         sum += a[n-i-1][i]
@@ -42,15 +46,15 @@ def diagonalSum(a):
 
 if __name__ == "__main__":
     import argparse
- 
+
     parser = argparse.ArgumentParser(description="ProjectEuler: 28")
     parser.add_argument("-n", metavar='N', type=int,
                         help="length of the spiral", required=True)
-    parser.add_argument("-d", action="store_true",default=False,
+    parser.add_argument("-d", action="store_true", default=False,
                         help="display the spiral")
     args = parser.parse_args()
     array = initialise(args.n)
-    array = spiralFill(array)
+    array = spiral_fill(array)
     if args.d:
-        printArr(array)
-    print diagonalSum(array)
+        print_arr(array)
+    print diagonal_sum(array)

+ 2 - 0
source-code/Pseudocode/Horner-Schema/basiswechsel.py

@@ -1,12 +1,14 @@
 #!/usr/bin/env python
 # -*- coding: utf-8 -*-
 
+
 def string(zahl):
     if zahl <= 9:
         return str(zahl)
     else:
         return chr(55+zahl)
 
+
 def horner(b, Z):
     ergebnis = ''
     while Z > 0:

+ 48 - 44
source-code/Pseudocode/SolveLinearCongruences/solveLinearCongruences.py

@@ -1,49 +1,53 @@
 #!/usr/bin/env python
 # -*- coding: utf-8 -*-
 
-def ExtendedEuclideanAlgorithm(a, b):
-	"""
-		Calculates gcd(a,b) and a linear combination such that
-		gcd(a,b) = a*x + b*y
-
-		As a side effect:
-		If gcd(a,b) = 1 = a*x + b*y
-		Then x is multiplicative inverse of a modulo b.
-	"""
-	aO, bO = a, b
-
-	x=lasty=0
-	y=lastx=1
-	while (b!=0):
-		q= a/b
-		a, b = b, a%b
-		x, lastx = lastx-q*x, x
-		y, lasty = lasty-q*y, y
-
-	return {
-		"x": lastx,
-		"y": lasty,
-		"gcd": aO * lastx + bO * lasty
-	}
-
-def solveLinearCongruenceEquations(rests, modulos):
-	"""
-	Solve a system of linear congruences.
-
-	>>> solveLinearCongruenceEquations([4, 12, 14], [19, 37, 43])
-	{'congruence class': 22804, 'modulo': 30229}
-	"""
-	assert len(rests) == len(modulos)
-	x = 0
-	M = reduce(lambda x, y: x*y, modulos)
-
-	for mi, resti in zip(modulos, rests):
-		Mi = M / mi
-		s = ExtendedEuclideanAlgorithm(Mi, mi)["x"]
-		e = s * Mi
-		x += resti * e
-	return {"congruence class": ((x % M) + M) % M, "modulo": M}
+
+def extended_euclidean_algorithm(a, b):
+    """
+    Calculates gcd(a,b) and a linear combination such that
+    gcd(a,b) = a*x + b*y
+
+    As a side effect:
+    If gcd(a,b) = 1 = a*x + b*y
+    Then x is multiplicative inverse of a modulo b.
+    """
+    aO, bO = a, b
+
+    x = lasty = 0
+    y = lastx = 1
+    while (b != 0):
+        q = a/b
+        a, b = b, a % b
+        x, lastx = lastx-q*x, x
+        y, lasty = lasty-q*y, y
+
+    return {
+        "x": lastx,
+        "y": lasty,
+        "gcd": aO * lastx + bO * lasty
+    }
+
+
+def solve_linear_congruence_equations(rests, modulos):
+    """
+    Solve a system of linear congruences.
+
+    Examples
+    --------
+    >>> solve_linear_congruence_equations([4, 12, 14], [19, 37, 43])
+    {'congruence class': 22804, 'modulo': 30229}
+    """
+    assert len(rests) == len(modulos)
+    x = 0
+    M = reduce(lambda x, y: x*y, modulos)
+
+    for mi, resti in zip(modulos, rests):
+        Mi = M / mi
+        s = extended_euclidean_algorithm(Mi, mi)["x"]
+        e = s * Mi
+        x += resti * e
+    return {"congruence class": ((x % M) + M) % M, "modulo": M}
 
 if __name__ == "__main__":
-	import doctest
-	doctest.testmod()
+    import doctest
+    doctest.testmod()

+ 12 - 11
source-code/Pseudocode/WER-calculation/wer.py

@@ -1,17 +1,18 @@
 #!/usr/bin/env python
 
+
 def wer(r, h):
     """
-        Calculation of WER with Levenshtein distance.
-        Works only for iterables up to 254 elements (uint8).
-        O(nm) time ans space complexity.
+    Calculation of WER with Levenshtein distance.
+    Works only for iterables up to 254 elements (uint8).
+    O(nm) time ans space complexity.
 
-        >>> wer("who is there".split(), "is there".split()) 
-        1
-        >>> wer("who is there".split(), "".split()) 
-        3
-        >>> wer("".split(), "who is there".split()) 
-        3
+    >>> wer("who is there".split(), "is there".split())
+    1
+    >>> wer("who is there".split(), "".split())
+    3
+    >>> wer("".split(), "who is there".split())
+    3
     """
     # initialisation
     import numpy
@@ -31,8 +32,8 @@ def wer(r, h):
                 d[i][j] = d[i-1][j-1]
             else:
                 substitution = d[i-1][j-1] + 1
-                insertion    = d[i][j-1] + 1
-                deletion     = d[i-1][j] + 1
+                insertion = d[i][j-1] + 1
+                deletion = d[i-1][j] + 1
                 d[i][j] = min(substitution, insertion, deletion)
 
     return d[len(r)][len(h)]

+ 7 - 5
tikz/birthday-paradox/calculate.py

@@ -4,11 +4,13 @@
 from math import factorial
 from gmpy import bincoef
 
-f = open('data.csv', 'w')
-f.write('People\tprobability\n')
 
 def prob(people):
-    return 1.0 - float(factorial(people)*bincoef(365,people))/(365**people)
+    return 1.0 - float(factorial(people)*bincoef(365, people))/(365**people)
 
-for people in xrange(60+1):
-    f.write("%i\t%f\n" % (people, prob(people)))
+if __name__ == '__main__':
+    with open('data.csv', 'w') as f:
+        f.write('People\tprobability\n')
+
+        for people in xrange(60+1):
+            f.write("%i\t%f\n" % (people, prob(people)))

+ 45 - 42
tikz/center-two-cluster/tikz.py

@@ -8,7 +8,7 @@ print """\documentclass{article}
 \usepackage{tikz}
 \usepackage{tkz-fct}
 \usetikzlibrary{shapes.misc}
-\usetikzlibrary{shapes, calc, decorations} 
+\usetikzlibrary{shapes, calc, decorations}
 \usepackage{amsmath,amssymb}
 
 \\begin{document}
@@ -21,7 +21,8 @@ print """\documentclass{article}
     minimum height=4pt}]
 """
 
-def getPositionFromOffset(px, py, angle, radius):
+
+def get_position_from_offset(px, py, angle, radius):
     x = px + radius * math.cos(math.radians(angle))
     y = py + radius * math.sin(math.radians(angle))
     return (x, y)
@@ -29,18 +30,18 @@ def getPositionFromOffset(px, py, angle, radius):
 n = 5
 xSum = 0
 ySum = 0
-coordinates = [(0,0)]
+coordinates = [(0, 0)]
 
 random.seed(13)
 
 for i in range(n-1):
-	radius = uniform(0,20)
-	angle = uniform(0, 360)
-	px, py = coordinates[-1]
-	x, y = getPositionFromOffset(px, py, angle, radius)
-	xSum += x
-	ySum += y
-	coordinates.append((x,y))
+    radius = uniform(0, 20)
+    angle = uniform(0, 360)
+    px, py = coordinates[-1]
+    x, y = get_position_from_offset(px, py, angle, radius)
+    xSum += x
+    ySum += y
+    coordinates.append((x, y))
 
 center = (float(xSum) / n, float(ySum) / n)
 
@@ -49,17 +50,18 @@ coordinates.append((cx+15, cy))
 
 pointCoords = ""
 for p in coordinates:
-	px, py = p	
-	px -= cx
-	py -= cy
-	newP = "(%.2f,%.2f)," % (px, py)
-	pointCoords = newP + pointCoords
-	deltaY = 0-py
-	deltaX = 0-px
-	length = (deltaY**2+deltaX**2)**0.5
-	sinAlpha = deltaY/length
-	cosAlpha = deltaX/length
-	print("\draw[->] (%.2f,%.2f) -- (%.2f,%.2f);" % (px, py, px+cosAlpha*length*0.80, py+sinAlpha*length*0.80))
+    px, py = p
+    px -= cx
+    py -= cy
+    newP = "(%.2f,%.2f)," % (px, py)
+    pointCoords = newP + pointCoords
+    deltaY = 0-py
+    deltaX = 0-px
+    length = (deltaY**2+deltaX**2)**0.5
+    sinAlpha = deltaY/length
+    cosAlpha = deltaX/length
+    print("\draw[->] (%.2f,%.2f) -- (%.2f,%.2f);" %
+          (px, py, px+cosAlpha*length*0.80, py+sinAlpha*length*0.80))
 
 print("\\node[circle,inner sep=1pt,fill]  at (%.2f,%.2f) {};" % (0, 0))
 
@@ -67,44 +69,45 @@ print("\\foreach \point in {" + pointCoords[:-1] + "}{")
 print("\\node[dot] at \point {};")
 print("}")
 
-################################################################################
+###############################################################################
 random.seed(17)
 xSum = 0
 ySum = 0
-coordinates = [(0,0)]
+coordinates = [(0, 0)]
 for i in range(n-1):
-	radius = uniform(0,20)
-	angle = uniform(0, 360)
-	px, py = coordinates[-1]
-	x, y = getPositionFromOffset(px, py, angle, radius)
-	xSum += x
-	ySum += y
-	coordinates.append((x,y))
+    radius = uniform(0, 20)
+    angle = uniform(0, 360)
+    px, py = coordinates[-1]
+    x, y = get_position_from_offset(px, py, angle, radius)
+    xSum += x
+    ySum += y
+    coordinates.append((x, y))
 
 center = (float(xSum) / n, float(ySum) / n)
 
 cx, cy = center
-coordinates.append((cx-15,cy))
+coordinates.append((cx-15, cy))
 xOffset = 40
 cTmp = []
 for p in coordinates:
-	px, py = p
-	cTmp.append((px-cx+xOffset,py-cy))	
+    px, py = p
+    cTmp.append((px-cx+xOffset, py-cy))
 
 coordinates = cTmp
 cx, cy = xOffset, 0
 pointCoords = ""
 
 for p in coordinates:
-	px, py = p	
-	newP = "(%.2f,%.2f)," % (px, py)
-	pointCoords = newP + pointCoords
-	deltaY = -py
-	deltaX = xOffset-px
-	length = (deltaY**2+deltaX**2)**0.5
-	sinAlpha = deltaY/length
-	cosAlpha = deltaX/length
-	print("\draw[->] (%.2f,%.2f) -- (%.2f,%.2f);" % (px, py, px+cosAlpha*length*0.80, py+sinAlpha*length*0.80))
+    px, py = p
+    newP = "(%.2f,%.2f)," % (px, py)
+    pointCoords = newP + pointCoords
+    deltaY = -py
+    deltaX = xOffset-px
+    length = (deltaY**2+deltaX**2)**0.5
+    sinAlpha = deltaY/length
+    cosAlpha = deltaX/length
+    print("\draw[->] (%.2f,%.2f) -- (%.2f,%.2f);" %
+          (px, py, px+cosAlpha*length*0.80, py+sinAlpha*length*0.80))
 
 
 print("\\node[circle,inner sep=1pt,fill]  at (%.2f,%.2f) {};" % (xOffset, 0))

+ 5 - 5
tikz/graph-triangles/coordinates.py

@@ -1,7 +1,7 @@
-def giveCoordinates(n):
-    for y in range(0,n):
-        for x in range(y,2*n-y,2):
-            print(x,y)
+def give_coordinates(n):
+    for y in range(0, n):
+        for x in range(y, 2*n-y, 2):
+            print(x, y)
         print("")
 
-giveCoordinates(5)
+give_coordinates(5)