2
0
Fork 0
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:
Martin Thoma 2015-11-20 23:12:22 +01:00
parent b36776fc27
commit de1ad26035
14 changed files with 349 additions and 311 deletions

View file

@ -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))

View file

@ -1,6 +1,7 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def get_next(n, i, damen_pos):
for i in range(n):
candidates = set(list(range(n)))
@ -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,6 +23,7 @@ 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.
@ -37,6 +40,7 @@ def finde_loesung(n):
i += 1
i, damen = get_next(n, i, damen)
def alle_loesungen(n):
generator = finde_loesung(n)
return list(generator)

View file

@ -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))

View file

@ -2,8 +2,8 @@
# -*- 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
@ -12,16 +12,17 @@ sys.setrecursionlimit(300000)
source = 'SCC.txt'
N = 875714
#globals
# globals
visited = {}
finish = {}
leader = {}
def getG(source):
def get_g(source):
""" Read the Graph from a textfile """
G = {}
Grev = {}
for i in range(1,N+1):
for i in range(1, N+1):
G[i] = []
Grev[i] = []
fin = open(source)
@ -33,56 +34,61 @@ def getG(source):
fin.close()
return G, Grev
def init():
for i in range(1,N+1):
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
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())
stat = []
pre = 0
for i in range(0,N-1):
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()

View file

@ -38,38 +38,43 @@ def strongly_connected_components(graph):
# 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))
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])
lowlinks[node] = min(lowlinks[node], lowlinks[successor])
elif successor in stack:
#else:
print("successor in stack: %s -> %s" % (node, successor));
# 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])
lowlinks[node] = min(lowlinks[node], index[successor])
else:
print("This happens sometimes. node: %s, successor: %s" % (node, successor))
print("Lowlinks: %s" %lowlinks)
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]))
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
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]))
print("Node: %s, lowlink: %i, index: %i" %
(node, lowlinks[node], index[node]))
for node in graph:
if node not in lowlinks:

View file

@ -23,11 +23,11 @@ def strongly_connected_components(graph):
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])
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])
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]:
@ -36,7 +36,8 @@ def strongly_connected_components(graph):
while True:
successor = stack.pop()
connected_component.append(successor)
if successor == node: break
if successor == node:
break
component = tuple(connected_component)

View file

@ -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)

View file

@ -1,38 +1,42 @@
#!/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
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
for i in xrange(0, n):
@ -46,11 +50,11 @@ if __name__ == "__main__":
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)

View file

@ -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:

View file

@ -1,7 +1,8 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def ExtendedEuclideanAlgorithm(a, b):
def extended_euclidean_algorithm(a, b):
"""
Calculates gcd(a,b) and a linear combination such that
gcd(a,b) = a*x + b*y
@ -12,11 +13,11 @@ def ExtendedEuclideanAlgorithm(a, b):
"""
aO, bO = a, b
x=lasty=0
y=lastx=1
while (b!=0):
q= a/b
a, b = b, 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
@ -26,11 +27,14 @@ def ExtendedEuclideanAlgorithm(a, b):
"gcd": aO * lastx + bO * lasty
}
def solveLinearCongruenceEquations(rests, modulos):
def solve_linear_congruence_equations(rests, modulos):
"""
Solve a system of linear congruences.
>>> solveLinearCongruenceEquations([4, 12, 14], [19, 37, 43])
Examples
--------
>>> solve_linear_congruence_equations([4, 12, 14], [19, 37, 43])
{'congruence class': 22804, 'modulo': 30229}
"""
assert len(rests) == len(modulos)
@ -39,7 +43,7 @@ def solveLinearCongruenceEquations(rests, modulos):
for mi, resti in zip(modulos, rests):
Mi = M / mi
s = ExtendedEuclideanAlgorithm(Mi, mi)["x"]
s = extended_euclidean_algorithm(Mi, mi)["x"]
e = s * Mi
x += resti * e
return {"congruence class": ((x % M) + M) % M, "modulo": M}

View file

@ -1,5 +1,6 @@
#!/usr/bin/env python
def wer(r, h):
"""
Calculation of WER with Levenshtein distance.

View file

@ -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):
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)))

View file

@ -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)
radius = uniform(0, 20)
angle = uniform(0, 360)
px, py = coordinates[-1]
x, y = getPositionFromOffset(px, py, angle, radius)
x, y = get_position_from_offset(px, py, angle, radius)
xSum += x
ySum += y
coordinates.append((x,y))
coordinates.append((x, y))
center = (float(xSum) / n, float(ySum) / n)
@ -59,7 +60,8 @@ for p in coordinates:
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("\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,29 +69,29 @@ 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)
radius = uniform(0, 20)
angle = uniform(0, 360)
px, py = coordinates[-1]
x, y = getPositionFromOffset(px, py, angle, radius)
x, y = get_position_from_offset(px, py, angle, radius)
xSum += x
ySum += y
coordinates.append((x,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))
cTmp.append((px-cx+xOffset, py-cy))
coordinates = cTmp
cx, cy = xOffset, 0
@ -104,7 +106,8 @@ for p in coordinates:
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("\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))

View file

@ -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)