mirror of
https://github.com/MartinThoma/LaTeX-examples.git
synced 2025-04-19 11:38:05 +02:00
Adjust Python code to follow PEP8
This commit is contained in:
parent
b36776fc27
commit
de1ad26035
14 changed files with 349 additions and 311 deletions
|
@ -1,13 +1,14 @@
|
||||||
from math import exp, log
|
from math import exp
|
||||||
|
|
||||||
|
|
||||||
def iterate(x, times=1):
|
def iterate(x, times=1):
|
||||||
#x = x - (2.0*x - exp(-x))/(2.0+exp(-x)) #Newton
|
# x = x - (2.0*x - exp(-x))/(2.0+exp(-x)) #Newton
|
||||||
x = 0.5*exp(-x) #F_1
|
x = 0.5*exp(-x) # F_1
|
||||||
#x = (-1)*log(2.0*x) #F_2
|
# x = (-1)*log(2.0*x) #F_2
|
||||||
|
|
||||||
if times > 0:
|
if times > 0:
|
||||||
x = iterate(x, times-1)
|
x = iterate(x, times-1)
|
||||||
|
|
||||||
return x
|
return x
|
||||||
|
|
||||||
print(iterate(0.5,6))
|
print(iterate(0.5, 6))
|
||||||
|
|
|
@ -1,12 +1,13 @@
|
||||||
#!/usr/bin/env python
|
#!/usr/bin/env python
|
||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
|
|
||||||
|
|
||||||
def get_next(n, i, damen_pos):
|
def get_next(n, i, damen_pos):
|
||||||
for i in range(n):
|
for i in range(n):
|
||||||
candidates = set(list(range(n)))
|
candidates = set(list(range(n)))
|
||||||
candidates -= set(damen_pos)
|
candidates -= set(damen_pos)
|
||||||
candidates -= set(list(range(damen_pos[i]+1)))
|
candidates -= set(list(range(damen_pos[i]+1)))
|
||||||
candidates = list(candidates)
|
candidates = list(candidates)
|
||||||
if len(candidates) > 0:
|
if len(candidates) > 0:
|
||||||
damen_pos[i] = candidates[0]
|
damen_pos[i] = candidates[0]
|
||||||
return i, damen_pos
|
return i, damen_pos
|
||||||
|
@ -14,6 +15,7 @@ def get_next(n, i, damen_pos):
|
||||||
damen_pos = damen_pos[0:i] + [0]*(n-i)
|
damen_pos = damen_pos[0:i] + [0]*(n-i)
|
||||||
i -= 1
|
i -= 1
|
||||||
|
|
||||||
|
|
||||||
def is_attacked(damen, x, y):
|
def is_attacked(damen, x, y):
|
||||||
""" Wird das Feld (x,y) von einer der Damen angegriffen? """
|
""" Wird das Feld (x,y) von einer der Damen angegriffen? """
|
||||||
for dy, dx in enumerate(damen[:y]):
|
for dy, dx in enumerate(damen[:y]):
|
||||||
|
@ -21,9 +23,10 @@ def is_attacked(damen, x, y):
|
||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def finde_loesung(n):
|
def finde_loesung(n):
|
||||||
""" Platziere n Damen so auf einem n×n Feld,
|
""" 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[i] ist die x-position von Dame i in Zeile i
|
||||||
damen = [0]*n
|
damen = [0]*n
|
||||||
|
@ -37,8 +40,9 @@ def finde_loesung(n):
|
||||||
i += 1
|
i += 1
|
||||||
i, damen = get_next(n, i, damen)
|
i, damen = get_next(n, i, damen)
|
||||||
|
|
||||||
|
|
||||||
def alle_loesungen(n):
|
def alle_loesungen(n):
|
||||||
generator = finde_loesung(n)
|
generator = finde_loesung(n)
|
||||||
return list(generator)
|
return list(generator)
|
||||||
|
|
||||||
print(len(alle_loesungen(11)))
|
print(len(alle_loesungen(11)))
|
||||||
|
|
|
@ -2,31 +2,36 @@
|
||||||
|
|
||||||
import numpy
|
import numpy
|
||||||
|
|
||||||
|
|
||||||
class Point:
|
class Point:
|
||||||
|
"""Represents a point in 2D."""
|
||||||
def __init__(self, x, y):
|
def __init__(self, x, y):
|
||||||
self.x = x
|
self.x = x
|
||||||
self.y = y
|
self.y = y
|
||||||
|
|
||||||
def euclideanDist(p1, p2):
|
|
||||||
|
def euclidean_dist(p1, p2):
|
||||||
|
"""Euclidean distance of two 2D points."""
|
||||||
from math import sqrt
|
from math import sqrt
|
||||||
return sqrt((p1.x-p2.x)**2 + (p1.y-p2.y)**2)
|
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."""
|
"""Get x of point on (x,x^2) that has minimal distance to given Point p."""
|
||||||
minDist = -1
|
min_dist = -1
|
||||||
for x in numpy.arange(startX, endX, precision):
|
for x in numpy.arange(start_x, end_x, precision):
|
||||||
p2 = Point(x, x**2)
|
p2 = Point(x, x**2)
|
||||||
dist = euclideanDist(p1, p2)
|
dist = euclidean_dist(p1, p2)
|
||||||
if minDist == -1 or dist < minDist:
|
if min_dist == -1 or dist < min_dist:
|
||||||
minDist = dist
|
min_dist = dist
|
||||||
return minDist
|
return min_dist
|
||||||
|
|
||||||
"""for i in numpy.arange(0, 3, 0.01):
|
"""for i in numpy.arange(0, 3, 0.01):
|
||||||
minDist = getMinDist(Point(0, i))
|
min_dist = get_min_dist(Point(0, i))
|
||||||
if abs(i-minDist) < 0.005:
|
if abs(i-min_dist) < 0.005:
|
||||||
print(i, minDist)"""
|
print(i, min_dist)"""
|
||||||
|
|
||||||
print(getMinDist(Point(0,4.25), precision=0.001, startX=0, endX=3))
|
print(get_min_dist(Point(0, 4.25), precision=0.001, start_x=0, end_x=3))
|
||||||
#print(euclideanDist(Point(0,5),Point(2, 2**2)))
|
# 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))
|
||||||
|
|
|
@ -1,28 +1,29 @@
|
||||||
#!/usr/bin/python
|
#!/usr/bin/python
|
||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
|
|
||||||
"""
|
"""
|
||||||
@source: http://codehiker.wordpress.com/2012/04/06/kosarajus-scc/
|
@source: http://codehiker.wordpress.com/2012/04/06/kosarajus-scc/
|
||||||
I made minor changs
|
I made minor changs
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import sys
|
import sys
|
||||||
sys.setrecursionlimit(300000)
|
sys.setrecursionlimit(300000)
|
||||||
|
|
||||||
source = 'SCC.txt'
|
source = 'SCC.txt'
|
||||||
N = 875714
|
N = 875714
|
||||||
|
|
||||||
#globals
|
# globals
|
||||||
visited = {}
|
visited = {}
|
||||||
finish = {}
|
finish = {}
|
||||||
leader = {}
|
leader = {}
|
||||||
|
|
||||||
def getG(source):
|
|
||||||
|
def get_g(source):
|
||||||
""" Read the Graph from a textfile """
|
""" Read the Graph from a textfile """
|
||||||
G = {}
|
G = {}
|
||||||
Grev = {}
|
Grev = {}
|
||||||
for i in range(1,N+1):
|
for i in range(1, N+1):
|
||||||
G[i] = []
|
G[i] = []
|
||||||
Grev[i] = []
|
Grev[i] = []
|
||||||
fin = open(source)
|
fin = open(source)
|
||||||
for line in fin:
|
for line in fin:
|
||||||
|
@ -33,56 +34,61 @@ def getG(source):
|
||||||
fin.close()
|
fin.close()
|
||||||
return G, Grev
|
return G, Grev
|
||||||
|
|
||||||
|
|
||||||
def init():
|
def init():
|
||||||
for i in range(1,N+1):
|
for i in range(1, N+1):
|
||||||
visited[i] = 0
|
visited[i] = 0
|
||||||
finish[i] = 0
|
finish[i] = 0
|
||||||
leader[i] = 0
|
leader[i] = 0
|
||||||
|
|
||||||
|
|
||||||
def dfs(G, i):
|
def dfs(G, i):
|
||||||
global t
|
global t
|
||||||
visited[i] = 1
|
visited[i] = 1
|
||||||
leader[i] = s
|
leader[i] = s
|
||||||
for j in G[i]:
|
for j in G[i]:
|
||||||
if(visited[j]==0): dfs(G,j)
|
if(visited[j] == 0):
|
||||||
|
dfs(G, j)
|
||||||
t = t + 1
|
t = t + 1
|
||||||
finish[i] = t
|
finish[i] = t
|
||||||
|
|
||||||
|
|
||||||
def dfs_loop(G):
|
def dfs_loop(G):
|
||||||
global t
|
global t
|
||||||
global s
|
global s
|
||||||
t = 0 #number of nodes processed so far
|
t = 0 # number of nodes processed so far
|
||||||
s = 0 #current source vertex
|
s = 0 # current source vertex
|
||||||
i = N
|
i = N
|
||||||
while(i>0):
|
while(i > 0):
|
||||||
if(visited[i]==0):
|
if(visited[i] == 0):
|
||||||
s=i
|
s = i
|
||||||
dfs(G,i)
|
dfs(G, i)
|
||||||
i=i-1
|
i = i-1
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
init()
|
init()
|
||||||
g, grev=getG()
|
g, grev = get_g()
|
||||||
dfs_loop(grev) #THE FIRST LOOP ON REVERSE GRAPH
|
dfs_loop(grev) # THE FIRST LOOP ON REVERSE GRAPH
|
||||||
|
|
||||||
# construct new graph
|
# construct new graph
|
||||||
newGraph = {}
|
newGraph = {}
|
||||||
for i in range(1, N+1):
|
for i in range(1, N+1):
|
||||||
temp = []
|
temp = []
|
||||||
for x in g[i]: temp.append(finish[x])
|
for x in g[i]:
|
||||||
|
temp.append(finish[x])
|
||||||
newGraph[finish[i]] = temp
|
newGraph[finish[i]] = temp
|
||||||
|
|
||||||
init()
|
init()
|
||||||
dfs_loop(newGraph) #THE SECOND LOOP
|
dfs_loop(newGraph) # THE SECOND LOOP
|
||||||
|
|
||||||
# statistics
|
# statistics
|
||||||
lst = sorted(leader.values())
|
lst = sorted(leader.values())
|
||||||
stat = []
|
stat = []
|
||||||
pre = 0
|
pre = 0
|
||||||
for i in range(0,N-1):
|
for i in range(0, N-1):
|
||||||
if lst[i] != lst[i+1]:
|
if lst[i] != lst[i+1]:
|
||||||
stat.append(i + 1 - pre)
|
stat.append(i + 1 - pre)
|
||||||
pre=i+1
|
pre = i+1
|
||||||
stat.append(N-pre)
|
stat.append(N-pre)
|
||||||
L = sorted(stat)
|
L = sorted(stat)
|
||||||
L.reverse()
|
L.reverse()
|
||||||
|
|
|
@ -1,93 +1,98 @@
|
||||||
def strongly_connected_components(graph):
|
def strongly_connected_components(graph):
|
||||||
"""
|
"""
|
||||||
Tarjan's Algorithm (named for its discoverer, Robert Tarjan) is a
|
Tarjan's Algorithm (named for its discoverer, Robert Tarjan) is a
|
||||||
graph theory algorithm for finding the strongly connected
|
graph theory algorithm for finding the strongly connected
|
||||||
components of a graph.
|
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
|
|
||||||
"""
|
|
||||||
|
|
||||||
index_counter = 0
|
Based on: http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
|
||||||
stack = []
|
@author: Dries Verdegem, some minor edits by Martin Thoma
|
||||||
lowlinks = {}
|
@source: http://www.logarithmic.net/pfh/blog/01208083168
|
||||||
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)
|
|
||||||
|
|
||||||
index[node] = index_counter
|
index_counter = 0
|
||||||
lowlinks[node] = index_counter
|
stack = []
|
||||||
index_counter += 1
|
lowlinks = {}
|
||||||
stack.append(node)
|
index = {}
|
||||||
|
result = []
|
||||||
# Consider successors of `node`
|
|
||||||
try:
|
|
||||||
successors = graph[node]
|
|
||||||
except:
|
|
||||||
successors = []
|
|
||||||
|
|
||||||
# Depth first search
|
def strongconnect(node, index_counter):
|
||||||
for successor in successors:
|
print("Start with node: %s###########################" % node)
|
||||||
# Does the current node point to a node that was already
|
# set the depth index for this node to the smallest unused index
|
||||||
# visited?
|
print("lowlinks:\t%s" % lowlinks)
|
||||||
if successor not in lowlinks:
|
print("index:\t%s" % index)
|
||||||
print("successor not in lowlinks: %s -> %s (node, successor)" % (node, successor))
|
print("stack:\t%s" % stack)
|
||||||
# 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)
|
index[node] = index_counter
|
||||||
|
lowlinks[node] = index_counter
|
||||||
|
index_counter += 1
|
||||||
|
stack.append(node)
|
||||||
|
|
||||||
# storing the result
|
# Consider successors of `node`
|
||||||
result.append(component)
|
try:
|
||||||
else:
|
successors = graph[node]
|
||||||
print("Node: %s, lowlink: %i, index: %i" % (node, lowlinks[node], index[node]))
|
except:
|
||||||
|
successors = []
|
||||||
for node in graph:
|
|
||||||
if node not in lowlinks:
|
# Depth first search
|
||||||
strongconnect(node, index_counter)
|
for successor in successors:
|
||||||
|
# Does the current node point to a node that was already
|
||||||
return result
|
# 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'],
|
graph = {'a': ['b'],
|
||||||
'b': ['c'],
|
'b': ['c'],
|
||||||
'c': ['d', 'e'],
|
'c': ['d', 'e'],
|
||||||
'd': ['a', 'e', 'h'],
|
'd': ['a', 'e', 'h'],
|
||||||
'e': ['c', 'f'],
|
'e': ['c', 'f'],
|
||||||
'f': ['g', 'i'],
|
'f': ['g', 'i'],
|
||||||
'g': ['h', 'f'],
|
'g': ['h', 'f'],
|
||||||
'h': ['j'],
|
'h': ['j'],
|
||||||
'i': ['g', 'f'],
|
'i': ['g', 'f'],
|
||||||
'j': ['i'],
|
'j': ['i'],
|
||||||
'k': [],
|
'k': [],
|
||||||
'h': []}
|
'h': []}
|
||||||
|
|
||||||
print strongly_connected_components(graph)
|
print strongly_connected_components(graph)
|
||||||
|
|
|
@ -1,50 +1,51 @@
|
||||||
def strongly_connected_components(graph):
|
def strongly_connected_components(graph):
|
||||||
index_counter = 0
|
index_counter = 0
|
||||||
stack = []
|
stack = []
|
||||||
lowlinks = {}
|
lowlinks = {}
|
||||||
index = {}
|
index = {}
|
||||||
result = []
|
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
|
def strongconnect(node, index_counter):
|
||||||
for successor in successors:
|
index[node] = index_counter
|
||||||
# Does the current node point to a node that was already
|
lowlinks[node] = index_counter
|
||||||
# visited?
|
index_counter += 1
|
||||||
if successor not in lowlinks:
|
stack.append(node)
|
||||||
# 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)
|
try:
|
||||||
|
successors = graph[node]
|
||||||
|
except:
|
||||||
|
successors = []
|
||||||
|
|
||||||
# storing the result
|
# Depth first search
|
||||||
result.append(component)
|
for successor in successors:
|
||||||
|
# Does the current node point to a node that was already
|
||||||
for node in graph:
|
# visited?
|
||||||
if node not in lowlinks:
|
if successor not in lowlinks:
|
||||||
strongconnect(node, index_counter)
|
# Successor has not yet been visited; recurse on it
|
||||||
|
strongconnect(successor, index_counter)
|
||||||
return result
|
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
|
||||||
|
|
|
@ -1,10 +1,10 @@
|
||||||
#!/usr/bin/env python
|
#!/usr/bin/env python
|
||||||
import datetime
|
import datetime
|
||||||
|
|
||||||
tmpDay = datetime.date.today() # von
|
tmp_day = datetime.date.today() # von
|
||||||
lastday = datetime.date(2014,2,10) # bis (Vorlesungsende?)
|
lastday = datetime.date(2014, 2, 10) # bis (Vorlesungsende?)
|
||||||
|
|
||||||
while tmpDay < lastday:
|
while tmp_day < lastday:
|
||||||
if tmpDay.weekday() == 0:
|
if tmp_day.weekday() == 0:
|
||||||
print tmpDay.strftime('%d.%m.%Y')
|
print tmp_day.strftime('%d.%m.%Y')
|
||||||
tmpDay += datetime.timedelta(days=1)
|
tmp_day += datetime.timedelta(days=1)
|
||||||
|
|
|
@ -1,40 +1,44 @@
|
||||||
#!/usr/bin/python
|
#!/usr/bin/python
|
||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
|
|
||||||
def printArr(a):
|
|
||||||
|
def print_arr(a):
|
||||||
for line in a:
|
for line in a:
|
||||||
print(line)
|
print(line)
|
||||||
|
|
||||||
|
|
||||||
def initialise(n):
|
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
|
return array
|
||||||
|
|
||||||
def spiralFill(a):
|
|
||||||
|
def spiral_fill(a):
|
||||||
n = len(a)
|
n = len(a)
|
||||||
x = y = n/2
|
x = y = n/2
|
||||||
number = 1
|
number = 1
|
||||||
# r u l o
|
# r u l o
|
||||||
order = [(1,0), (0,1), (-1,0), (0,-1)]
|
order = [(1, 0), (0, 1), (-1, 0), (0, -1)]
|
||||||
iOrder = 0
|
i_order = 0
|
||||||
length = 1
|
length = 1
|
||||||
a[y][x] = number
|
a[y][x] = number
|
||||||
while not (x == (n-1) and y == 0):
|
while not (x == (n-1) and y == 0):
|
||||||
for j in xrange(0, length):
|
for j in xrange(0, length):
|
||||||
xAdd, yAdd = order[iOrder]
|
xAdd, yAdd = order[i_order]
|
||||||
x += xAdd
|
x += xAdd
|
||||||
y += yAdd
|
y += yAdd
|
||||||
number += 1
|
number += 1
|
||||||
a[y][x] = number
|
a[y][x] = number
|
||||||
if x == (n-1) and y==0:
|
if x == (n-1) and y == 0:
|
||||||
break
|
break
|
||||||
if iOrder == 1 or iOrder == 3:
|
if i_order == 1 or i_order == 3:
|
||||||
length += 1
|
length += 1
|
||||||
iOrder = (iOrder+1) % 4
|
i_order = (i_order+1) % 4
|
||||||
return a
|
return a
|
||||||
|
|
||||||
def diagonalSum(a):
|
|
||||||
|
def diagonal_sum(a):
|
||||||
n = len(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):
|
for i in xrange(0, n):
|
||||||
sum += a[i][i]
|
sum += a[i][i]
|
||||||
sum += a[n-i-1][i]
|
sum += a[n-i-1][i]
|
||||||
|
@ -42,15 +46,15 @@ def diagonalSum(a):
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
import argparse
|
import argparse
|
||||||
|
|
||||||
parser = argparse.ArgumentParser(description="ProjectEuler: 28")
|
parser = argparse.ArgumentParser(description="ProjectEuler: 28")
|
||||||
parser.add_argument("-n", metavar='N', type=int,
|
parser.add_argument("-n", metavar='N', type=int,
|
||||||
help="length of the spiral", required=True)
|
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")
|
help="display the spiral")
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
array = initialise(args.n)
|
array = initialise(args.n)
|
||||||
array = spiralFill(array)
|
array = spiral_fill(array)
|
||||||
if args.d:
|
if args.d:
|
||||||
printArr(array)
|
print_arr(array)
|
||||||
print diagonalSum(array)
|
print diagonal_sum(array)
|
||||||
|
|
|
@ -1,12 +1,14 @@
|
||||||
#!/usr/bin/env python
|
#!/usr/bin/env python
|
||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
|
|
||||||
|
|
||||||
def string(zahl):
|
def string(zahl):
|
||||||
if zahl <= 9:
|
if zahl <= 9:
|
||||||
return str(zahl)
|
return str(zahl)
|
||||||
else:
|
else:
|
||||||
return chr(55+zahl)
|
return chr(55+zahl)
|
||||||
|
|
||||||
|
|
||||||
def horner(b, Z):
|
def horner(b, Z):
|
||||||
ergebnis = ''
|
ergebnis = ''
|
||||||
while Z > 0:
|
while Z > 0:
|
||||||
|
|
|
@ -1,49 +1,53 @@
|
||||||
#!/usr/bin/env python
|
#!/usr/bin/env python
|
||||||
# -*- coding: utf-8 -*-
|
# -*- 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:
|
def extended_euclidean_algorithm(a, b):
|
||||||
If gcd(a,b) = 1 = a*x + b*y
|
"""
|
||||||
Then x is multiplicative inverse of a modulo b.
|
Calculates gcd(a,b) and a linear combination such that
|
||||||
"""
|
gcd(a,b) = a*x + b*y
|
||||||
aO, bO = a, b
|
|
||||||
|
|
||||||
x=lasty=0
|
As a side effect:
|
||||||
y=lastx=1
|
If gcd(a,b) = 1 = a*x + b*y
|
||||||
while (b!=0):
|
Then x is multiplicative inverse of a modulo b.
|
||||||
q= a/b
|
"""
|
||||||
a, b = b, a%b
|
aO, bO = a, b
|
||||||
x, lastx = lastx-q*x, x
|
|
||||||
y, lasty = lasty-q*y, y
|
|
||||||
|
|
||||||
return {
|
x = lasty = 0
|
||||||
"x": lastx,
|
y = lastx = 1
|
||||||
"y": lasty,
|
while (b != 0):
|
||||||
"gcd": aO * lastx + bO * lasty
|
q = a/b
|
||||||
}
|
a, b = b, a % b
|
||||||
|
x, lastx = lastx-q*x, x
|
||||||
|
y, lasty = lasty-q*y, y
|
||||||
|
|
||||||
def solveLinearCongruenceEquations(rests, modulos):
|
return {
|
||||||
"""
|
"x": lastx,
|
||||||
Solve a system of linear congruences.
|
"y": lasty,
|
||||||
|
"gcd": aO * lastx + bO * lasty
|
||||||
|
}
|
||||||
|
|
||||||
>>> 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):
|
def solve_linear_congruence_equations(rests, modulos):
|
||||||
Mi = M / mi
|
"""
|
||||||
s = ExtendedEuclideanAlgorithm(Mi, mi)["x"]
|
Solve a system of linear congruences.
|
||||||
e = s * Mi
|
|
||||||
x += resti * e
|
Examples
|
||||||
return {"congruence class": ((x % M) + M) % M, "modulo": M}
|
--------
|
||||||
|
>>> 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__":
|
if __name__ == "__main__":
|
||||||
import doctest
|
import doctest
|
||||||
doctest.testmod()
|
doctest.testmod()
|
||||||
|
|
|
@ -1,17 +1,18 @@
|
||||||
#!/usr/bin/env python
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
|
||||||
def wer(r, h):
|
def wer(r, h):
|
||||||
"""
|
"""
|
||||||
Calculation of WER with Levenshtein distance.
|
Calculation of WER with Levenshtein distance.
|
||||||
Works only for iterables up to 254 elements (uint8).
|
Works only for iterables up to 254 elements (uint8).
|
||||||
O(nm) time ans space complexity.
|
O(nm) time ans space complexity.
|
||||||
|
|
||||||
>>> wer("who is there".split(), "is there".split())
|
>>> wer("who is there".split(), "is there".split())
|
||||||
1
|
1
|
||||||
>>> wer("who is there".split(), "".split())
|
>>> wer("who is there".split(), "".split())
|
||||||
3
|
3
|
||||||
>>> wer("".split(), "who is there".split())
|
>>> wer("".split(), "who is there".split())
|
||||||
3
|
3
|
||||||
"""
|
"""
|
||||||
# initialisation
|
# initialisation
|
||||||
import numpy
|
import numpy
|
||||||
|
@ -31,8 +32,8 @@ def wer(r, h):
|
||||||
d[i][j] = d[i-1][j-1]
|
d[i][j] = d[i-1][j-1]
|
||||||
else:
|
else:
|
||||||
substitution = d[i-1][j-1] + 1
|
substitution = d[i-1][j-1] + 1
|
||||||
insertion = d[i][j-1] + 1
|
insertion = d[i][j-1] + 1
|
||||||
deletion = d[i-1][j] + 1
|
deletion = d[i-1][j] + 1
|
||||||
d[i][j] = min(substitution, insertion, deletion)
|
d[i][j] = min(substitution, insertion, deletion)
|
||||||
|
|
||||||
return d[len(r)][len(h)]
|
return d[len(r)][len(h)]
|
||||||
|
|
|
@ -4,11 +4,13 @@
|
||||||
from math import factorial
|
from math import factorial
|
||||||
from gmpy import bincoef
|
from gmpy import bincoef
|
||||||
|
|
||||||
f = open('data.csv', 'w')
|
|
||||||
f.write('People\tprobability\n')
|
|
||||||
|
|
||||||
def prob(people):
|
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):
|
if __name__ == '__main__':
|
||||||
f.write("%i\t%f\n" % (people, prob(people)))
|
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)))
|
||||||
|
|
|
@ -8,7 +8,7 @@ print """\documentclass{article}
|
||||||
\usepackage{tikz}
|
\usepackage{tikz}
|
||||||
\usepackage{tkz-fct}
|
\usepackage{tkz-fct}
|
||||||
\usetikzlibrary{shapes.misc}
|
\usetikzlibrary{shapes.misc}
|
||||||
\usetikzlibrary{shapes, calc, decorations}
|
\usetikzlibrary{shapes, calc, decorations}
|
||||||
\usepackage{amsmath,amssymb}
|
\usepackage{amsmath,amssymb}
|
||||||
|
|
||||||
\\begin{document}
|
\\begin{document}
|
||||||
|
@ -21,7 +21,8 @@ print """\documentclass{article}
|
||||||
minimum height=4pt}]
|
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))
|
x = px + radius * math.cos(math.radians(angle))
|
||||||
y = py + radius * math.sin(math.radians(angle))
|
y = py + radius * math.sin(math.radians(angle))
|
||||||
return (x, y)
|
return (x, y)
|
||||||
|
@ -29,18 +30,18 @@ def getPositionFromOffset(px, py, angle, radius):
|
||||||
n = 5
|
n = 5
|
||||||
xSum = 0
|
xSum = 0
|
||||||
ySum = 0
|
ySum = 0
|
||||||
coordinates = [(0,0)]
|
coordinates = [(0, 0)]
|
||||||
|
|
||||||
random.seed(13)
|
random.seed(13)
|
||||||
|
|
||||||
for i in range(n-1):
|
for i in range(n-1):
|
||||||
radius = uniform(0,20)
|
radius = uniform(0, 20)
|
||||||
angle = uniform(0, 360)
|
angle = uniform(0, 360)
|
||||||
px, py = coordinates[-1]
|
px, py = coordinates[-1]
|
||||||
x, y = getPositionFromOffset(px, py, angle, radius)
|
x, y = get_position_from_offset(px, py, angle, radius)
|
||||||
xSum += x
|
xSum += x
|
||||||
ySum += y
|
ySum += y
|
||||||
coordinates.append((x,y))
|
coordinates.append((x, y))
|
||||||
|
|
||||||
center = (float(xSum) / n, float(ySum) / n)
|
center = (float(xSum) / n, float(ySum) / n)
|
||||||
|
|
||||||
|
@ -49,17 +50,18 @@ coordinates.append((cx+15, cy))
|
||||||
|
|
||||||
pointCoords = ""
|
pointCoords = ""
|
||||||
for p in coordinates:
|
for p in coordinates:
|
||||||
px, py = p
|
px, py = p
|
||||||
px -= cx
|
px -= cx
|
||||||
py -= cy
|
py -= cy
|
||||||
newP = "(%.2f,%.2f)," % (px, py)
|
newP = "(%.2f,%.2f)," % (px, py)
|
||||||
pointCoords = newP + pointCoords
|
pointCoords = newP + pointCoords
|
||||||
deltaY = 0-py
|
deltaY = 0-py
|
||||||
deltaX = 0-px
|
deltaX = 0-px
|
||||||
length = (deltaY**2+deltaX**2)**0.5
|
length = (deltaY**2+deltaX**2)**0.5
|
||||||
sinAlpha = deltaY/length
|
sinAlpha = deltaY/length
|
||||||
cosAlpha = deltaX/length
|
cosAlpha = deltaX/length
|
||||||
print("\draw[->] (%.2f,%.2f) -- (%.2f,%.2f);" % (px, py, px+cosAlpha*length*0.80, py+sinAlpha*length*0.80))
|
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))
|
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("\\node[dot] at \point {};")
|
||||||
print("}")
|
print("}")
|
||||||
|
|
||||||
################################################################################
|
###############################################################################
|
||||||
random.seed(17)
|
random.seed(17)
|
||||||
xSum = 0
|
xSum = 0
|
||||||
ySum = 0
|
ySum = 0
|
||||||
coordinates = [(0,0)]
|
coordinates = [(0, 0)]
|
||||||
for i in range(n-1):
|
for i in range(n-1):
|
||||||
radius = uniform(0,20)
|
radius = uniform(0, 20)
|
||||||
angle = uniform(0, 360)
|
angle = uniform(0, 360)
|
||||||
px, py = coordinates[-1]
|
px, py = coordinates[-1]
|
||||||
x, y = getPositionFromOffset(px, py, angle, radius)
|
x, y = get_position_from_offset(px, py, angle, radius)
|
||||||
xSum += x
|
xSum += x
|
||||||
ySum += y
|
ySum += y
|
||||||
coordinates.append((x,y))
|
coordinates.append((x, y))
|
||||||
|
|
||||||
center = (float(xSum) / n, float(ySum) / n)
|
center = (float(xSum) / n, float(ySum) / n)
|
||||||
|
|
||||||
cx, cy = center
|
cx, cy = center
|
||||||
coordinates.append((cx-15,cy))
|
coordinates.append((cx-15, cy))
|
||||||
xOffset = 40
|
xOffset = 40
|
||||||
cTmp = []
|
cTmp = []
|
||||||
for p in coordinates:
|
for p in coordinates:
|
||||||
px, py = p
|
px, py = p
|
||||||
cTmp.append((px-cx+xOffset,py-cy))
|
cTmp.append((px-cx+xOffset, py-cy))
|
||||||
|
|
||||||
coordinates = cTmp
|
coordinates = cTmp
|
||||||
cx, cy = xOffset, 0
|
cx, cy = xOffset, 0
|
||||||
pointCoords = ""
|
pointCoords = ""
|
||||||
|
|
||||||
for p in coordinates:
|
for p in coordinates:
|
||||||
px, py = p
|
px, py = p
|
||||||
newP = "(%.2f,%.2f)," % (px, py)
|
newP = "(%.2f,%.2f)," % (px, py)
|
||||||
pointCoords = newP + pointCoords
|
pointCoords = newP + pointCoords
|
||||||
deltaY = -py
|
deltaY = -py
|
||||||
deltaX = xOffset-px
|
deltaX = xOffset-px
|
||||||
length = (deltaY**2+deltaX**2)**0.5
|
length = (deltaY**2+deltaX**2)**0.5
|
||||||
sinAlpha = deltaY/length
|
sinAlpha = deltaY/length
|
||||||
cosAlpha = deltaX/length
|
cosAlpha = deltaX/length
|
||||||
print("\draw[->] (%.2f,%.2f) -- (%.2f,%.2f);" % (px, py, px+cosAlpha*length*0.80, py+sinAlpha*length*0.80))
|
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))
|
print("\\node[circle,inner sep=1pt,fill] at (%.2f,%.2f) {};" % (xOffset, 0))
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
def giveCoordinates(n):
|
def give_coordinates(n):
|
||||||
for y in range(0,n):
|
for y in range(0, n):
|
||||||
for x in range(y,2*n-y,2):
|
for x in range(y, 2*n-y, 2):
|
||||||
print(x,y)
|
print(x, y)
|
||||||
print("")
|
print("")
|
||||||
|
|
||||||
giveCoordinates(5)
|
give_coordinates(5)
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue