repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
jilljenn/tryalgo
tryalgo/scalar.py
min_scalar_prod
def min_scalar_prod(x, y): """Permute vector to minimize scalar product :param x: :param y: x, y are vectors of same size :returns: min sum x[i] * y[sigma[i]] over all permutations sigma :complexity: O(n log n) """ x = sorted(x) # make copies y = sorted(y) # to save arguments return sum(x[i] * y[-i - 1] for i in range(len(x)))
python
def min_scalar_prod(x, y): """Permute vector to minimize scalar product :param x: :param y: x, y are vectors of same size :returns: min sum x[i] * y[sigma[i]] over all permutations sigma :complexity: O(n log n) """ x = sorted(x) # make copies y = sorted(y) # to save arguments return sum(x[i] * y[-i - 1] for i in range(len(x)))
[ "def", "min_scalar_prod", "(", "x", ",", "y", ")", ":", "x", "=", "sorted", "(", "x", ")", "# make copies", "y", "=", "sorted", "(", "y", ")", "# to save arguments", "return", "sum", "(", "x", "[", "i", "]", "*", "y", "[", "-", "i", "-", "1", "...
Permute vector to minimize scalar product :param x: :param y: x, y are vectors of same size :returns: min sum x[i] * y[sigma[i]] over all permutations sigma :complexity: O(n log n)
[ "Permute", "vector", "to", "minimize", "scalar", "product" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/scalar.py#L8-L18
train
208,700
jilljenn/tryalgo
tryalgo/laser_mirrors.py
laser_mirrors
def laser_mirrors(rows, cols, mir): """Orienting mirrors to allow reachability by laser beam :param int rows: :param int cols: rows and cols are the dimension of the grid :param mir: list of mirror coordinates, except mir[0]= laser entrance, mir[-1]= laser exit. :complexity: :math:`O(2^n)` """ # build structures n = len(mir) orien = [None] * (n + 2) orien[n] = 0 # arbitrary orientations orien[n + 1] = 0 succ = [[None for direc in range(4)] for i in range(n + 2)] L = [(mir[i][0], mir[i][1], i) for i in range(n)] L.append((0, -1, n)) # enter L.append((0, cols, n + 1)) # exit last_r, last_i = None, None for (r, c, i) in sorted(L): # sweep by row if last_r == r: succ[i][LEFT] = last_i succ[last_i][RIGHT] = i last_r, last_i = r, i last_c = None for (r, c, i) in sorted(L, key=lambda rci: (rci[1], rci[0])): if last_c == c: # sweep by column succ[i][UP] = last_i succ[last_i][DOWN] = i last_c, last_i = c, i if solve(succ, orien, n, RIGHT): # exploration return orien[:n] else: return None
python
def laser_mirrors(rows, cols, mir): """Orienting mirrors to allow reachability by laser beam :param int rows: :param int cols: rows and cols are the dimension of the grid :param mir: list of mirror coordinates, except mir[0]= laser entrance, mir[-1]= laser exit. :complexity: :math:`O(2^n)` """ # build structures n = len(mir) orien = [None] * (n + 2) orien[n] = 0 # arbitrary orientations orien[n + 1] = 0 succ = [[None for direc in range(4)] for i in range(n + 2)] L = [(mir[i][0], mir[i][1], i) for i in range(n)] L.append((0, -1, n)) # enter L.append((0, cols, n + 1)) # exit last_r, last_i = None, None for (r, c, i) in sorted(L): # sweep by row if last_r == r: succ[i][LEFT] = last_i succ[last_i][RIGHT] = i last_r, last_i = r, i last_c = None for (r, c, i) in sorted(L, key=lambda rci: (rci[1], rci[0])): if last_c == c: # sweep by column succ[i][UP] = last_i succ[last_i][DOWN] = i last_c, last_i = c, i if solve(succ, orien, n, RIGHT): # exploration return orien[:n] else: return None
[ "def", "laser_mirrors", "(", "rows", ",", "cols", ",", "mir", ")", ":", "# build structures", "n", "=", "len", "(", "mir", ")", "orien", "=", "[", "None", "]", "*", "(", "n", "+", "2", ")", "orien", "[", "n", "]", "=", "0", "# arbitrary orientation...
Orienting mirrors to allow reachability by laser beam :param int rows: :param int cols: rows and cols are the dimension of the grid :param mir: list of mirror coordinates, except mir[0]= laser entrance, mir[-1]= laser exit. :complexity: :math:`O(2^n)`
[ "Orienting", "mirrors", "to", "allow", "reachability", "by", "laser", "beam" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/laser_mirrors.py#L18-L52
train
208,701
jilljenn/tryalgo
tryalgo/laser_mirrors.py
solve
def solve(succ, orien, i, direc): """Can a laser leaving mirror i in direction direc reach exit ? :param i: mirror index :param direc: direction leaving mirror i :param orient: orient[i]=orientation of mirror i :param succ: succ[i][direc]=succ mirror reached when leaving i in direction direc """ assert orien[i] is not None j = succ[i][direc] if j is None: # basic case return False if j == len(orien) - 1: return True if orien[j] is None: # try both orientations for x in [0, 1]: orien[j] = x if solve(succ, orien, j, reflex[direc][x]): return True orien[j] = None return False else: return solve(succ, orien, j, reflex[direc][orien[j]])
python
def solve(succ, orien, i, direc): """Can a laser leaving mirror i in direction direc reach exit ? :param i: mirror index :param direc: direction leaving mirror i :param orient: orient[i]=orientation of mirror i :param succ: succ[i][direc]=succ mirror reached when leaving i in direction direc """ assert orien[i] is not None j = succ[i][direc] if j is None: # basic case return False if j == len(orien) - 1: return True if orien[j] is None: # try both orientations for x in [0, 1]: orien[j] = x if solve(succ, orien, j, reflex[direc][x]): return True orien[j] = None return False else: return solve(succ, orien, j, reflex[direc][orien[j]])
[ "def", "solve", "(", "succ", ",", "orien", ",", "i", ",", "direc", ")", ":", "assert", "orien", "[", "i", "]", "is", "not", "None", "j", "=", "succ", "[", "i", "]", "[", "direc", "]", "if", "j", "is", "None", ":", "# basic case", "return", "Fal...
Can a laser leaving mirror i in direction direc reach exit ? :param i: mirror index :param direc: direction leaving mirror i :param orient: orient[i]=orientation of mirror i :param succ: succ[i][direc]=succ mirror reached when leaving i in direction direc
[ "Can", "a", "laser", "leaving", "mirror", "i", "in", "direction", "direc", "reach", "exit", "?" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/laser_mirrors.py#L57-L80
train
208,702
jilljenn/tryalgo
tryalgo/dancing_links.py
dancing_links
def dancing_links(size_universe, sets): """Exact set cover by the dancing links algorithm :param size_universe: universe = {0, 1, ..., size_universe - 1} :param sets: list of sets :returns: list of set indices partitioning the universe, or None :complexity: huge """ header = Cell(None, None, 0, None) # building the cell structure col = [] for j in range(size_universe): col.append(Cell(header, None, 0, None)) for i in range(len(sets)): row = None for j in sets[i]: col[j].S += 1 # one more entry in this column row = Cell(row, col[j], i, col[j]) sol = [] if solve(header, sol): return sol else: return None
python
def dancing_links(size_universe, sets): """Exact set cover by the dancing links algorithm :param size_universe: universe = {0, 1, ..., size_universe - 1} :param sets: list of sets :returns: list of set indices partitioning the universe, or None :complexity: huge """ header = Cell(None, None, 0, None) # building the cell structure col = [] for j in range(size_universe): col.append(Cell(header, None, 0, None)) for i in range(len(sets)): row = None for j in sets[i]: col[j].S += 1 # one more entry in this column row = Cell(row, col[j], i, col[j]) sol = [] if solve(header, sol): return sol else: return None
[ "def", "dancing_links", "(", "size_universe", ",", "sets", ")", ":", "header", "=", "Cell", "(", "None", ",", "None", ",", "0", ",", "None", ")", "# building the cell structure", "col", "=", "[", "]", "for", "j", "in", "range", "(", "size_universe", ")",...
Exact set cover by the dancing links algorithm :param size_universe: universe = {0, 1, ..., size_universe - 1} :param sets: list of sets :returns: list of set indices partitioning the universe, or None :complexity: huge
[ "Exact", "set", "cover", "by", "the", "dancing", "links", "algorithm" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/dancing_links.py#L78-L99
train
208,703
jilljenn/tryalgo
tryalgo/two_sat.py
two_sat
def two_sat(formula): """Solving a 2-SAT boolean formula :param formula: list of clauses, a clause is pair of literals over X1,...,Xn for some n. a literal is an integer, for example -1 = not X1, 3 = X3 :returns: table with boolean assignment satisfying the formula or None :complexity: linear """ # -- n is the number of variables n = max(abs(clause[p]) for p in (0, 1) for clause in formula) graph = [[] for node in range(2 * n)] for x, y in formula: # x or y graph[_vertex(-x)].append(_vertex(y)) # -x => y graph[_vertex(-y)].append(_vertex(x)) # -y => x sccp = tarjan(graph) comp_id = [None] * (2 * n) # for each node the ID of its component assignment = [None] * (2 * n) for component in sccp: rep = min(component) # representative of the component for vtx in component: comp_id[vtx] = rep if assignment[vtx] is None: assignment[vtx] = True assignment[vtx ^ 1] = False # complementary literal for i in range(n): if comp_id[2 * i] == comp_id[2 * i + 1]: return None # insatisfiable formula return assignment[::2]
python
def two_sat(formula): """Solving a 2-SAT boolean formula :param formula: list of clauses, a clause is pair of literals over X1,...,Xn for some n. a literal is an integer, for example -1 = not X1, 3 = X3 :returns: table with boolean assignment satisfying the formula or None :complexity: linear """ # -- n is the number of variables n = max(abs(clause[p]) for p in (0, 1) for clause in formula) graph = [[] for node in range(2 * n)] for x, y in formula: # x or y graph[_vertex(-x)].append(_vertex(y)) # -x => y graph[_vertex(-y)].append(_vertex(x)) # -y => x sccp = tarjan(graph) comp_id = [None] * (2 * n) # for each node the ID of its component assignment = [None] * (2 * n) for component in sccp: rep = min(component) # representative of the component for vtx in component: comp_id[vtx] = rep if assignment[vtx] is None: assignment[vtx] = True assignment[vtx ^ 1] = False # complementary literal for i in range(n): if comp_id[2 * i] == comp_id[2 * i + 1]: return None # insatisfiable formula return assignment[::2]
[ "def", "two_sat", "(", "formula", ")", ":", "# -- n is the number of variables", "n", "=", "max", "(", "abs", "(", "clause", "[", "p", "]", ")", "for", "p", "in", "(", "0", ",", "1", ")", "for", "clause", "in", "formula", ...
Solving a 2-SAT boolean formula :param formula: list of clauses, a clause is pair of literals over X1,...,Xn for some n. a literal is an integer, for example -1 = not X1, 3 = X3 :returns: table with boolean assignment satisfying the formula or None :complexity: linear
[ "Solving", "a", "2", "-", "SAT", "boolean", "formula" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/two_sat.py#L17-L45
train
208,704
jilljenn/tryalgo
tryalgo/rectangles_from_grid.py
rectangles_from_grid
def rectangles_from_grid(P, black=1): """Largest area rectangle in a binary matrix :param P: matrix :param black: search for rectangles filled with value black :returns: area, left, top, right, bottom of optimal rectangle consisting of all (i,j) with left <= j < right and top <= i <= bottom :complexity: linear """ rows = len(P) cols = len(P[0]) t = [0] * cols best = None for i in range(rows): for j in range(cols): if P[i][j] == black: t[j] += 1 else: t[j] = 0 (area, left, height, right) = rectangles_from_histogram(t) alt = (area, left, i, right, i-height) if best is None or alt > best: best = alt return best
python
def rectangles_from_grid(P, black=1): """Largest area rectangle in a binary matrix :param P: matrix :param black: search for rectangles filled with value black :returns: area, left, top, right, bottom of optimal rectangle consisting of all (i,j) with left <= j < right and top <= i <= bottom :complexity: linear """ rows = len(P) cols = len(P[0]) t = [0] * cols best = None for i in range(rows): for j in range(cols): if P[i][j] == black: t[j] += 1 else: t[j] = 0 (area, left, height, right) = rectangles_from_histogram(t) alt = (area, left, i, right, i-height) if best is None or alt > best: best = alt return best
[ "def", "rectangles_from_grid", "(", "P", ",", "black", "=", "1", ")", ":", "rows", "=", "len", "(", "P", ")", "cols", "=", "len", "(", "P", "[", "0", "]", ")", "t", "=", "[", "0", "]", "*", "cols", "best", "=", "None", "for", "i", "in", "ra...
Largest area rectangle in a binary matrix :param P: matrix :param black: search for rectangles filled with value black :returns: area, left, top, right, bottom of optimal rectangle consisting of all (i,j) with left <= j < right and top <= i <= bottom :complexity: linear
[ "Largest", "area", "rectangle", "in", "a", "binary", "matrix" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/rectangles_from_grid.py#L11-L35
train
208,705
jilljenn/tryalgo
tryalgo/min_mean_cycle.py
min_mean_cycle
def min_mean_cycle(graph, weight, start=0): """Minimum mean cycle by Karp :param graph: directed graph in listlist or listdict format :param weight: in matrix format or same listdict graph :param int start: vertex that should be contained in cycle :returns: cycle as vertex list, average arc weights or None if there is no cycle from start :complexity: `O(|V|*|E|)` """ INF = float('inf') n = len(graph) # compute distances dist = [[INF] * n] prec = [[None] * n] dist[0][start] = 0 for ell in range(1, n + 1): dist.append([INF] * n) prec.append([None] * n) for node in range(n): for neighbor in graph[node]: alt = dist[ell - 1][node] + weight[node][neighbor] if alt < dist[ell][neighbor]: dist[ell][neighbor] = alt prec[ell][neighbor] = node # -- find the optimal value valmin = INF argmin = None for node in range(n): valmax = -INF argmax = None for k in range(n): alt = (dist[n][node] - dist[k][node]) / float(n - k) # do not divide by float(n-k) => cycle of minimal total weight if alt >= valmax: # with >= we get simple cycles valmax = alt argmax = k if argmax is not None and valmax < valmin: valmin = valmax argmin = (node, argmax) # -- extract cycle if valmin == INF: # -- there is no cycle return None C = [] node, k = argmin for l in range(n, k, -1): C.append(node) node = prec[l][node] return C[::-1], valmin
python
def min_mean_cycle(graph, weight, start=0): """Minimum mean cycle by Karp :param graph: directed graph in listlist or listdict format :param weight: in matrix format or same listdict graph :param int start: vertex that should be contained in cycle :returns: cycle as vertex list, average arc weights or None if there is no cycle from start :complexity: `O(|V|*|E|)` """ INF = float('inf') n = len(graph) # compute distances dist = [[INF] * n] prec = [[None] * n] dist[0][start] = 0 for ell in range(1, n + 1): dist.append([INF] * n) prec.append([None] * n) for node in range(n): for neighbor in graph[node]: alt = dist[ell - 1][node] + weight[node][neighbor] if alt < dist[ell][neighbor]: dist[ell][neighbor] = alt prec[ell][neighbor] = node # -- find the optimal value valmin = INF argmin = None for node in range(n): valmax = -INF argmax = None for k in range(n): alt = (dist[n][node] - dist[k][node]) / float(n - k) # do not divide by float(n-k) => cycle of minimal total weight if alt >= valmax: # with >= we get simple cycles valmax = alt argmax = k if argmax is not None and valmax < valmin: valmin = valmax argmin = (node, argmax) # -- extract cycle if valmin == INF: # -- there is no cycle return None C = [] node, k = argmin for l in range(n, k, -1): C.append(node) node = prec[l][node] return C[::-1], valmin
[ "def", "min_mean_cycle", "(", "graph", ",", "weight", ",", "start", "=", "0", ")", ":", "INF", "=", "float", "(", "'inf'", ")", "n", "=", "len", "(", "graph", ")", "# compute distances", "dist", "=", "[", "[", "INF", "]", "*", "n", "]", "prec", "...
Minimum mean cycle by Karp :param graph: directed graph in listlist or listdict format :param weight: in matrix format or same listdict graph :param int start: vertex that should be contained in cycle :returns: cycle as vertex list, average arc weights or None if there is no cycle from start :complexity: `O(|V|*|E|)`
[ "Minimum", "mean", "cycle", "by", "Karp" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/min_mean_cycle.py#L8-L55
train
208,706
jilljenn/tryalgo
tryalgo/floyd_warshall.py
floyd_warshall
def floyd_warshall(weight): """All pairs shortest paths by Floyd-Warshall :param weight: edge weight matrix :modifies: weight matrix to contain distances in graph :returns: True if there are negative cycles :complexity: :math:`O(|V|^3)` """ V = range(len(weight)) for k in V: for u in V: for v in V: weight[u][v] = min(weight[u][v], weight[u][k] + weight[k][v]) for v in V: if weight[v][v] < 0: # negative cycle found return True return False
python
def floyd_warshall(weight): """All pairs shortest paths by Floyd-Warshall :param weight: edge weight matrix :modifies: weight matrix to contain distances in graph :returns: True if there are negative cycles :complexity: :math:`O(|V|^3)` """ V = range(len(weight)) for k in V: for u in V: for v in V: weight[u][v] = min(weight[u][v], weight[u][k] + weight[k][v]) for v in V: if weight[v][v] < 0: # negative cycle found return True return False
[ "def", "floyd_warshall", "(", "weight", ")", ":", "V", "=", "range", "(", "len", "(", "weight", ")", ")", "for", "k", "in", "V", ":", "for", "u", "in", "V", ":", "for", "v", "in", "V", ":", "weight", "[", "u", "]", "[", "v", "]", "=", "min"...
All pairs shortest paths by Floyd-Warshall :param weight: edge weight matrix :modifies: weight matrix to contain distances in graph :returns: True if there are negative cycles :complexity: :math:`O(|V|^3)`
[ "All", "pairs", "shortest", "paths", "by", "Floyd", "-", "Warshall" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/floyd_warshall.py#L8-L25
train
208,707
jilljenn/tryalgo
tryalgo/bellman_ford.py
bellman_ford
def bellman_ford(graph, weight, source=0): """ Single source shortest paths by Bellman-Ford :param graph: directed graph in listlist or listdict format :param weight: can be negative. in matrix format or same listdict graph :returns: distance table, precedence table, bool :explanation: bool is True if a negative circuit is reachable from the source, circuits can have length 2. :complexity: `O(|V|*|E|)` """ n = len(graph) dist = [float('inf')] * n prec = [None] * n dist[source] = 0 for nb_iterations in range(n): changed = False for node in range(n): for neighbor in graph[node]: alt = dist[node] + weight[node][neighbor] if alt < dist[neighbor]: dist[neighbor] = alt prec[neighbor] = node changed = True if not changed: # fixed point return dist, prec, False return dist, prec, True
python
def bellman_ford(graph, weight, source=0): """ Single source shortest paths by Bellman-Ford :param graph: directed graph in listlist or listdict format :param weight: can be negative. in matrix format or same listdict graph :returns: distance table, precedence table, bool :explanation: bool is True if a negative circuit is reachable from the source, circuits can have length 2. :complexity: `O(|V|*|E|)` """ n = len(graph) dist = [float('inf')] * n prec = [None] * n dist[source] = 0 for nb_iterations in range(n): changed = False for node in range(n): for neighbor in graph[node]: alt = dist[node] + weight[node][neighbor] if alt < dist[neighbor]: dist[neighbor] = alt prec[neighbor] = node changed = True if not changed: # fixed point return dist, prec, False return dist, prec, True
[ "def", "bellman_ford", "(", "graph", ",", "weight", ",", "source", "=", "0", ")", ":", "n", "=", "len", "(", "graph", ")", "dist", "=", "[", "float", "(", "'inf'", ")", "]", "*", "n", "prec", "=", "[", "None", "]", "*", "n", "dist", "[", "sou...
Single source shortest paths by Bellman-Ford :param graph: directed graph in listlist or listdict format :param weight: can be negative. in matrix format or same listdict graph :returns: distance table, precedence table, bool :explanation: bool is True if a negative circuit is reachable from the source, circuits can have length 2. :complexity: `O(|V|*|E|)`
[ "Single", "source", "shortest", "paths", "by", "Bellman", "-", "Ford" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/bellman_ford.py#L8-L35
train
208,708
jilljenn/tryalgo
tryalgo/roman_numbers.py
roman2int
def roman2int(s): """Decode roman number :param s: string representing a roman number between 1 and 9999 :returns: the decoded roman number :complexity: linear (if that makes sense for constant bounded input size) """ val = 0 pos10 = 1000 beg = 0 for pos in range(3, -1, -1): for digit in range(9,-1,-1): r = roman[pos][digit] if s.startswith(r, beg): # footnote 1 beg += len(r) val += digit * pos10 break pos10 //= 10 return val
python
def roman2int(s): """Decode roman number :param s: string representing a roman number between 1 and 9999 :returns: the decoded roman number :complexity: linear (if that makes sense for constant bounded input size) """ val = 0 pos10 = 1000 beg = 0 for pos in range(3, -1, -1): for digit in range(9,-1,-1): r = roman[pos][digit] if s.startswith(r, beg): # footnote 1 beg += len(r) val += digit * pos10 break pos10 //= 10 return val
[ "def", "roman2int", "(", "s", ")", ":", "val", "=", "0", "pos10", "=", "1000", "beg", "=", "0", "for", "pos", "in", "range", "(", "3", ",", "-", "1", ",", "-", "1", ")", ":", "for", "digit", "in", "range", "(", "9", ",", "-", "1", ",", "-...
Decode roman number :param s: string representing a roman number between 1 and 9999 :returns: the decoded roman number :complexity: linear (if that makes sense for constant bounded input size)
[ "Decode", "roman", "number" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/roman_numbers.py#L14-L32
train
208,709
jilljenn/tryalgo
tryalgo/roman_numbers.py
int2roman
def int2roman(val): """Code roman number :param val: integer between 1 and 9999 :returns: the corresponding roman number :complexity: linear (if that makes sense for constant bounded input size) """ s = '' pos10 = 1000 for pos in range(3, -1, -1): digit = val // pos10 s += roman[pos][digit] val %= pos10 pos10 //= 10 return s
python
def int2roman(val): """Code roman number :param val: integer between 1 and 9999 :returns: the corresponding roman number :complexity: linear (if that makes sense for constant bounded input size) """ s = '' pos10 = 1000 for pos in range(3, -1, -1): digit = val // pos10 s += roman[pos][digit] val %= pos10 pos10 //= 10 return s
[ "def", "int2roman", "(", "val", ")", ":", "s", "=", "''", "pos10", "=", "1000", "for", "pos", "in", "range", "(", "3", ",", "-", "1", ",", "-", "1", ")", ":", "digit", "=", "val", "//", "pos10", "s", "+=", "roman", "[", "pos", "]", "[", "di...
Code roman number :param val: integer between 1 and 9999 :returns: the corresponding roman number :complexity: linear (if that makes sense for constant bounded input size)
[ "Code", "roman", "number" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/roman_numbers.py#L52-L66
train
208,710
jilljenn/tryalgo
tryalgo/dijkstra.py
dijkstra
def dijkstra(graph, weight, source=0, target=None): """single source shortest paths by Dijkstra :param graph: directed graph in listlist or listdict format :param weight: in matrix format or same listdict graph :assumes: weights are non-negative :param source: source vertex :type source: int :param target: if given, stops once distance to target found :type target: int :returns: distance table, precedence table :complexity: `O(|V| + |E|log|V|)` """ n = len(graph) assert all(weight[u][v] >= 0 for u in range(n) for v in graph[u]) prec = [None] * n black = [False] * n dist = [float('inf')] * n dist[source] = 0 heap = [(0, source)] while heap: dist_node, node = heappop(heap) # Closest node from source if not black[node]: black[node] = True if node == target: break for neighbor in graph[node]: dist_neighbor = dist_node + weight[node][neighbor] if dist_neighbor < dist[neighbor]: dist[neighbor] = dist_neighbor prec[neighbor] = node heappush(heap, (dist_neighbor, neighbor)) return dist, prec
python
def dijkstra(graph, weight, source=0, target=None): """single source shortest paths by Dijkstra :param graph: directed graph in listlist or listdict format :param weight: in matrix format or same listdict graph :assumes: weights are non-negative :param source: source vertex :type source: int :param target: if given, stops once distance to target found :type target: int :returns: distance table, precedence table :complexity: `O(|V| + |E|log|V|)` """ n = len(graph) assert all(weight[u][v] >= 0 for u in range(n) for v in graph[u]) prec = [None] * n black = [False] * n dist = [float('inf')] * n dist[source] = 0 heap = [(0, source)] while heap: dist_node, node = heappop(heap) # Closest node from source if not black[node]: black[node] = True if node == target: break for neighbor in graph[node]: dist_neighbor = dist_node + weight[node][neighbor] if dist_neighbor < dist[neighbor]: dist[neighbor] = dist_neighbor prec[neighbor] = node heappush(heap, (dist_neighbor, neighbor)) return dist, prec
[ "def", "dijkstra", "(", "graph", ",", "weight", ",", "source", "=", "0", ",", "target", "=", "None", ")", ":", "n", "=", "len", "(", "graph", ")", "assert", "all", "(", "weight", "[", "u", "]", "[", "v", "]", ">=", "0", "for", "u", "in", "ran...
single source shortest paths by Dijkstra :param graph: directed graph in listlist or listdict format :param weight: in matrix format or same listdict graph :assumes: weights are non-negative :param source: source vertex :type source: int :param target: if given, stops once distance to target found :type target: int :returns: distance table, precedence table :complexity: `O(|V| + |E|log|V|)`
[ "single", "source", "shortest", "paths", "by", "Dijkstra" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/dijkstra.py#L11-L44
train
208,711
jilljenn/tryalgo
tryalgo/dijkstra.py
dijkstra_update_heap
def dijkstra_update_heap(graph, weight, source=0, target=None): """single source shortest paths by Dijkstra with a heap implementing item updates :param graph: adjacency list or adjacency dictionary of a directed graph :param weight: matrix or adjacency dictionary :assumes: weights are non-negatif and weights are infinite for non edges :param source: source vertex :type source: int :param target: if given, stops once distance to target found :type target: int :returns: distance table, precedence table :complexity: `O(|V| + |E|log|V|)` """ n = len(graph) assert all(weight[u][v] >= 0 for u in range(n) for v in graph[u]) prec = [None] * n dist = [float('inf')] * n dist[source] = 0 heap = OurHeap([(dist[node], node) for node in range(n)]) while heap: dist_node, node = heap.pop() # Closest node from source if node == target: break for neighbor in graph[node]: old = dist[neighbor] new = dist_node + weight[node][neighbor] if new < old: dist[neighbor] = new prec[neighbor] = node heap.update((old, neighbor), (new, neighbor)) return dist, prec
python
def dijkstra_update_heap(graph, weight, source=0, target=None): """single source shortest paths by Dijkstra with a heap implementing item updates :param graph: adjacency list or adjacency dictionary of a directed graph :param weight: matrix or adjacency dictionary :assumes: weights are non-negatif and weights are infinite for non edges :param source: source vertex :type source: int :param target: if given, stops once distance to target found :type target: int :returns: distance table, precedence table :complexity: `O(|V| + |E|log|V|)` """ n = len(graph) assert all(weight[u][v] >= 0 for u in range(n) for v in graph[u]) prec = [None] * n dist = [float('inf')] * n dist[source] = 0 heap = OurHeap([(dist[node], node) for node in range(n)]) while heap: dist_node, node = heap.pop() # Closest node from source if node == target: break for neighbor in graph[node]: old = dist[neighbor] new = dist_node + weight[node][neighbor] if new < old: dist[neighbor] = new prec[neighbor] = node heap.update((old, neighbor), (new, neighbor)) return dist, prec
[ "def", "dijkstra_update_heap", "(", "graph", ",", "weight", ",", "source", "=", "0", ",", "target", "=", "None", ")", ":", "n", "=", "len", "(", "graph", ")", "assert", "all", "(", "weight", "[", "u", "]", "[", "v", "]", ">=", "0", "for", "u", ...
single source shortest paths by Dijkstra with a heap implementing item updates :param graph: adjacency list or adjacency dictionary of a directed graph :param weight: matrix or adjacency dictionary :assumes: weights are non-negatif and weights are infinite for non edges :param source: source vertex :type source: int :param target: if given, stops once distance to target found :type target: int :returns: distance table, precedence table :complexity: `O(|V| + |E|log|V|)`
[ "single", "source", "shortest", "paths", "by", "Dijkstra", "with", "a", "heap", "implementing", "item", "updates" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/dijkstra.py#L55-L86
train
208,712
jilljenn/tryalgo
tryalgo/manacher.py
manacher
def manacher(s): """Longest palindrome in a string by Manacher :param s: string :requires: s is not empty :returns: i,j such that s[i:j] is the longest palindrome in s :complexity: O(len(s)) """ assert set.isdisjoint({'$', '^', '#'}, s) # Forbidden letters if s == "": return (0, 1) t = "^#" + "#".join(s) + "#$" c = 1 d = 1 p = [0] * len(t) for i in range(2, len(t) - 1): # -- reflect index i with respect to c mirror = 2 * c - i # = c - (i-c) p[i] = max(0, min(d - i, p[mirror])) # -- grow palindrome centered in i while t[i + 1 + p[i]] == t[i - 1 - p[i]]: p[i] += 1 # -- adjust center if necessary if i + p[i] > d: c = i d = i + p[i] (k, i) = max((p[i], i) for i in range(1, len(t) - 1)) return ((i - k) // 2, (i + k) // 2)
python
def manacher(s): """Longest palindrome in a string by Manacher :param s: string :requires: s is not empty :returns: i,j such that s[i:j] is the longest palindrome in s :complexity: O(len(s)) """ assert set.isdisjoint({'$', '^', '#'}, s) # Forbidden letters if s == "": return (0, 1) t = "^#" + "#".join(s) + "#$" c = 1 d = 1 p = [0] * len(t) for i in range(2, len(t) - 1): # -- reflect index i with respect to c mirror = 2 * c - i # = c - (i-c) p[i] = max(0, min(d - i, p[mirror])) # -- grow palindrome centered in i while t[i + 1 + p[i]] == t[i - 1 - p[i]]: p[i] += 1 # -- adjust center if necessary if i + p[i] > d: c = i d = i + p[i] (k, i) = max((p[i], i) for i in range(1, len(t) - 1)) return ((i - k) // 2, (i + k) // 2)
[ "def", "manacher", "(", "s", ")", ":", "assert", "set", ".", "isdisjoint", "(", "{", "'$'", ",", "'^'", ",", "'#'", "}", ",", "s", ")", "# Forbidden letters", "if", "s", "==", "\"\"", ":", "return", "(", "0", ",", "1", ")", "t", "=", "\"^#\"", ...
Longest palindrome in a string by Manacher :param s: string :requires: s is not empty :returns: i,j such that s[i:j] is the longest palindrome in s :complexity: O(len(s))
[ "Longest", "palindrome", "in", "a", "string", "by", "Manacher" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/manacher.py#L24-L51
train
208,713
jilljenn/tryalgo
tryalgo/bfs.py
bfs
def bfs(graph, start=0): """Shortest path in unweighted graph by BFS :param graph: directed graph in listlist or listdict format :param int start: source vertex :returns: distance table, precedence table :complexity: `O(|V|+|E|)` """ to_visit = deque() dist = [float('inf')] * len(graph) prec = [None] * len(graph) dist[start] = 0 to_visit.appendleft(start) while to_visit: # an empty queue is considered False node = to_visit.pop() for neighbor in graph[node]: if dist[neighbor] == float('inf'): dist[neighbor] = dist[node] + 1 prec[neighbor] = node to_visit.appendleft(neighbor) return dist, prec
python
def bfs(graph, start=0): """Shortest path in unweighted graph by BFS :param graph: directed graph in listlist or listdict format :param int start: source vertex :returns: distance table, precedence table :complexity: `O(|V|+|E|)` """ to_visit = deque() dist = [float('inf')] * len(graph) prec = [None] * len(graph) dist[start] = 0 to_visit.appendleft(start) while to_visit: # an empty queue is considered False node = to_visit.pop() for neighbor in graph[node]: if dist[neighbor] == float('inf'): dist[neighbor] = dist[node] + 1 prec[neighbor] = node to_visit.appendleft(neighbor) return dist, prec
[ "def", "bfs", "(", "graph", ",", "start", "=", "0", ")", ":", "to_visit", "=", "deque", "(", ")", "dist", "=", "[", "float", "(", "'inf'", ")", "]", "*", "len", "(", "graph", ")", "prec", "=", "[", "None", "]", "*", "len", "(", "graph", ")", ...
Shortest path in unweighted graph by BFS :param graph: directed graph in listlist or listdict format :param int start: source vertex :returns: distance table, precedence table :complexity: `O(|V|+|E|)`
[ "Shortest", "path", "in", "unweighted", "graph", "by", "BFS" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/bfs.py#L10-L30
train
208,714
jilljenn/tryalgo
tryalgo/graph.py
read_graph
def read_graph(filename, directed=False, weighted=False, default_weight=None): """Read a graph from a text file :param filename: plain text file. All numbers are separated by space. Starts with a line containing n (#vertices) and m (#edges). Then m lines follow, for each edge. Vertices are numbered from 0 to n-1. Line for unweighted edge u,v contains two integers u, v. Line for weighted edge u,v contains three integers u, v, w[u,v]. :param directed: true for a directed graph, false for undirected :param weighted: true for an edge weighted graph :returns: graph in listlist format, possibly followed by weight matrix :complexity: O(n + m) for unweighted graph, :math:`O(n^2)` for weighted graph """ with open(filename, 'r') as f: while True: line = f.readline() # ignore leading comments if line[0] != '#': break nb_nodes, nb_edges = tuple(map(int, line.split())) graph = [[] for u in range(nb_nodes)] if weighted: weight = [[default_weight] * nb_nodes for v in range(nb_nodes)] for v in range(nb_nodes): weight[v][v] = 0 for _ in range(nb_edges): u, v, w = readtab(f, int) graph[u].append(v) weight[u][v] = w if not directed: graph[v].append(u) weight[v][u] = w return graph, weight else: for _ in range(nb_edges): # si le fichier contient des poids, ils seront ignorés u, v = readtab(f, int)[:2] graph[u].append(v) if not directed: graph[v].append(u) return graph
python
def read_graph(filename, directed=False, weighted=False, default_weight=None): """Read a graph from a text file :param filename: plain text file. All numbers are separated by space. Starts with a line containing n (#vertices) and m (#edges). Then m lines follow, for each edge. Vertices are numbered from 0 to n-1. Line for unweighted edge u,v contains two integers u, v. Line for weighted edge u,v contains three integers u, v, w[u,v]. :param directed: true for a directed graph, false for undirected :param weighted: true for an edge weighted graph :returns: graph in listlist format, possibly followed by weight matrix :complexity: O(n + m) for unweighted graph, :math:`O(n^2)` for weighted graph """ with open(filename, 'r') as f: while True: line = f.readline() # ignore leading comments if line[0] != '#': break nb_nodes, nb_edges = tuple(map(int, line.split())) graph = [[] for u in range(nb_nodes)] if weighted: weight = [[default_weight] * nb_nodes for v in range(nb_nodes)] for v in range(nb_nodes): weight[v][v] = 0 for _ in range(nb_edges): u, v, w = readtab(f, int) graph[u].append(v) weight[u][v] = w if not directed: graph[v].append(u) weight[v][u] = w return graph, weight else: for _ in range(nb_edges): # si le fichier contient des poids, ils seront ignorés u, v = readtab(f, int)[:2] graph[u].append(v) if not directed: graph[v].append(u) return graph
[ "def", "read_graph", "(", "filename", ",", "directed", "=", "False", ",", "weighted", "=", "False", ",", "default_weight", "=", "None", ")", ":", "with", "open", "(", "filename", ",", "'r'", ")", "as", "f", ":", "while", "True", ":", "line", "=", "f"...
Read a graph from a text file :param filename: plain text file. All numbers are separated by space. Starts with a line containing n (#vertices) and m (#edges). Then m lines follow, for each edge. Vertices are numbered from 0 to n-1. Line for unweighted edge u,v contains two integers u, v. Line for weighted edge u,v contains three integers u, v, w[u,v]. :param directed: true for a directed graph, false for undirected :param weighted: true for an edge weighted graph :returns: graph in listlist format, possibly followed by weight matrix :complexity: O(n + m) for unweighted graph, :math:`O(n^2)` for weighted graph
[ "Read", "a", "graph", "from", "a", "text", "file" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/graph.py#L28-L70
train
208,715
jilljenn/tryalgo
tryalgo/graph.py
write_graph
def write_graph(dotfile, graph, directed=False, node_label=None, arc_label=None, comment="", node_mark=set(), arc_mark=set()): """Writes a graph to a file in the DOT format :param dotfile: the filename. :param graph: directed graph in listlist or listdict format :param directed: true if graph is directed, false if undirected :param weight: in matrix format or same listdict graph or None :param node_label: vertex label table or None :param arc_label: arc label matrix or None :param comment: comment string for the dot file or None :param node_mark: set of nodes to be shown in gray :param arc_marc: set of arcs to be shown in red :complexity: `O(|V| + |E|)` """ with open(dotfile, 'w') as f: if directed: f.write("digraph G{\n") else: f.write("graph G{\n") if comment: f.write('label="%s";\n' % comment) V = range(len(graph)) # -- vertices for u in V: if node_mark and u in node_mark: f.write('%d [style=filled, color="lightgrey", ' % u) else: f.write('%d [' % u) if node_label: f.write('label="%u [%s]"];\n' % (u, node_label[u])) else: f.write('shape=circle, label="%u"];\n' % u) # -- edges if isinstance(arc_mark, list): arc_mark = set((u, arc_mark[u]) for u in V) for u in V: for v in graph[u]: if not directed and u > v: continue # don't show twice the edge if arc_label and arc_label[u][v] == None: continue # suppress arcs with no label if directed: arc = "%d -> %d " % (u, v) else: arc = "%d -- %d " % (u, v) if arc_mark and ( (v,u) in arc_mark or (not directed and (u,v) in arc_mark) ): pen = 'color="red"' else: pen = "" if arc_label: tag = 'label="%s"' % arc_label[u][v] else: tag = "" if tag and pen: sep = ", " else: sep = "" f.write(arc + "[" + tag + sep + pen + "];\n") f.write("}")
python
def write_graph(dotfile, graph, directed=False, node_label=None, arc_label=None, comment="", node_mark=set(), arc_mark=set()): """Writes a graph to a file in the DOT format :param dotfile: the filename. :param graph: directed graph in listlist or listdict format :param directed: true if graph is directed, false if undirected :param weight: in matrix format or same listdict graph or None :param node_label: vertex label table or None :param arc_label: arc label matrix or None :param comment: comment string for the dot file or None :param node_mark: set of nodes to be shown in gray :param arc_marc: set of arcs to be shown in red :complexity: `O(|V| + |E|)` """ with open(dotfile, 'w') as f: if directed: f.write("digraph G{\n") else: f.write("graph G{\n") if comment: f.write('label="%s";\n' % comment) V = range(len(graph)) # -- vertices for u in V: if node_mark and u in node_mark: f.write('%d [style=filled, color="lightgrey", ' % u) else: f.write('%d [' % u) if node_label: f.write('label="%u [%s]"];\n' % (u, node_label[u])) else: f.write('shape=circle, label="%u"];\n' % u) # -- edges if isinstance(arc_mark, list): arc_mark = set((u, arc_mark[u]) for u in V) for u in V: for v in graph[u]: if not directed and u > v: continue # don't show twice the edge if arc_label and arc_label[u][v] == None: continue # suppress arcs with no label if directed: arc = "%d -> %d " % (u, v) else: arc = "%d -- %d " % (u, v) if arc_mark and ( (v,u) in arc_mark or (not directed and (u,v) in arc_mark) ): pen = 'color="red"' else: pen = "" if arc_label: tag = 'label="%s"' % arc_label[u][v] else: tag = "" if tag and pen: sep = ", " else: sep = "" f.write(arc + "[" + tag + sep + pen + "];\n") f.write("}")
[ "def", "write_graph", "(", "dotfile", ",", "graph", ",", "directed", "=", "False", ",", "node_label", "=", "None", ",", "arc_label", "=", "None", ",", "comment", "=", "\"\"", ",", "node_mark", "=", "set", "(", ")", ",", "arc_mark", "=", "set", "(", "...
Writes a graph to a file in the DOT format :param dotfile: the filename. :param graph: directed graph in listlist or listdict format :param directed: true if graph is directed, false if undirected :param weight: in matrix format or same listdict graph or None :param node_label: vertex label table or None :param arc_label: arc label matrix or None :param comment: comment string for the dot file or None :param node_mark: set of nodes to be shown in gray :param arc_marc: set of arcs to be shown in red :complexity: `O(|V| + |E|)`
[ "Writes", "a", "graph", "to", "a", "file", "in", "the", "DOT", "format" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/graph.py#L73-L133
train
208,716
jilljenn/tryalgo
tryalgo/graph.py
tree_prec_to_adj
def tree_prec_to_adj(prec, root=0): """Transforms a tree given as predecessor table into adjacency list form :param prec: predecessor table representing a tree, prec[u] == v iff u is successor of v, except for the root where prec[root] == root :param root: root vertex of the tree :returns: undirected graph in listlist representation :complexity: linear """ n = len(prec) graph = [[prec[u]] for u in range(n)] # add predecessors graph[root] = [] for u in range(n): # add successors if u != root: graph[prec[u]].append(u) return graph
python
def tree_prec_to_adj(prec, root=0): """Transforms a tree given as predecessor table into adjacency list form :param prec: predecessor table representing a tree, prec[u] == v iff u is successor of v, except for the root where prec[root] == root :param root: root vertex of the tree :returns: undirected graph in listlist representation :complexity: linear """ n = len(prec) graph = [[prec[u]] for u in range(n)] # add predecessors graph[root] = [] for u in range(n): # add successors if u != root: graph[prec[u]].append(u) return graph
[ "def", "tree_prec_to_adj", "(", "prec", ",", "root", "=", "0", ")", ":", "n", "=", "len", "(", "prec", ")", "graph", "=", "[", "[", "prec", "[", "u", "]", "]", "for", "u", "in", "range", "(", "n", ")", "]", "# add predecessors", "graph", "[", "...
Transforms a tree given as predecessor table into adjacency list form :param prec: predecessor table representing a tree, prec[u] == v iff u is successor of v, except for the root where prec[root] == root :param root: root vertex of the tree :returns: undirected graph in listlist representation :complexity: linear
[ "Transforms", "a", "tree", "given", "as", "predecessor", "table", "into", "adjacency", "list", "form" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/graph.py#L137-L152
train
208,717
jilljenn/tryalgo
tryalgo/graph.py
matrix_to_listlist
def matrix_to_listlist(weight): """transforms a squared weight matrix in a adjacency table of type listlist encoding the directed graph corresponding to the entries of the matrix different from None :param weight: squared weight matrix, weight[u][v] != None iff arc (u,v) exists :complexity: linear :returns: the unweighted directed graph in the listlist representation, listlist[u] contains all v for which arc (u,v) exists. """ graph = [[] for _ in range(len(weight))] for u in range(len(graph)): for v in range(len(graph)): if weight[u][v] != None: graph[u].append(v) return graph
python
def matrix_to_listlist(weight): """transforms a squared weight matrix in a adjacency table of type listlist encoding the directed graph corresponding to the entries of the matrix different from None :param weight: squared weight matrix, weight[u][v] != None iff arc (u,v) exists :complexity: linear :returns: the unweighted directed graph in the listlist representation, listlist[u] contains all v for which arc (u,v) exists. """ graph = [[] for _ in range(len(weight))] for u in range(len(graph)): for v in range(len(graph)): if weight[u][v] != None: graph[u].append(v) return graph
[ "def", "matrix_to_listlist", "(", "weight", ")", ":", "graph", "=", "[", "[", "]", "for", "_", "in", "range", "(", "len", "(", "weight", ")", ")", "]", "for", "u", "in", "range", "(", "len", "(", "graph", ")", ")", ":", "for", "v", "in", "range...
transforms a squared weight matrix in a adjacency table of type listlist encoding the directed graph corresponding to the entries of the matrix different from None :param weight: squared weight matrix, weight[u][v] != None iff arc (u,v) exists :complexity: linear :returns: the unweighted directed graph in the listlist representation, listlist[u] contains all v for which arc (u,v) exists.
[ "transforms", "a", "squared", "weight", "matrix", "in", "a", "adjacency", "table", "of", "type", "listlist", "encoding", "the", "directed", "graph", "corresponding", "to", "the", "entries", "of", "the", "matrix", "different", "from", "None" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/graph.py#L223-L238
train
208,718
jilljenn/tryalgo
tryalgo/graph.py
listlist_and_matrix_to_listdict
def listlist_and_matrix_to_listdict(graph, weight=None): """Transforms the weighted adjacency list representation of a graph of type listlist + optional weight matrix into the listdict representation :param graph: in listlist representation :param weight: optional weight matrix :returns: graph in listdict representation :complexity: linear """ if weight: return [{v:weight[u][v] for v in graph[u]} for u in range(len(graph))] else: return [{v:None for v in graph[u]} for u in range(len(graph))]
python
def listlist_and_matrix_to_listdict(graph, weight=None): """Transforms the weighted adjacency list representation of a graph of type listlist + optional weight matrix into the listdict representation :param graph: in listlist representation :param weight: optional weight matrix :returns: graph in listdict representation :complexity: linear """ if weight: return [{v:weight[u][v] for v in graph[u]} for u in range(len(graph))] else: return [{v:None for v in graph[u]} for u in range(len(graph))]
[ "def", "listlist_and_matrix_to_listdict", "(", "graph", ",", "weight", "=", "None", ")", ":", "if", "weight", ":", "return", "[", "{", "v", ":", "weight", "[", "u", "]", "[", "v", "]", "for", "v", "in", "graph", "[", "u", "]", "}", "for", "u", "i...
Transforms the weighted adjacency list representation of a graph of type listlist + optional weight matrix into the listdict representation :param graph: in listlist representation :param weight: optional weight matrix :returns: graph in listdict representation :complexity: linear
[ "Transforms", "the", "weighted", "adjacency", "list", "representation", "of", "a", "graph", "of", "type", "listlist", "+", "optional", "weight", "matrix", "into", "the", "listdict", "representation" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/graph.py#L241-L254
train
208,719
jilljenn/tryalgo
tryalgo/graph.py
listdict_to_listlist_and_matrix
def listdict_to_listlist_and_matrix(sparse): """Transforms the adjacency list representation of a graph of type listdict into the listlist + weight matrix representation :param sparse: graph in listdict representation :returns: couple with listlist representation, and weight matrix :complexity: linear """ V = range(len(sparse)) graph = [[] for _ in V] weight = [[None for v in V] for u in V] for u in V: for v in sparse[u]: graph[u].append(v) weight[u][v] = sparse[u][v] return graph, weight
python
def listdict_to_listlist_and_matrix(sparse): """Transforms the adjacency list representation of a graph of type listdict into the listlist + weight matrix representation :param sparse: graph in listdict representation :returns: couple with listlist representation, and weight matrix :complexity: linear """ V = range(len(sparse)) graph = [[] for _ in V] weight = [[None for v in V] for u in V] for u in V: for v in sparse[u]: graph[u].append(v) weight[u][v] = sparse[u][v] return graph, weight
[ "def", "listdict_to_listlist_and_matrix", "(", "sparse", ")", ":", "V", "=", "range", "(", "len", "(", "sparse", ")", ")", "graph", "=", "[", "[", "]", "for", "_", "in", "V", "]", "weight", "=", "[", "[", "None", "for", "v", "in", "V", "]", "for"...
Transforms the adjacency list representation of a graph of type listdict into the listlist + weight matrix representation :param sparse: graph in listdict representation :returns: couple with listlist representation, and weight matrix :complexity: linear
[ "Transforms", "the", "adjacency", "list", "representation", "of", "a", "graph", "of", "type", "listdict", "into", "the", "listlist", "+", "weight", "matrix", "representation" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/graph.py#L257-L272
train
208,720
jilljenn/tryalgo
tryalgo/graph.py
extract_path
def extract_path(prec, v): """extracts a path in form of vertex list from source to vertex v given a precedence table prec leading to the source :param prec: precedence table of a tree :param v: vertex on the tree :returns: path from root to v, in form of a list :complexity: linear """ L = [] while v is not None: L.append(v) v = prec[v] assert v not in L # prevent infinite loops for a bad formed table prec return L[::-1]
python
def extract_path(prec, v): """extracts a path in form of vertex list from source to vertex v given a precedence table prec leading to the source :param prec: precedence table of a tree :param v: vertex on the tree :returns: path from root to v, in form of a list :complexity: linear """ L = [] while v is not None: L.append(v) v = prec[v] assert v not in L # prevent infinite loops for a bad formed table prec return L[::-1]
[ "def", "extract_path", "(", "prec", ",", "v", ")", ":", "L", "=", "[", "]", "while", "v", "is", "not", "None", ":", "L", ".", "append", "(", "v", ")", "v", "=", "prec", "[", "v", "]", "assert", "v", "not", "in", "L", "# prevent infinite loops for...
extracts a path in form of vertex list from source to vertex v given a precedence table prec leading to the source :param prec: precedence table of a tree :param v: vertex on the tree :returns: path from root to v, in form of a list :complexity: linear
[ "extracts", "a", "path", "in", "form", "of", "vertex", "list", "from", "source", "to", "vertex", "v", "given", "a", "precedence", "table", "prec", "leading", "to", "the", "source" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/graph.py#L300-L314
train
208,721
jilljenn/tryalgo
tryalgo/graph.py
make_flow_labels
def make_flow_labels(graph, flow, capac): """Generate arc labels for a flow in a graph with capacities. :param graph: adjacency list or adjacency dictionary :param flow: flow matrix or adjacency dictionary :param capac: capacity matrix or adjacency dictionary :returns: listdic graph representation, with the arc label strings """ V = range(len(graph)) arc_label = [{v:"" for v in graph[u]} for u in V] for u in V: for v in graph[u]: if flow[u][v] >= 0: arc_label[u][v] = "%s/%s" % (flow[u][v], capac[u][v]) else: arc_label[u][v] = None # do not show negative flow arcs return arc_label
python
def make_flow_labels(graph, flow, capac): """Generate arc labels for a flow in a graph with capacities. :param graph: adjacency list or adjacency dictionary :param flow: flow matrix or adjacency dictionary :param capac: capacity matrix or adjacency dictionary :returns: listdic graph representation, with the arc label strings """ V = range(len(graph)) arc_label = [{v:"" for v in graph[u]} for u in V] for u in V: for v in graph[u]: if flow[u][v] >= 0: arc_label[u][v] = "%s/%s" % (flow[u][v], capac[u][v]) else: arc_label[u][v] = None # do not show negative flow arcs return arc_label
[ "def", "make_flow_labels", "(", "graph", ",", "flow", ",", "capac", ")", ":", "V", "=", "range", "(", "len", "(", "graph", ")", ")", "arc_label", "=", "[", "{", "v", ":", "\"\"", "for", "v", "in", "graph", "[", "u", "]", "}", "for", "u", "in", ...
Generate arc labels for a flow in a graph with capacities. :param graph: adjacency list or adjacency dictionary :param flow: flow matrix or adjacency dictionary :param capac: capacity matrix or adjacency dictionary :returns: listdic graph representation, with the arc label strings
[ "Generate", "arc", "labels", "for", "a", "flow", "in", "a", "graph", "with", "capacities", "." ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/graph.py#L320-L336
train
208,722
jilljenn/tryalgo
tryalgo/dilworth.py
dilworth
def dilworth(graph): """Decompose a DAG into a minimum number of chains by Dilworth :param graph: directed graph in listlist or listdict format :assumes: graph is acyclic :returns: table giving for each vertex the number of its chains :complexity: same as matching """ n = len(graph) match = max_bipartite_matching(graph) # maximum matching part = [None] * n # partition into chains nb_chains = 0 for v in range(n - 1, -1, -1): # in inverse topological order if part[v] is None: # start of chain u = v while u is not None: # follow the chain part[u] = nb_chains # mark u = match[u] nb_chains += 1 return part
python
def dilworth(graph): """Decompose a DAG into a minimum number of chains by Dilworth :param graph: directed graph in listlist or listdict format :assumes: graph is acyclic :returns: table giving for each vertex the number of its chains :complexity: same as matching """ n = len(graph) match = max_bipartite_matching(graph) # maximum matching part = [None] * n # partition into chains nb_chains = 0 for v in range(n - 1, -1, -1): # in inverse topological order if part[v] is None: # start of chain u = v while u is not None: # follow the chain part[u] = nb_chains # mark u = match[u] nb_chains += 1 return part
[ "def", "dilworth", "(", "graph", ")", ":", "n", "=", "len", "(", "graph", ")", "match", "=", "max_bipartite_matching", "(", "graph", ")", "# maximum matching", "part", "=", "[", "None", "]", "*", "n", "# partition into chains", "nb_chains", "=", "0", "for"...
Decompose a DAG into a minimum number of chains by Dilworth :param graph: directed graph in listlist or listdict format :assumes: graph is acyclic :returns: table giving for each vertex the number of its chains :complexity: same as matching
[ "Decompose", "a", "DAG", "into", "a", "minimum", "number", "of", "chains", "by", "Dilworth" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/dilworth.py#L10-L29
train
208,723
jilljenn/tryalgo
tryalgo/huffman.py
extract
def extract(code, tree, prefix=[]): """Extract Huffman code from a Huffman tree :param tree: a node of the tree :param prefix: a list with the 01 characters encoding the path from the root to the node `tree` :complexity: O(n) """ if isinstance(tree, list): l, r = tree prefix.append('0') extract(code, l, prefix) prefix.pop() prefix.append('1') extract(code, r, prefix) prefix.pop() else: code[tree] = ''.join(prefix)
python
def extract(code, tree, prefix=[]): """Extract Huffman code from a Huffman tree :param tree: a node of the tree :param prefix: a list with the 01 characters encoding the path from the root to the node `tree` :complexity: O(n) """ if isinstance(tree, list): l, r = tree prefix.append('0') extract(code, l, prefix) prefix.pop() prefix.append('1') extract(code, r, prefix) prefix.pop() else: code[tree] = ''.join(prefix)
[ "def", "extract", "(", "code", ",", "tree", ",", "prefix", "=", "[", "]", ")", ":", "if", "isinstance", "(", "tree", ",", "list", ")", ":", "l", ",", "r", "=", "tree", "prefix", ".", "append", "(", "'0'", ")", "extract", "(", "code", ",", "l", ...
Extract Huffman code from a Huffman tree :param tree: a node of the tree :param prefix: a list with the 01 characters encoding the path from the root to the node `tree` :complexity: O(n)
[ "Extract", "Huffman", "code", "from", "a", "Huffman", "tree" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/huffman.py#L29-L46
train
208,724
jilljenn/tryalgo
tryalgo/next_permutation.py
next_permutation
def next_permutation(tab): """find the next permutation of tab in the lexicographical order :param tab: table with n elements from an ordered set :modifies: table to next permutation :returns: False if permutation is already lexicographical maximal :complexity: O(n) """ n = len(tab) pivot = None # find pivot for i in range(n - 1): if tab[i] < tab[i + 1]: pivot = i if pivot is None: # tab is already the last perm. return False for i in range(pivot + 1, n): # find the element to swap if tab[i] > tab[pivot]: swap = i tab[swap], tab[pivot] = tab[pivot], tab[swap] i = pivot + 1 j = n - 1 # invert suffix while i < j: tab[i], tab[j] = tab[j], tab[i] i += 1 j -= 1 return True
python
def next_permutation(tab): """find the next permutation of tab in the lexicographical order :param tab: table with n elements from an ordered set :modifies: table to next permutation :returns: False if permutation is already lexicographical maximal :complexity: O(n) """ n = len(tab) pivot = None # find pivot for i in range(n - 1): if tab[i] < tab[i + 1]: pivot = i if pivot is None: # tab is already the last perm. return False for i in range(pivot + 1, n): # find the element to swap if tab[i] > tab[pivot]: swap = i tab[swap], tab[pivot] = tab[pivot], tab[swap] i = pivot + 1 j = n - 1 # invert suffix while i < j: tab[i], tab[j] = tab[j], tab[i] i += 1 j -= 1 return True
[ "def", "next_permutation", "(", "tab", ")", ":", "n", "=", "len", "(", "tab", ")", "pivot", "=", "None", "# find pivot", "for", "i", "in", "range", "(", "n", "-", "1", ")", ":", "if", "tab", "[", "i", "]", "<", "tab", "[", "i", "+", "1", "]",...
find the next permutation of tab in the lexicographical order :param tab: table with n elements from an ordered set :modifies: table to next permutation :returns: False if permutation is already lexicographical maximal :complexity: O(n)
[ "find", "the", "next", "permutation", "of", "tab", "in", "the", "lexicographical", "order" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/next_permutation.py#L11-L36
train
208,725
jilljenn/tryalgo
tryalgo/intervals_union.py
intervals_union
def intervals_union(S): """Union of intervals :param S: list of pairs (low, high) defining intervals [low, high) :returns: ordered list of disjoint intervals with the same union as S :complexity: O(n log n) """ E = [(low, -1) for (low, high) in S] E += [(high, +1) for (low, high) in S] nb_open = 0 last = None retval = [] for x, _dir in sorted(E): if _dir == -1: if nb_open == 0: last = x nb_open += 1 else: nb_open -= 1 if nb_open == 0: retval.append((last, x)) return retval
python
def intervals_union(S): """Union of intervals :param S: list of pairs (low, high) defining intervals [low, high) :returns: ordered list of disjoint intervals with the same union as S :complexity: O(n log n) """ E = [(low, -1) for (low, high) in S] E += [(high, +1) for (low, high) in S] nb_open = 0 last = None retval = [] for x, _dir in sorted(E): if _dir == -1: if nb_open == 0: last = x nb_open += 1 else: nb_open -= 1 if nb_open == 0: retval.append((last, x)) return retval
[ "def", "intervals_union", "(", "S", ")", ":", "E", "=", "[", "(", "low", ",", "-", "1", ")", "for", "(", "low", ",", "high", ")", "in", "S", "]", "E", "+=", "[", "(", "high", ",", "+", "1", ")", "for", "(", "low", ",", "high", ")", "in", ...
Union of intervals :param S: list of pairs (low, high) defining intervals [low, high) :returns: ordered list of disjoint intervals with the same union as S :complexity: O(n log n)
[ "Union", "of", "intervals" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/intervals_union.py#L8-L29
train
208,726
jilljenn/tryalgo
tryalgo/ford_fulkerson.py
_augment
def _augment(graph, capacity, flow, val, u, target, visit): """Find an augmenting path from u to target with value at most val""" visit[u] = True if u == target: return val for v in graph[u]: cuv = capacity[u][v] if not visit[v] and cuv > flow[u][v]: # reachable arc res = min(val, cuv - flow[u][v]) delta = _augment(graph, capacity, flow, res, v, target, visit) if delta > 0: flow[u][v] += delta # augment flow flow[v][u] -= delta return delta return 0
python
def _augment(graph, capacity, flow, val, u, target, visit): """Find an augmenting path from u to target with value at most val""" visit[u] = True if u == target: return val for v in graph[u]: cuv = capacity[u][v] if not visit[v] and cuv > flow[u][v]: # reachable arc res = min(val, cuv - flow[u][v]) delta = _augment(graph, capacity, flow, res, v, target, visit) if delta > 0: flow[u][v] += delta # augment flow flow[v][u] -= delta return delta return 0
[ "def", "_augment", "(", "graph", ",", "capacity", ",", "flow", ",", "val", ",", "u", ",", "target", ",", "visit", ")", ":", "visit", "[", "u", "]", "=", "True", "if", "u", "==", "target", ":", "return", "val", "for", "v", "in", "graph", "[", "u...
Find an augmenting path from u to target with value at most val
[ "Find", "an", "augmenting", "path", "from", "u", "to", "target", "with", "value", "at", "most", "val" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/ford_fulkerson.py#L11-L25
train
208,727
jilljenn/tryalgo
tryalgo/ford_fulkerson.py
ford_fulkerson
def ford_fulkerson(graph, capacity, s, t): """Maximum flow by Ford-Fulkerson :param graph: directed graph in listlist or listdict format :param capacity: in matrix format or same listdict graph :param int s: source vertex :param int t: target vertex :returns: flow matrix, flow value :complexity: `O(|V|*|E|*max_capacity)` """ add_reverse_arcs(graph, capacity) n = len(graph) flow = [[0] * n for _ in range(n)] INF = float('inf') while _augment(graph, capacity, flow, INF, s, t, [False] * n) > 0: pass # work already done in _augment return (flow, sum(flow[s]))
python
def ford_fulkerson(graph, capacity, s, t): """Maximum flow by Ford-Fulkerson :param graph: directed graph in listlist or listdict format :param capacity: in matrix format or same listdict graph :param int s: source vertex :param int t: target vertex :returns: flow matrix, flow value :complexity: `O(|V|*|E|*max_capacity)` """ add_reverse_arcs(graph, capacity) n = len(graph) flow = [[0] * n for _ in range(n)] INF = float('inf') while _augment(graph, capacity, flow, INF, s, t, [False] * n) > 0: pass # work already done in _augment return (flow, sum(flow[s]))
[ "def", "ford_fulkerson", "(", "graph", ",", "capacity", ",", "s", ",", "t", ")", ":", "add_reverse_arcs", "(", "graph", ",", "capacity", ")", "n", "=", "len", "(", "graph", ")", "flow", "=", "[", "[", "0", "]", "*", "n", "for", "_", "in", "range"...
Maximum flow by Ford-Fulkerson :param graph: directed graph in listlist or listdict format :param capacity: in matrix format or same listdict graph :param int s: source vertex :param int t: target vertex :returns: flow matrix, flow value :complexity: `O(|V|*|E|*max_capacity)`
[ "Maximum", "flow", "by", "Ford", "-", "Fulkerson" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/ford_fulkerson.py#L28-L45
train
208,728
jilljenn/tryalgo
tryalgo/windows_k_distinct.py
windows_k_distinct
def windows_k_distinct(x, k): """Find all largest windows containing exactly k distinct elements :param x: list or string :param k: positive integer :yields: largest intervals [i, j) with len(set(x[i:j])) == k :complexity: `O(|x|)` """ dist, i, j = 0, 0, 0 # dist = |{x[i], ..., x[j-1]}| occ = {xi: 0 for xi in x} # number of occurrences in x[i:j] while j < len(x): while dist == k: # move start of interval occ[x[i]] -= 1 # update counters if occ[x[i]] == 0: dist -= 1 i += 1 while j < len(x) and (dist < k or occ[x[j]]): if occ[x[j]] == 0: # update counters dist += 1 occ[x[j]] += 1 j += 1 # move end of interval if dist == k: yield (i, j)
python
def windows_k_distinct(x, k): """Find all largest windows containing exactly k distinct elements :param x: list or string :param k: positive integer :yields: largest intervals [i, j) with len(set(x[i:j])) == k :complexity: `O(|x|)` """ dist, i, j = 0, 0, 0 # dist = |{x[i], ..., x[j-1]}| occ = {xi: 0 for xi in x} # number of occurrences in x[i:j] while j < len(x): while dist == k: # move start of interval occ[x[i]] -= 1 # update counters if occ[x[i]] == 0: dist -= 1 i += 1 while j < len(x) and (dist < k or occ[x[j]]): if occ[x[j]] == 0: # update counters dist += 1 occ[x[j]] += 1 j += 1 # move end of interval if dist == k: yield (i, j)
[ "def", "windows_k_distinct", "(", "x", ",", "k", ")", ":", "dist", ",", "i", ",", "j", "=", "0", ",", "0", ",", "0", "# dist = |{x[i], ..., x[j-1]}|", "occ", "=", "{", "xi", ":", "0", "for", "xi", "in", "x", "}", "# number of occurrences in x[i:j]", "w...
Find all largest windows containing exactly k distinct elements :param x: list or string :param k: positive integer :yields: largest intervals [i, j) with len(set(x[i:j])) == k :complexity: `O(|x|)`
[ "Find", "all", "largest", "windows", "containing", "exactly", "k", "distinct", "elements" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/windows_k_distinct.py#L8-L30
train
208,729
jilljenn/tryalgo
tryalgo/arithm.py
bezout
def bezout(a, b): """Bezout coefficients for a and b :param a,b: non-negative integers :complexity: O(log a + log b) """ if b == 0: return (1, 0) else: u, v = bezout(b, a % b) return (v, u - (a // b) * v)
python
def bezout(a, b): """Bezout coefficients for a and b :param a,b: non-negative integers :complexity: O(log a + log b) """ if b == 0: return (1, 0) else: u, v = bezout(b, a % b) return (v, u - (a // b) * v)
[ "def", "bezout", "(", "a", ",", "b", ")", ":", "if", "b", "==", "0", ":", "return", "(", "1", ",", "0", ")", "else", ":", "u", ",", "v", "=", "bezout", "(", "b", ",", "a", "%", "b", ")", "return", "(", "v", ",", "u", "-", "(", "a", "/...
Bezout coefficients for a and b :param a,b: non-negative integers :complexity: O(log a + log b)
[ "Bezout", "coefficients", "for", "a", "and", "b" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/arithm.py#L19-L29
train
208,730
jilljenn/tryalgo
tryalgo/predictive_text.py
predictive_text
def predictive_text(dic): """Predictive text for mobile phones :param dic: associates weights to words from [a-z]* :returns: a dictionary associating to words from [2-9]* a corresponding word from the dictionary with highest weight :complexity: linear in total word length """ freq = {} # freq[p] = total weight of words having prefix p for word, weight in dic: prefix = "" for x in word: prefix += x if prefix in freq: freq[prefix] += weight else: freq[prefix] = weight # prop[s] = prefix to display for s prop = {} for prefix in freq: code = code_word(prefix) if code not in prop or freq[prop[code]] < freq[prefix]: prop[code] = prefix return prop
python
def predictive_text(dic): """Predictive text for mobile phones :param dic: associates weights to words from [a-z]* :returns: a dictionary associating to words from [2-9]* a corresponding word from the dictionary with highest weight :complexity: linear in total word length """ freq = {} # freq[p] = total weight of words having prefix p for word, weight in dic: prefix = "" for x in word: prefix += x if prefix in freq: freq[prefix] += weight else: freq[prefix] = weight # prop[s] = prefix to display for s prop = {} for prefix in freq: code = code_word(prefix) if code not in prop or freq[prop[code]] < freq[prefix]: prop[code] = prefix return prop
[ "def", "predictive_text", "(", "dic", ")", ":", "freq", "=", "{", "}", "# freq[p] = total weight of words having prefix p", "for", "word", ",", "weight", "in", "dic", ":", "prefix", "=", "\"\"", "for", "x", "in", "word", ":", "prefix", "+=", "x", "if", "pr...
Predictive text for mobile phones :param dic: associates weights to words from [a-z]* :returns: a dictionary associating to words from [2-9]* a corresponding word from the dictionary with highest weight :complexity: linear in total word length
[ "Predictive", "text", "for", "mobile", "phones" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/predictive_text.py#L24-L47
train
208,731
jilljenn/tryalgo
tryalgo/rectangles_from_points.py
rectangles_from_points
def rectangles_from_points(S): """How many rectangles can be formed from a set of points :param S: list of points, as coordinate pairs :returns: the number of rectangles :complexity: :math:`O(n^2)` """ answ = 0 pairs = {} for j in range(len(S)): for i in range(j): px, py = S[i] qx, qy = S[j] center = (px + qx, py + qy) dist = (px - qx) ** 2 + (py - qy) ** 2 sign = (center, dist) if sign in pairs: answ += len(pairs[sign]) pairs[sign].append((i, j)) else: pairs[sign] = [(i, j)] return answ
python
def rectangles_from_points(S): """How many rectangles can be formed from a set of points :param S: list of points, as coordinate pairs :returns: the number of rectangles :complexity: :math:`O(n^2)` """ answ = 0 pairs = {} for j in range(len(S)): for i in range(j): px, py = S[i] qx, qy = S[j] center = (px + qx, py + qy) dist = (px - qx) ** 2 + (py - qy) ** 2 sign = (center, dist) if sign in pairs: answ += len(pairs[sign]) pairs[sign].append((i, j)) else: pairs[sign] = [(i, j)] return answ
[ "def", "rectangles_from_points", "(", "S", ")", ":", "answ", "=", "0", "pairs", "=", "{", "}", "for", "j", "in", "range", "(", "len", "(", "S", ")", ")", ":", "for", "i", "in", "range", "(", "j", ")", ":", "px", ",", "py", "=", "S", "[", "i...
How many rectangles can be formed from a set of points :param S: list of points, as coordinate pairs :returns: the number of rectangles :complexity: :math:`O(n^2)`
[ "How", "many", "rectangles", "can", "be", "formed", "from", "a", "set", "of", "points" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/rectangles_from_points.py#L8-L29
train
208,732
jilljenn/tryalgo
tryalgo/biconnected_components.py
cut_nodes_edges
def cut_nodes_edges(graph): """Bi-connected components :param graph: undirected graph. in listlist format. Cannot be in listdict format. :returns: a tuple with the list of cut-nodes and the list of cut-edges :complexity: `O(|V|+|E|)` """ n = len(graph) time = 0 num = [None] * n low = [n] * n father = [None] * n # father[v] = None if root else father of v critical_childs = [0] * n # c_c[u] = #childs v s.t. low[v] >= num[u] times_seen = [-1] * n for start in range(n): if times_seen[start] == -1: # init DFS path times_seen[start] = 0 to_visit = [start] while to_visit: node = to_visit[-1] if times_seen[node] == 0: # start processing num[node] = time time += 1 low[node] = float('inf') children = graph[node] if times_seen[node] == len(children): # end processing to_visit.pop() up = father[node] # propagate low to father if up is not None: low[up] = min(low[up], low[node]) if low[node] >= num[up]: critical_childs[up] += 1 else: child = children[times_seen[node]] # next arrow times_seen[node] += 1 if times_seen[child] == -1: # not visited yet father[child] = node # link arrow times_seen[child] = 0 to_visit.append(child) # (below) back arrow elif num[child] < num[node] and father[node] != child: low[node] = min(low[node], num[child]) cut_edges = [] cut_nodes = [] # extract solution for node in range(n): if father[node] is None: # characteristics if critical_childs[node] >= 2: cut_nodes.append(node) else: # internal nodes if critical_childs[node] >= 1: cut_nodes.append(node) if low[node] >= num[node]: cut_edges.append((father[node], node)) return cut_nodes, cut_edges
python
def cut_nodes_edges(graph): """Bi-connected components :param graph: undirected graph. in listlist format. Cannot be in listdict format. :returns: a tuple with the list of cut-nodes and the list of cut-edges :complexity: `O(|V|+|E|)` """ n = len(graph) time = 0 num = [None] * n low = [n] * n father = [None] * n # father[v] = None if root else father of v critical_childs = [0] * n # c_c[u] = #childs v s.t. low[v] >= num[u] times_seen = [-1] * n for start in range(n): if times_seen[start] == -1: # init DFS path times_seen[start] = 0 to_visit = [start] while to_visit: node = to_visit[-1] if times_seen[node] == 0: # start processing num[node] = time time += 1 low[node] = float('inf') children = graph[node] if times_seen[node] == len(children): # end processing to_visit.pop() up = father[node] # propagate low to father if up is not None: low[up] = min(low[up], low[node]) if low[node] >= num[up]: critical_childs[up] += 1 else: child = children[times_seen[node]] # next arrow times_seen[node] += 1 if times_seen[child] == -1: # not visited yet father[child] = node # link arrow times_seen[child] = 0 to_visit.append(child) # (below) back arrow elif num[child] < num[node] and father[node] != child: low[node] = min(low[node], num[child]) cut_edges = [] cut_nodes = [] # extract solution for node in range(n): if father[node] is None: # characteristics if critical_childs[node] >= 2: cut_nodes.append(node) else: # internal nodes if critical_childs[node] >= 1: cut_nodes.append(node) if low[node] >= num[node]: cut_edges.append((father[node], node)) return cut_nodes, cut_edges
[ "def", "cut_nodes_edges", "(", "graph", ")", ":", "n", "=", "len", "(", "graph", ")", "time", "=", "0", "num", "=", "[", "None", "]", "*", "n", "low", "=", "[", "n", "]", "*", "n", "father", "=", "[", "None", "]", "*", "n", "# father[v] = None ...
Bi-connected components :param graph: undirected graph. in listlist format. Cannot be in listdict format. :returns: a tuple with the list of cut-nodes and the list of cut-edges :complexity: `O(|V|+|E|)`
[ "Bi", "-", "connected", "components" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/biconnected_components.py#L10-L62
train
208,733
jilljenn/tryalgo
tryalgo/biconnected_components.py
cut_nodes_edges2
def cut_nodes_edges2(graph): """Bi-connected components, alternative recursive implementation :param graph: undirected graph. in listlist format. Cannot be in listdict format. :assumes: graph has about 5000 vertices at most, otherwise memory limit is reached :returns: a tuple with the list of cut-nodes and the list of cut-edges :complexity: `O(|V|+|E|)` in average, `O(|V|+|E|^2)` in worst case due to use of dictionary """ N = len(graph) assert N <= 5000 recursionlimit = getrecursionlimit() setrecursionlimit(max(recursionlimit, N + 42)) edges = set((i, j) for i in range(N) for j in graph[i] if i <= j) nodes = set() NOT = -2 # not visited yet; -1 would be buggy `marked[v] != prof - 1` FIN = -3 # already visited marked = [NOT] * N # if >= 0, it means depth within the DFS def DFS(n, prof=0): """ Recursively search graph, update edge list and returns the first node the first edge within search to which we can come back. """ if marked[n] == FIN: return # only when there are several connected components if marked[n] != NOT: return marked[n] marked[n] = prof m = float('inf') count = 0 # useful only for prof == 0 for v in graph[n]: if marked[v] != FIN and marked[v] != prof - 1: count += 1 r = DFS(v, prof+1) if r <= prof: edges.discard(tuple(sorted((n, v)))) if prof and r >= prof: # only if we are not at root nodes.add(n) m = min(m, r) # root is an articulation point iff it has more than 2 childs if prof == 0 and count >= 2: nodes.add(n) marked[n] = FIN return m for r in range(N): DFS(r) # we can count connected components by nb += DFS(r) setrecursionlimit(recursionlimit) return nodes, edges
python
def cut_nodes_edges2(graph): """Bi-connected components, alternative recursive implementation :param graph: undirected graph. in listlist format. Cannot be in listdict format. :assumes: graph has about 5000 vertices at most, otherwise memory limit is reached :returns: a tuple with the list of cut-nodes and the list of cut-edges :complexity: `O(|V|+|E|)` in average, `O(|V|+|E|^2)` in worst case due to use of dictionary """ N = len(graph) assert N <= 5000 recursionlimit = getrecursionlimit() setrecursionlimit(max(recursionlimit, N + 42)) edges = set((i, j) for i in range(N) for j in graph[i] if i <= j) nodes = set() NOT = -2 # not visited yet; -1 would be buggy `marked[v] != prof - 1` FIN = -3 # already visited marked = [NOT] * N # if >= 0, it means depth within the DFS def DFS(n, prof=0): """ Recursively search graph, update edge list and returns the first node the first edge within search to which we can come back. """ if marked[n] == FIN: return # only when there are several connected components if marked[n] != NOT: return marked[n] marked[n] = prof m = float('inf') count = 0 # useful only for prof == 0 for v in graph[n]: if marked[v] != FIN and marked[v] != prof - 1: count += 1 r = DFS(v, prof+1) if r <= prof: edges.discard(tuple(sorted((n, v)))) if prof and r >= prof: # only if we are not at root nodes.add(n) m = min(m, r) # root is an articulation point iff it has more than 2 childs if prof == 0 and count >= 2: nodes.add(n) marked[n] = FIN return m for r in range(N): DFS(r) # we can count connected components by nb += DFS(r) setrecursionlimit(recursionlimit) return nodes, edges
[ "def", "cut_nodes_edges2", "(", "graph", ")", ":", "N", "=", "len", "(", "graph", ")", "assert", "N", "<=", "5000", "recursionlimit", "=", "getrecursionlimit", "(", ")", "setrecursionlimit", "(", "max", "(", "recursionlimit", ",", "N", "+", "42", ")", ")...
Bi-connected components, alternative recursive implementation :param graph: undirected graph. in listlist format. Cannot be in listdict format. :assumes: graph has about 5000 vertices at most, otherwise memory limit is reached :returns: a tuple with the list of cut-nodes and the list of cut-edges :complexity: `O(|V|+|E|)` in average, `O(|V|+|E|^2)` in worst case due to use of dictionary
[ "Bi", "-", "connected", "components", "alternative", "recursive", "implementation" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/biconnected_components.py#L66-L113
train
208,734
jilljenn/tryalgo
tryalgo/polygon.py
area
def area(p): """Area of a polygone :param p: list of the points taken in any orientation, p[0] can differ from p[-1] :returns: area :complexity: linear """ A = 0 for i in range(len(p)): A += p[i - 1][0] * p[i][1] - p[i][0] * p[i - 1][1] return A / 2.
python
def area(p): """Area of a polygone :param p: list of the points taken in any orientation, p[0] can differ from p[-1] :returns: area :complexity: linear """ A = 0 for i in range(len(p)): A += p[i - 1][0] * p[i][1] - p[i][0] * p[i - 1][1] return A / 2.
[ "def", "area", "(", "p", ")", ":", "A", "=", "0", "for", "i", "in", "range", "(", "len", "(", "p", ")", ")", ":", "A", "+=", "p", "[", "i", "-", "1", "]", "[", "0", "]", "*", "p", "[", "i", "]", "[", "1", "]", "-", "p", "[", "i", ...
Area of a polygone :param p: list of the points taken in any orientation, p[0] can differ from p[-1] :returns: area :complexity: linear
[ "Area", "of", "a", "polygone" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/polygon.py#L12-L23
train
208,735
jilljenn/tryalgo
tryalgo/polygon.py
is_simple
def is_simple(polygon): """Test if a rectilinear polygon is is_simple :param polygon: list of points as (x,y) pairs along the closed polygon :returns: True if the segements do not intersect :complexity: O(n log n) for n=len(polygon) """ n = len(polygon) order = list(range(n)) order.sort(key=lambda i: polygon[i]) # lexicographic order rank_to_y = list(set(p[1] for p in polygon)) rank_to_y.sort() y_to_rank = {y: rank for rank, y in enumerate(rank_to_y)} S = RangeMinQuery([0] * len(rank_to_y)) # sweep structure last_y = None for i in order: x, y = polygon[i] rank = y_to_rank[y] # -- type of point right_x = max(polygon[i - 1][0], polygon[(i + 1) % n][0]) left = x < right_x below_y = min(polygon[i - 1][1], polygon[(i + 1) % n][1]) high = y > below_y if left: # y does not need to be in S yet if S[rank]: return False # two horizontal segments intersect S[rank] = -1 # add y to S else: S[rank] = 0 # remove y from S if high: lo = y_to_rank[below_y] # check S between [lo + 1, rank - 1] if (below_y != last_y or last_y == y or rank - lo >= 2 and S.range_min(lo + 1, rank)): return False # horiz. & vert. segments intersect last_y = y # remember for next iteration return True
python
def is_simple(polygon): """Test if a rectilinear polygon is is_simple :param polygon: list of points as (x,y) pairs along the closed polygon :returns: True if the segements do not intersect :complexity: O(n log n) for n=len(polygon) """ n = len(polygon) order = list(range(n)) order.sort(key=lambda i: polygon[i]) # lexicographic order rank_to_y = list(set(p[1] for p in polygon)) rank_to_y.sort() y_to_rank = {y: rank for rank, y in enumerate(rank_to_y)} S = RangeMinQuery([0] * len(rank_to_y)) # sweep structure last_y = None for i in order: x, y = polygon[i] rank = y_to_rank[y] # -- type of point right_x = max(polygon[i - 1][0], polygon[(i + 1) % n][0]) left = x < right_x below_y = min(polygon[i - 1][1], polygon[(i + 1) % n][1]) high = y > below_y if left: # y does not need to be in S yet if S[rank]: return False # two horizontal segments intersect S[rank] = -1 # add y to S else: S[rank] = 0 # remove y from S if high: lo = y_to_rank[below_y] # check S between [lo + 1, rank - 1] if (below_y != last_y or last_y == y or rank - lo >= 2 and S.range_min(lo + 1, rank)): return False # horiz. & vert. segments intersect last_y = y # remember for next iteration return True
[ "def", "is_simple", "(", "polygon", ")", ":", "n", "=", "len", "(", "polygon", ")", "order", "=", "list", "(", "range", "(", "n", ")", ")", "order", ".", "sort", "(", "key", "=", "lambda", "i", ":", "polygon", "[", "i", "]", ")", "# lexicographic...
Test if a rectilinear polygon is is_simple :param polygon: list of points as (x,y) pairs along the closed polygon :returns: True if the segements do not intersect :complexity: O(n log n) for n=len(polygon)
[ "Test", "if", "a", "rectilinear", "polygon", "is", "is_simple" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/polygon.py#L28-L63
train
208,736
jilljenn/tryalgo
tryalgo/closest_points.py
closest_points
def closest_points(S): """Closest pair of points :param S: list of points :requires: size of S at least 2 :modifies: changes the order in S :returns: pair of points p,q from S with minimum Euclidean distance :complexity: expected linear time """ shuffle(S) assert len(S) >= 2 p = S[0] q = S[1] d = dist(p, q) while d > 0: r = improve(S, d) if r: d, p, q = r else: break return p, q
python
def closest_points(S): """Closest pair of points :param S: list of points :requires: size of S at least 2 :modifies: changes the order in S :returns: pair of points p,q from S with minimum Euclidean distance :complexity: expected linear time """ shuffle(S) assert len(S) >= 2 p = S[0] q = S[1] d = dist(p, q) while d > 0: r = improve(S, d) if r: d, p, q = r else: break return p, q
[ "def", "closest_points", "(", "S", ")", ":", "shuffle", "(", "S", ")", "assert", "len", "(", "S", ")", ">=", "2", "p", "=", "S", "[", "0", "]", "q", "=", "S", "[", "1", "]", "d", "=", "dist", "(", "p", ",", "q", ")", "while", "d", ">", ...
Closest pair of points :param S: list of points :requires: size of S at least 2 :modifies: changes the order in S :returns: pair of points p,q from S with minimum Euclidean distance :complexity: expected linear time
[ "Closest", "pair", "of", "points" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/closest_points.py#L44-L64
train
208,737
jilljenn/tryalgo
tryalgo/longest_increasing_subsequence.py
longest_increasing_subsequence
def longest_increasing_subsequence(x): """Longest increasing subsequence :param x: sequence :returns: longest strictly increasing subsequence y :complexity: `O(|x|*log(|y|))` """ n = len(x) p = [None] * n h = [None] b = [float('-inf')] # - infinity for i in range(n): if x[i] > b[-1]: p[i] = h[-1] h.append(i) b.append(x[i]) else: # -- binary search: b[k - 1] < x[i] <= b[k] k = bisect_left(b, x[i]) h[k] = i b[k] = x[i] p[i] = h[k - 1] # extract solution q = h[-1] s = [] while q is not None: s.append(x[q]) q = p[q] return s[::-1]
python
def longest_increasing_subsequence(x): """Longest increasing subsequence :param x: sequence :returns: longest strictly increasing subsequence y :complexity: `O(|x|*log(|y|))` """ n = len(x) p = [None] * n h = [None] b = [float('-inf')] # - infinity for i in range(n): if x[i] > b[-1]: p[i] = h[-1] h.append(i) b.append(x[i]) else: # -- binary search: b[k - 1] < x[i] <= b[k] k = bisect_left(b, x[i]) h[k] = i b[k] = x[i] p[i] = h[k - 1] # extract solution q = h[-1] s = [] while q is not None: s.append(x[q]) q = p[q] return s[::-1]
[ "def", "longest_increasing_subsequence", "(", "x", ")", ":", "n", "=", "len", "(", "x", ")", "p", "=", "[", "None", "]", "*", "n", "h", "=", "[", "None", "]", "b", "=", "[", "float", "(", "'-inf'", ")", "]", "# - infinity", "for", "i", "in", "r...
Longest increasing subsequence :param x: sequence :returns: longest strictly increasing subsequence y :complexity: `O(|x|*log(|y|))`
[ "Longest", "increasing", "subsequence" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/longest_increasing_subsequence.py#L10-L38
train
208,738
jilljenn/tryalgo
tryalgo/dfs.py
dfs_recursive
def dfs_recursive(graph, node, seen): """DFS, detect connected component, recursive implementation :param graph: directed graph in listlist or listdict format :param int node: to start graph exploration :param boolean-table seen: will be set true for the connected component containing node. :complexity: `O(|V|+|E|)` """ seen[node] = True for neighbor in graph[node]: if not seen[neighbor]: dfs_recursive(graph, neighbor, seen)
python
def dfs_recursive(graph, node, seen): """DFS, detect connected component, recursive implementation :param graph: directed graph in listlist or listdict format :param int node: to start graph exploration :param boolean-table seen: will be set true for the connected component containing node. :complexity: `O(|V|+|E|)` """ seen[node] = True for neighbor in graph[node]: if not seen[neighbor]: dfs_recursive(graph, neighbor, seen)
[ "def", "dfs_recursive", "(", "graph", ",", "node", ",", "seen", ")", ":", "seen", "[", "node", "]", "=", "True", "for", "neighbor", "in", "graph", "[", "node", "]", ":", "if", "not", "seen", "[", "neighbor", "]", ":", "dfs_recursive", "(", "graph", ...
DFS, detect connected component, recursive implementation :param graph: directed graph in listlist or listdict format :param int node: to start graph exploration :param boolean-table seen: will be set true for the connected component containing node. :complexity: `O(|V|+|E|)`
[ "DFS", "detect", "connected", "component", "recursive", "implementation" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/dfs.py#L8-L20
train
208,739
jilljenn/tryalgo
tryalgo/dfs.py
dfs_iterative
def dfs_iterative(graph, start, seen): """DFS, detect connected component, iterative implementation :param graph: directed graph in listlist or listdict format :param int node: to start graph exploration :param boolean-table seen: will be set true for the connected component containing node. :complexity: `O(|V|+|E|)` """ seen[start] = True to_visit = [start] while to_visit: node = to_visit.pop() for neighbor in graph[node]: if not seen[neighbor]: seen[neighbor] = True to_visit.append(neighbor)
python
def dfs_iterative(graph, start, seen): """DFS, detect connected component, iterative implementation :param graph: directed graph in listlist or listdict format :param int node: to start graph exploration :param boolean-table seen: will be set true for the connected component containing node. :complexity: `O(|V|+|E|)` """ seen[start] = True to_visit = [start] while to_visit: node = to_visit.pop() for neighbor in graph[node]: if not seen[neighbor]: seen[neighbor] = True to_visit.append(neighbor)
[ "def", "dfs_iterative", "(", "graph", ",", "start", ",", "seen", ")", ":", "seen", "[", "start", "]", "=", "True", "to_visit", "=", "[", "start", "]", "while", "to_visit", ":", "node", "=", "to_visit", ".", "pop", "(", ")", "for", "neighbor", "in", ...
DFS, detect connected component, iterative implementation :param graph: directed graph in listlist or listdict format :param int node: to start graph exploration :param boolean-table seen: will be set true for the connected component containing node. :complexity: `O(|V|+|E|)`
[ "DFS", "detect", "connected", "component", "iterative", "implementation" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/dfs.py#L25-L41
train
208,740
jilljenn/tryalgo
tryalgo/dfs.py
dfs_tree
def dfs_tree(graph, start=0): """DFS, build DFS tree in unweighted graph :param graph: directed graph in listlist or listdict format :param int start: source vertex :returns: precedence table :complexity: `O(|V|+|E|)` """ to_visit = [start] prec = [None] * len(graph) while to_visit: # an empty queue equals False node = to_visit.pop() for neighbor in graph[node]: if prec[neighbor] is None: prec[neighbor] = node to_visit.append(neighbor) return prec
python
def dfs_tree(graph, start=0): """DFS, build DFS tree in unweighted graph :param graph: directed graph in listlist or listdict format :param int start: source vertex :returns: precedence table :complexity: `O(|V|+|E|)` """ to_visit = [start] prec = [None] * len(graph) while to_visit: # an empty queue equals False node = to_visit.pop() for neighbor in graph[node]: if prec[neighbor] is None: prec[neighbor] = node to_visit.append(neighbor) return prec
[ "def", "dfs_tree", "(", "graph", ",", "start", "=", "0", ")", ":", "to_visit", "=", "[", "start", "]", "prec", "=", "[", "None", "]", "*", "len", "(", "graph", ")", "while", "to_visit", ":", "# an empty queue equals False", "node", "=", "to_visit", "."...
DFS, build DFS tree in unweighted graph :param graph: directed graph in listlist or listdict format :param int start: source vertex :returns: precedence table :complexity: `O(|V|+|E|)`
[ "DFS", "build", "DFS", "tree", "in", "unweighted", "graph" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/dfs.py#L46-L62
train
208,741
jilljenn/tryalgo
tryalgo/dfs.py
find_cycle
def find_cycle(graph): """find a cycle in an undirected graph :param graph: undirected graph in listlist or listdict format :returns: list of vertices in a cycle or None :complexity: `O(|V|+|E|)` """ n = len(graph) prec = [None] * n # ancestor marks for visited vertices for u in range(n): if prec[u] is None: # unvisited vertex S = [u] # start new DFS prec[u] = u # mark root (not necessary for this algorithm) while S: u = S.pop() for v in graph[u]: # for all neighbors if v != prec[u]: # except arcs to father in DFS tree if prec[v] is not None: cycle = [v, u] # cycle found, (u,v) back edge while u != prec[v] and u != prec[u]: # directed u = prec[u] # climb up the tree cycle.append(u) return cycle else: prec[v] = u # v is new vertex in tree S.append(v) return None
python
def find_cycle(graph): """find a cycle in an undirected graph :param graph: undirected graph in listlist or listdict format :returns: list of vertices in a cycle or None :complexity: `O(|V|+|E|)` """ n = len(graph) prec = [None] * n # ancestor marks for visited vertices for u in range(n): if prec[u] is None: # unvisited vertex S = [u] # start new DFS prec[u] = u # mark root (not necessary for this algorithm) while S: u = S.pop() for v in graph[u]: # for all neighbors if v != prec[u]: # except arcs to father in DFS tree if prec[v] is not None: cycle = [v, u] # cycle found, (u,v) back edge while u != prec[v] and u != prec[u]: # directed u = prec[u] # climb up the tree cycle.append(u) return cycle else: prec[v] = u # v is new vertex in tree S.append(v) return None
[ "def", "find_cycle", "(", "graph", ")", ":", "n", "=", "len", "(", "graph", ")", "prec", "=", "[", "None", "]", "*", "n", "# ancestor marks for visited vertices", "for", "u", "in", "range", "(", "n", ")", ":", "if", "prec", "[", "u", "]", "is", "No...
find a cycle in an undirected graph :param graph: undirected graph in listlist or listdict format :returns: list of vertices in a cycle or None :complexity: `O(|V|+|E|)`
[ "find", "a", "cycle", "in", "an", "undirected", "graph" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/dfs.py#L110-L136
train
208,742
jilljenn/tryalgo
tryalgo/arithm_expr_eval.py
arithm_expr_eval
def arithm_expr_eval(cell, expr): """Evaluates a given expression :param expr: expression :param cell: dictionary variable name -> expression :returns: numerical value of expression :complexity: linear """ if isinstance(expr, tuple): (left, op, right) = expr lval = arithm_expr_eval(cell, left) rval = arithm_expr_eval(cell, right) if op == '+': return lval + rval if op == '-': return lval - rval if op == '*': return lval * rval if op == '/': return lval // rval elif isinstance(expr, int): return expr else: cell[expr] = arithm_expr_eval(cell, cell[expr]) return cell[expr]
python
def arithm_expr_eval(cell, expr): """Evaluates a given expression :param expr: expression :param cell: dictionary variable name -> expression :returns: numerical value of expression :complexity: linear """ if isinstance(expr, tuple): (left, op, right) = expr lval = arithm_expr_eval(cell, left) rval = arithm_expr_eval(cell, right) if op == '+': return lval + rval if op == '-': return lval - rval if op == '*': return lval * rval if op == '/': return lval // rval elif isinstance(expr, int): return expr else: cell[expr] = arithm_expr_eval(cell, cell[expr]) return cell[expr]
[ "def", "arithm_expr_eval", "(", "cell", ",", "expr", ")", ":", "if", "isinstance", "(", "expr", ",", "tuple", ")", ":", "(", "left", ",", "op", ",", "right", ")", "=", "expr", "lval", "=", "arithm_expr_eval", "(", "cell", ",", "left", ")", "rval", ...
Evaluates a given expression :param expr: expression :param cell: dictionary variable name -> expression :returns: numerical value of expression :complexity: linear
[ "Evaluates", "a", "given", "expression" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/arithm_expr_eval.py#L13-L39
train
208,743
jilljenn/tryalgo
tryalgo/arithm_expr_eval.py
arithm_expr_parse
def arithm_expr_parse(line): """Constructs an arithmetic expression tree :param line: list of token strings containing the expression :returns: expression tree :complexity: linear """ vals = [] ops = [] for tok in line + [';']: if tok in priority: # tok is an operator while (tok != '(' and ops and priority[ops[-1]] >= priority[tok]): right = vals.pop() left = vals.pop() vals.append((left, ops.pop(), right)) if tok == ')': ops.pop() # this is the corresponding '(' else: ops.append(tok) elif tok.isdigit(): # tok is an integer vals.append(int(tok)) else: # tok is an identifier vals.append(tok) return vals.pop()
python
def arithm_expr_parse(line): """Constructs an arithmetic expression tree :param line: list of token strings containing the expression :returns: expression tree :complexity: linear """ vals = [] ops = [] for tok in line + [';']: if tok in priority: # tok is an operator while (tok != '(' and ops and priority[ops[-1]] >= priority[tok]): right = vals.pop() left = vals.pop() vals.append((left, ops.pop(), right)) if tok == ')': ops.pop() # this is the corresponding '(' else: ops.append(tok) elif tok.isdigit(): # tok is an integer vals.append(int(tok)) else: # tok is an identifier vals.append(tok) return vals.pop()
[ "def", "arithm_expr_parse", "(", "line", ")", ":", "vals", "=", "[", "]", "ops", "=", "[", "]", "for", "tok", "in", "line", "+", "[", "';'", "]", ":", "if", "tok", "in", "priority", ":", "# tok is an operator", "while", "(", "tok", "!=", "'('", "an...
Constructs an arithmetic expression tree :param line: list of token strings containing the expression :returns: expression tree :complexity: linear
[ "Constructs", "an", "arithmetic", "expression", "tree" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/arithm_expr_eval.py#L47-L72
train
208,744
jilljenn/tryalgo
tryalgo/bipartite_vertex_cover.py
_alternate
def _alternate(u, bigraph, visitU, visitV, matchV): """extend alternating tree from free vertex u. visitU, visitV marks all vertices covered by the tree. """ visitU[u] = True for v in bigraph[u]: if not visitV[v]: visitV[v] = True assert matchV[v] is not None # otherwise match is not maximum _alternate(matchV[v], bigraph, visitU, visitV, matchV)
python
def _alternate(u, bigraph, visitU, visitV, matchV): """extend alternating tree from free vertex u. visitU, visitV marks all vertices covered by the tree. """ visitU[u] = True for v in bigraph[u]: if not visitV[v]: visitV[v] = True assert matchV[v] is not None # otherwise match is not maximum _alternate(matchV[v], bigraph, visitU, visitV, matchV)
[ "def", "_alternate", "(", "u", ",", "bigraph", ",", "visitU", ",", "visitV", ",", "matchV", ")", ":", "visitU", "[", "u", "]", "=", "True", "for", "v", "in", "bigraph", "[", "u", "]", ":", "if", "not", "visitV", "[", "v", "]", ":", "visitV", "[...
extend alternating tree from free vertex u. visitU, visitV marks all vertices covered by the tree.
[ "extend", "alternating", "tree", "from", "free", "vertex", "u", ".", "visitU", "visitV", "marks", "all", "vertices", "covered", "by", "the", "tree", "." ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/bipartite_vertex_cover.py#L10-L19
train
208,745
jilljenn/tryalgo
tryalgo/bipartite_vertex_cover.py
bipartite_vertex_cover
def bipartite_vertex_cover(bigraph): """Bipartite minimum vertex cover by Koenig's theorem :param bigraph: adjacency list, index = vertex in U, value = neighbor list in V :assumption: U = V = {0, 1, 2, ..., n - 1} for n = len(bigraph) :returns: boolean table for U, boolean table for V :comment: selected vertices form a minimum vertex cover, i.e. every edge is adjacent to at least one selected vertex and number of selected vertices is minimum :complexity: `O(|V|*|E|)` """ V = range(len(bigraph)) matchV = max_bipartite_matching(bigraph) matchU = [None for u in V] for v in V: # -- build the mapping from U to V if matchV[v] is not None: matchU[matchV[v]] = v visitU = [False for u in V] # -- build max alternating forest visitV = [False for v in V] for u in V: if matchU[u] is None: # -- starting with free vertices in U _alternate(u, bigraph, visitU, visitV, matchV) inverse = [not b for b in visitU] return (inverse, visitV)
python
def bipartite_vertex_cover(bigraph): """Bipartite minimum vertex cover by Koenig's theorem :param bigraph: adjacency list, index = vertex in U, value = neighbor list in V :assumption: U = V = {0, 1, 2, ..., n - 1} for n = len(bigraph) :returns: boolean table for U, boolean table for V :comment: selected vertices form a minimum vertex cover, i.e. every edge is adjacent to at least one selected vertex and number of selected vertices is minimum :complexity: `O(|V|*|E|)` """ V = range(len(bigraph)) matchV = max_bipartite_matching(bigraph) matchU = [None for u in V] for v in V: # -- build the mapping from U to V if matchV[v] is not None: matchU[matchV[v]] = v visitU = [False for u in V] # -- build max alternating forest visitV = [False for v in V] for u in V: if matchU[u] is None: # -- starting with free vertices in U _alternate(u, bigraph, visitU, visitV, matchV) inverse = [not b for b in visitU] return (inverse, visitV)
[ "def", "bipartite_vertex_cover", "(", "bigraph", ")", ":", "V", "=", "range", "(", "len", "(", "bigraph", ")", ")", "matchV", "=", "max_bipartite_matching", "(", "bigraph", ")", "matchU", "=", "[", "None", "for", "u", "in", "V", "]", "for", "v", "in", ...
Bipartite minimum vertex cover by Koenig's theorem :param bigraph: adjacency list, index = vertex in U, value = neighbor list in V :assumption: U = V = {0, 1, 2, ..., n - 1} for n = len(bigraph) :returns: boolean table for U, boolean table for V :comment: selected vertices form a minimum vertex cover, i.e. every edge is adjacent to at least one selected vertex and number of selected vertices is minimum :complexity: `O(|V|*|E|)`
[ "Bipartite", "minimum", "vertex", "cover", "by", "Koenig", "s", "theorem" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/bipartite_vertex_cover.py#L22-L46
train
208,746
jilljenn/tryalgo
tryalgo/union_rectangles.py
union_rectangles
def union_rectangles(R): """Area of union of rectangles :param R: list of rectangles defined by (x1, y1, x2, y2) where (x1, y1) is top left corner and (x2, y2) bottom right corner :returns: area :complexity: :math:`O(n^2)` """ if R == []: return 0 X = [] Y = [] for j in range(len(R)): (x1, y1, x2, y2) = R[j] assert x1 <= x2 and y1 <= y2 X.append(x1) X.append(x2) Y.append((y1, +1, j)) # generate events Y.append((y2, -1, j)) X.sort() Y.sort() X2i = {X[i]: i for i in range(len(X))} L = [X[i + 1] - X[i] for i in range(len(X) - 1)] C = Cover_query(L) area = 0 last = 0 for (y, delta, j) in Y: area += (y - last) * C.cover() last = y (x1, y1, x2, y2) = R[j] i = X2i[x1] k = X2i[x2] C.change(i, k, delta) return area
python
def union_rectangles(R): """Area of union of rectangles :param R: list of rectangles defined by (x1, y1, x2, y2) where (x1, y1) is top left corner and (x2, y2) bottom right corner :returns: area :complexity: :math:`O(n^2)` """ if R == []: return 0 X = [] Y = [] for j in range(len(R)): (x1, y1, x2, y2) = R[j] assert x1 <= x2 and y1 <= y2 X.append(x1) X.append(x2) Y.append((y1, +1, j)) # generate events Y.append((y2, -1, j)) X.sort() Y.sort() X2i = {X[i]: i for i in range(len(X))} L = [X[i + 1] - X[i] for i in range(len(X) - 1)] C = Cover_query(L) area = 0 last = 0 for (y, delta, j) in Y: area += (y - last) * C.cover() last = y (x1, y1, x2, y2) = R[j] i = X2i[x1] k = X2i[x2] C.change(i, k, delta) return area
[ "def", "union_rectangles", "(", "R", ")", ":", "if", "R", "==", "[", "]", ":", "return", "0", "X", "=", "[", "]", "Y", "=", "[", "]", "for", "j", "in", "range", "(", "len", "(", "R", ")", ")", ":", "(", "x1", ",", "y1", ",", "x2", ",", ...
Area of union of rectangles :param R: list of rectangles defined by (x1, y1, x2, y2) where (x1, y1) is top left corner and (x2, y2) bottom right corner :returns: area :complexity: :math:`O(n^2)`
[ "Area", "of", "union", "of", "rectangles" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/union_rectangles.py#L59-L92
train
208,747
jilljenn/tryalgo
tryalgo/horn_sat.py
read
def read(filename): """ reads a Horn SAT formula from a text file :file format: # comment A # clause with unique positive literal :- A # clause with unique negative literal A :- B, C, D # clause where A is positive and B,C,D negative # variables are strings without spaces """ formula = [] for line in open(filename, 'r'): line = line.strip() if line[0] == "#": continue lit = line.split(":-") if len(lit) == 1: posvar = lit[0] negvars = [] else: assert len(lit) == 2 posvar = lit[0].strip() if posvar == '': posvar = None negvars = lit[1].split(',') for i in range(len(negvars)): negvars[i] = negvars[i].strip() formula.append((posvar, negvars)) return formula
python
def read(filename): """ reads a Horn SAT formula from a text file :file format: # comment A # clause with unique positive literal :- A # clause with unique negative literal A :- B, C, D # clause where A is positive and B,C,D negative # variables are strings without spaces """ formula = [] for line in open(filename, 'r'): line = line.strip() if line[0] == "#": continue lit = line.split(":-") if len(lit) == 1: posvar = lit[0] negvars = [] else: assert len(lit) == 2 posvar = lit[0].strip() if posvar == '': posvar = None negvars = lit[1].split(',') for i in range(len(negvars)): negvars[i] = negvars[i].strip() formula.append((posvar, negvars)) return formula
[ "def", "read", "(", "filename", ")", ":", "formula", "=", "[", "]", "for", "line", "in", "open", "(", "filename", ",", "'r'", ")", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "line", "[", "0", "]", "==", "\"#\"", ":", "continue", "l...
reads a Horn SAT formula from a text file :file format: # comment A # clause with unique positive literal :- A # clause with unique negative literal A :- B, C, D # clause where A is positive and B,C,D negative # variables are strings without spaces
[ "reads", "a", "Horn", "SAT", "formula", "from", "a", "text", "file" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/horn_sat.py#L24-L52
train
208,748
jilljenn/tryalgo
tryalgo/horn_sat.py
horn_sat
def horn_sat(formula): """ Solving a HORN Sat formula :param formula: list of couple(posvar, negvars). negvars is a list of the negative variables and can be empty. posvar is the positive variable and can be None. Variables can be any hashable objects, as integers or strings for example. :returns: None if formula is not satisfiable, else a minimal set of variables that have to be set to true in order to satisfy the formula. :complexity: linear """ # --- construct data structures CLAUSES = range(len(formula)) score = [0 for c in CLAUSES] # number of negative vars that are not yet in solution posvar_in_clause = [None for c in CLAUSES] # the unique positive variable of a clause (if any) clauses_with_negvar = defaultdict(set) # all clauses where a variable appears negatively for c in CLAUSES: posvar, negvars = formula[c] score[c] = len(set(negvars)) # do not count twice repeated negative variables posvar_in_clause[c] = posvar for v in negvars: clauses_with_negvar[v].add(c) pool = [set() for s in range(max(score) + 1)] # create the pool for c in CLAUSES: pool[score[c]].add(c) # pool[s] = set of clauses with score s # --- solve Horn SAT formula solution = set() # contains all variables set to True while pool[0]: curr = pool[0].pop() # arbitrary zero score clause v = posvar_in_clause[curr] if v == None: # formula is not satisfiable return None if v in solution or curr in clauses_with_negvar[v]: continue # clause is already satisfied solution.add(v) for c in clauses_with_negvar[v]: # update score pool[score[c]].remove(c) score[c] -= 1 pool[score[c]].add(c) # change c to lower score in pool return solution
python
def horn_sat(formula): """ Solving a HORN Sat formula :param formula: list of couple(posvar, negvars). negvars is a list of the negative variables and can be empty. posvar is the positive variable and can be None. Variables can be any hashable objects, as integers or strings for example. :returns: None if formula is not satisfiable, else a minimal set of variables that have to be set to true in order to satisfy the formula. :complexity: linear """ # --- construct data structures CLAUSES = range(len(formula)) score = [0 for c in CLAUSES] # number of negative vars that are not yet in solution posvar_in_clause = [None for c in CLAUSES] # the unique positive variable of a clause (if any) clauses_with_negvar = defaultdict(set) # all clauses where a variable appears negatively for c in CLAUSES: posvar, negvars = formula[c] score[c] = len(set(negvars)) # do not count twice repeated negative variables posvar_in_clause[c] = posvar for v in negvars: clauses_with_negvar[v].add(c) pool = [set() for s in range(max(score) + 1)] # create the pool for c in CLAUSES: pool[score[c]].add(c) # pool[s] = set of clauses with score s # --- solve Horn SAT formula solution = set() # contains all variables set to True while pool[0]: curr = pool[0].pop() # arbitrary zero score clause v = posvar_in_clause[curr] if v == None: # formula is not satisfiable return None if v in solution or curr in clauses_with_negvar[v]: continue # clause is already satisfied solution.add(v) for c in clauses_with_negvar[v]: # update score pool[score[c]].remove(c) score[c] -= 1 pool[score[c]].add(c) # change c to lower score in pool return solution
[ "def", "horn_sat", "(", "formula", ")", ":", "# --- construct data structures", "CLAUSES", "=", "range", "(", "len", "(", "formula", ")", ")", "score", "=", "[", "0", "for", "c", "in", "CLAUSES", "]", "# number of negative vars that are not yet in solution", "posv...
Solving a HORN Sat formula :param formula: list of couple(posvar, negvars). negvars is a list of the negative variables and can be empty. posvar is the positive variable and can be None. Variables can be any hashable objects, as integers or strings for example. :returns: None if formula is not satisfiable, else a minimal set of variables that have to be set to true in order to satisfy the formula. :complexity: linear
[ "Solving", "a", "HORN", "Sat", "formula" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/horn_sat.py#L55-L96
train
208,749
jilljenn/tryalgo
tryalgo/dinic.py
dinic
def dinic(graph, capacity, source, target): """Maximum flow by Dinic :param graph: directed graph in listlist or listdict format :param capacity: in matrix format or same listdict graph :param int source: vertex :param int target: vertex :returns: skew symmetric flow matrix, flow value :complexity: :math:`O(|V|^2 |E|)` """ assert source != target add_reverse_arcs(graph, capacity) Q = deque() total = 0 n = len(graph) flow = [[0] * n for u in range(n)] # flow initially empty while True: # repeat while we can increase Q.appendleft(source) lev = [None] * n # build levels, None = inaccessible lev[source] = 0 # by BFS while Q: u = Q.pop() for v in graph[u]: if lev[v] is None and capacity[u][v] > flow[u][v]: lev[v] = lev[u] + 1 Q.appendleft(v) if lev[target] is None: # stop if sink is not reachable return flow, total up_bound = sum(capacity[source][v] for v in graph[source]) - total total += _dinic_step(graph, capacity, lev, flow, source, target, up_bound)
python
def dinic(graph, capacity, source, target): """Maximum flow by Dinic :param graph: directed graph in listlist or listdict format :param capacity: in matrix format or same listdict graph :param int source: vertex :param int target: vertex :returns: skew symmetric flow matrix, flow value :complexity: :math:`O(|V|^2 |E|)` """ assert source != target add_reverse_arcs(graph, capacity) Q = deque() total = 0 n = len(graph) flow = [[0] * n for u in range(n)] # flow initially empty while True: # repeat while we can increase Q.appendleft(source) lev = [None] * n # build levels, None = inaccessible lev[source] = 0 # by BFS while Q: u = Q.pop() for v in graph[u]: if lev[v] is None and capacity[u][v] > flow[u][v]: lev[v] = lev[u] + 1 Q.appendleft(v) if lev[target] is None: # stop if sink is not reachable return flow, total up_bound = sum(capacity[source][v] for v in graph[source]) - total total += _dinic_step(graph, capacity, lev, flow, source, target, up_bound)
[ "def", "dinic", "(", "graph", ",", "capacity", ",", "source", ",", "target", ")", ":", "assert", "source", "!=", "target", "add_reverse_arcs", "(", "graph", ",", "capacity", ")", "Q", "=", "deque", "(", ")", "total", "=", "0", "n", "=", "len", "(", ...
Maximum flow by Dinic :param graph: directed graph in listlist or listdict format :param capacity: in matrix format or same listdict graph :param int source: vertex :param int target: vertex :returns: skew symmetric flow matrix, flow value :complexity: :math:`O(|V|^2 |E|)`
[ "Maximum", "flow", "by", "Dinic" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/dinic.py#L16-L47
train
208,750
jilljenn/tryalgo
tryalgo/our_heap.py
OurHeap.pop
def pop(self): """Remove and return smallest element""" root = self.heap[1] del self.rank[root] x = self.heap.pop() # remove last leaf if self: # if heap is not empty self.heap[1] = x # put last leaf to root self.rank[x] = 1 self.down(1) # maintain heap order return root
python
def pop(self): """Remove and return smallest element""" root = self.heap[1] del self.rank[root] x = self.heap.pop() # remove last leaf if self: # if heap is not empty self.heap[1] = x # put last leaf to root self.rank[x] = 1 self.down(1) # maintain heap order return root
[ "def", "pop", "(", "self", ")", ":", "root", "=", "self", ".", "heap", "[", "1", "]", "del", "self", ".", "rank", "[", "root", "]", "x", "=", "self", ".", "heap", ".", "pop", "(", ")", "# remove last leaf", "if", "self", ":", "# if heap is not empt...
Remove and return smallest element
[ "Remove", "and", "return", "smallest", "element" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/our_heap.py#L37-L46
train
208,751
jilljenn/tryalgo
tryalgo/our_heap.py
OurHeap.update
def update(self, old, new): """Replace an element in the heap """ i = self.rank[old] # change value at index i del self.rank[old] self.heap[i] = new self.rank[new] = i if old < new: # maintain heap order self.down(i) else: self.up(i)
python
def update(self, old, new): """Replace an element in the heap """ i = self.rank[old] # change value at index i del self.rank[old] self.heap[i] = new self.rank[new] = i if old < new: # maintain heap order self.down(i) else: self.up(i)
[ "def", "update", "(", "self", ",", "old", ",", "new", ")", ":", "i", "=", "self", ".", "rank", "[", "old", "]", "# change value at index i", "del", "self", ".", "rank", "[", "old", "]", "self", ".", "heap", "[", "i", "]", "=", "new", "self", ".",...
Replace an element in the heap
[ "Replace", "an", "element", "in", "the", "heap" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/our_heap.py#L81-L91
train
208,752
jilljenn/tryalgo
tryalgo/kruskal.py
kruskal
def kruskal(graph, weight): """Minimum spanning tree by Kruskal :param graph: undirected graph in listlist or listdict format :param weight: in matrix format or same listdict graph :returns: list of edges of the tree :complexity: ``O(|E|log|E|)`` """ uf = UnionFind(len(graph)) edges = [] for u in range(len(graph)): for v in graph[u]: edges.append((weight[u][v], u, v)) edges.sort() mst = [] for w, u, v in edges: if uf.union(u, v): mst.append((u, v)) return mst
python
def kruskal(graph, weight): """Minimum spanning tree by Kruskal :param graph: undirected graph in listlist or listdict format :param weight: in matrix format or same listdict graph :returns: list of edges of the tree :complexity: ``O(|E|log|E|)`` """ uf = UnionFind(len(graph)) edges = [] for u in range(len(graph)): for v in graph[u]: edges.append((weight[u][v], u, v)) edges.sort() mst = [] for w, u, v in edges: if uf.union(u, v): mst.append((u, v)) return mst
[ "def", "kruskal", "(", "graph", ",", "weight", ")", ":", "uf", "=", "UnionFind", "(", "len", "(", "graph", ")", ")", "edges", "=", "[", "]", "for", "u", "in", "range", "(", "len", "(", "graph", ")", ")", ":", "for", "v", "in", "graph", "[", "...
Minimum spanning tree by Kruskal :param graph: undirected graph in listlist or listdict format :param weight: in matrix format or same listdict graph :returns: list of edges of the tree :complexity: ``O(|E|log|E|)``
[ "Minimum", "spanning", "tree", "by", "Kruskal" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/kruskal.py#L50-L68
train
208,753
jilljenn/tryalgo
tryalgo/kruskal.py
UnionFind.union
def union(self, x, y): """Merges part that contain x and part containing y :returns: False if x, y are already in same part :complexity: O(inverse_ackerman(n)) """ repr_x = self.find(x) repr_y = self.find(y) if repr_x == repr_y: # already in the same component return False if self.rank[repr_x] == self.rank[repr_y]: self.rank[repr_x] += 1 self.up[repr_y] = repr_x elif self.rank[repr_x] > self.rank[repr_y]: self.up[repr_y] = repr_x else: self.up[repr_x] = repr_y return True
python
def union(self, x, y): """Merges part that contain x and part containing y :returns: False if x, y are already in same part :complexity: O(inverse_ackerman(n)) """ repr_x = self.find(x) repr_y = self.find(y) if repr_x == repr_y: # already in the same component return False if self.rank[repr_x] == self.rank[repr_y]: self.rank[repr_x] += 1 self.up[repr_y] = repr_x elif self.rank[repr_x] > self.rank[repr_y]: self.up[repr_y] = repr_x else: self.up[repr_x] = repr_y return True
[ "def", "union", "(", "self", ",", "x", ",", "y", ")", ":", "repr_x", "=", "self", ".", "find", "(", "x", ")", "repr_y", "=", "self", ".", "find", "(", "y", ")", "if", "repr_x", "==", "repr_y", ":", "# already in the same component", "return", "False"...
Merges part that contain x and part containing y :returns: False if x, y are already in same part :complexity: O(inverse_ackerman(n))
[ "Merges", "part", "that", "contain", "x", "and", "part", "containing", "y" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/kruskal.py#L28-L45
train
208,754
jilljenn/tryalgo
tryalgo/partition_refinement.py
DoubleLinkedListItem.insert
def insert(self, anchor): """insert list item before anchor """ self.prec = anchor.prec # point to neighbors self.succ = anchor self.succ.prec = self # make neighbors point to item self.prec.succ = self
python
def insert(self, anchor): """insert list item before anchor """ self.prec = anchor.prec # point to neighbors self.succ = anchor self.succ.prec = self # make neighbors point to item self.prec.succ = self
[ "def", "insert", "(", "self", ",", "anchor", ")", ":", "self", ".", "prec", "=", "anchor", ".", "prec", "# point to neighbors", "self", ".", "succ", "=", "anchor", "self", ".", "succ", ".", "prec", "=", "self", "# make neighbors point to item", "self", "."...
insert list item before anchor
[ "insert", "list", "item", "before", "anchor" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/partition_refinement.py#L31-L37
train
208,755
jilljenn/tryalgo
tryalgo/partition_refinement.py
PartitionClass.append
def append(self, item): """add item to the end of the item list """ if not self.items: # was list empty ? self.items = item # then this is the new head item.insert(self.items)
python
def append(self, item): """add item to the end of the item list """ if not self.items: # was list empty ? self.items = item # then this is the new head item.insert(self.items)
[ "def", "append", "(", "self", ",", "item", ")", ":", "if", "not", "self", ".", "items", ":", "# was list empty ?", "self", ".", "items", "=", "item", "# then this is the new head", "item", ".", "insert", "(", "self", ".", "items", ")" ]
add item to the end of the item list
[ "add", "item", "to", "the", "end", "of", "the", "item", "list" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/partition_refinement.py#L59-L64
train
208,756
jilljenn/tryalgo
tryalgo/partition_refinement.py
PartitionItem.remove
def remove(self): """remove item from its class """ DoubleLinkedListItem.remove(self) # remove from double linked list if self.succ is self: # list was a singleton self.theclass.items = None # class is empty elif self.theclass.items is self: # oups we removed the head self.theclass.items = self.succ
python
def remove(self): """remove item from its class """ DoubleLinkedListItem.remove(self) # remove from double linked list if self.succ is self: # list was a singleton self.theclass.items = None # class is empty elif self.theclass.items is self: # oups we removed the head self.theclass.items = self.succ
[ "def", "remove", "(", "self", ")", ":", "DoubleLinkedListItem", ".", "remove", "(", "self", ")", "# remove from double linked list", "if", "self", ".", "succ", "is", "self", ":", "# list was a singleton", "self", ".", "theclass", ".", "items", "=", "None", "# ...
remove item from its class
[ "remove", "item", "from", "its", "class" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/partition_refinement.py#L77-L84
train
208,757
jilljenn/tryalgo
tryalgo/partition_refinement.py
PartitionRefinement.tolist
def tolist(self): """produce a list representation of the partition """ return [[x.val for x in theclass.items] for theclass in self.classes]
python
def tolist(self): """produce a list representation of the partition """ return [[x.val for x in theclass.items] for theclass in self.classes]
[ "def", "tolist", "(", "self", ")", ":", "return", "[", "[", "x", ".", "val", "for", "x", "in", "theclass", ".", "items", "]", "for", "theclass", "in", "self", ".", "classes", "]" ]
produce a list representation of the partition
[ "produce", "a", "list", "representation", "of", "the", "partition" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/partition_refinement.py#L122-L125
train
208,758
jilljenn/tryalgo
tryalgo/partition_refinement.py
PartitionRefinement.order
def order(self): """Produce a flatten list of the partition, ordered by classes """ return [x.val for theclass in self.classes for x in theclass.items]
python
def order(self): """Produce a flatten list of the partition, ordered by classes """ return [x.val for theclass in self.classes for x in theclass.items]
[ "def", "order", "(", "self", ")", ":", "return", "[", "x", ".", "val", "for", "theclass", "in", "self", ".", "classes", "for", "x", "in", "theclass", ".", "items", "]" ]
Produce a flatten list of the partition, ordered by classes
[ "Produce", "a", "flatten", "list", "of", "the", "partition", "ordered", "by", "classes" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/partition_refinement.py#L127-L130
train
208,759
jilljenn/tryalgo
tryalgo/primes.py
eratosthene
def eratosthene(n): """Prime numbers by sieve of Eratosthene :param n: positive integer :assumes: n > 2 :returns: list of prime numbers <n :complexity: O(n loglog n) """ P = [True] * n answ = [2] for i in range(3, n, 2): if P[i]: answ.append(i) for j in range(2 * i, n, i): P[j] = False return answ
python
def eratosthene(n): """Prime numbers by sieve of Eratosthene :param n: positive integer :assumes: n > 2 :returns: list of prime numbers <n :complexity: O(n loglog n) """ P = [True] * n answ = [2] for i in range(3, n, 2): if P[i]: answ.append(i) for j in range(2 * i, n, i): P[j] = False return answ
[ "def", "eratosthene", "(", "n", ")", ":", "P", "=", "[", "True", "]", "*", "n", "answ", "=", "[", "2", "]", "for", "i", "in", "range", "(", "3", ",", "n", ",", "2", ")", ":", "if", "P", "[", "i", "]", ":", "answ", ".", "append", "(", "i...
Prime numbers by sieve of Eratosthene :param n: positive integer :assumes: n > 2 :returns: list of prime numbers <n :complexity: O(n loglog n)
[ "Prime", "numbers", "by", "sieve", "of", "Eratosthene" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/primes.py#L9-L24
train
208,760
jilljenn/tryalgo
tryalgo/edmonds_karp.py
_augment
def _augment(graph, capacity, flow, source, target): """find a shortest augmenting path """ n = len(graph) A = [0] * n # A[v] = min residual cap. on path source->v augm_path = [None] * n # None = node was not visited yet Q = deque() # BFS Q.append(source) augm_path[source] = source A[source] = float('inf') while Q: u = Q.popleft() for v in graph[u]: cuv = capacity[u][v] residual = cuv - flow[u][v] if residual > 0 and augm_path[v] is None: augm_path[v] = u # store predecessor A[v] = min(A[u], residual) if v == target: break else: Q.append(v) return (augm_path, A[target])
python
def _augment(graph, capacity, flow, source, target): """find a shortest augmenting path """ n = len(graph) A = [0] * n # A[v] = min residual cap. on path source->v augm_path = [None] * n # None = node was not visited yet Q = deque() # BFS Q.append(source) augm_path[source] = source A[source] = float('inf') while Q: u = Q.popleft() for v in graph[u]: cuv = capacity[u][v] residual = cuv - flow[u][v] if residual > 0 and augm_path[v] is None: augm_path[v] = u # store predecessor A[v] = min(A[u], residual) if v == target: break else: Q.append(v) return (augm_path, A[target])
[ "def", "_augment", "(", "graph", ",", "capacity", ",", "flow", ",", "source", ",", "target", ")", ":", "n", "=", "len", "(", "graph", ")", "A", "=", "[", "0", "]", "*", "n", "# A[v] = min residual cap. on path source->v", "augm_path", "=", "[", "None", ...
find a shortest augmenting path
[ "find", "a", "shortest", "augmenting", "path" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/edmonds_karp.py#L11-L33
train
208,761
jilljenn/tryalgo
tryalgo/edmonds_karp.py
edmonds_karp
def edmonds_karp(graph, capacity, source, target): """Maximum flow by Edmonds-Karp :param graph: directed graph in listlist or listdict format :param capacity: in matrix format or same listdict graph :param int source: vertex :param int target: vertex :returns: flow matrix, flow value :complexity: :math:`O(|V|*|E|^2)` """ add_reverse_arcs(graph, capacity) V = range(len(graph)) flow = [[0 for v in V] for u in V] while True: augm_path, delta = _augment(graph, capacity, flow, source, target) if delta == 0: break v = target # go back to source while v != source: u = augm_path[v] # augment flow flow[u][v] += delta flow[v][u] -= delta v = u return (flow, sum(flow[source]))
python
def edmonds_karp(graph, capacity, source, target): """Maximum flow by Edmonds-Karp :param graph: directed graph in listlist or listdict format :param capacity: in matrix format or same listdict graph :param int source: vertex :param int target: vertex :returns: flow matrix, flow value :complexity: :math:`O(|V|*|E|^2)` """ add_reverse_arcs(graph, capacity) V = range(len(graph)) flow = [[0 for v in V] for u in V] while True: augm_path, delta = _augment(graph, capacity, flow, source, target) if delta == 0: break v = target # go back to source while v != source: u = augm_path[v] # augment flow flow[u][v] += delta flow[v][u] -= delta v = u return (flow, sum(flow[source]))
[ "def", "edmonds_karp", "(", "graph", ",", "capacity", ",", "source", ",", "target", ")", ":", "add_reverse_arcs", "(", "graph", ",", "capacity", ")", "V", "=", "range", "(", "len", "(", "graph", ")", ")", "flow", "=", "[", "[", "0", "for", "v", "in...
Maximum flow by Edmonds-Karp :param graph: directed graph in listlist or listdict format :param capacity: in matrix format or same listdict graph :param int source: vertex :param int target: vertex :returns: flow matrix, flow value :complexity: :math:`O(|V|*|E|^2)`
[ "Maximum", "flow", "by", "Edmonds", "-", "Karp" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/edmonds_karp.py#L36-L59
train
208,762
jilljenn/tryalgo
tryalgo/gauss_jordan.py
gauss_jordan
def gauss_jordan(A, x, b): """Linear equation system Ax=b by Gauss-Jordan :param A: n by m matrix :param x: table of size n :param b: table of size m :modifies: x will contain solution if any :returns int: 0 if no solution, 1 if solution unique, 2 otherwise :complexity: :math:`O(n^2m)` """ n = len(x) m = len(b) assert len(A) == m and len(A[0]) == n S = [] # put linear system in a single matrix S for i in range(m): S.append(A[i][:] + [b[i]]) S.append(list(range(n))) # indices in x k = diagonalize(S, n, m) if k < m: for i in range(k, m): if not is_zero(S[i][n]): return GJ_ZERO_SOLUTIONS for j in range(k): x[S[m][j]] = S[j][n] if k < n: for j in range(k, n): x[S[m][j]] = 0 return GJ_SEVERAL_SOLUTIONS return GJ_SINGLE_SOLUTION
python
def gauss_jordan(A, x, b): """Linear equation system Ax=b by Gauss-Jordan :param A: n by m matrix :param x: table of size n :param b: table of size m :modifies: x will contain solution if any :returns int: 0 if no solution, 1 if solution unique, 2 otherwise :complexity: :math:`O(n^2m)` """ n = len(x) m = len(b) assert len(A) == m and len(A[0]) == n S = [] # put linear system in a single matrix S for i in range(m): S.append(A[i][:] + [b[i]]) S.append(list(range(n))) # indices in x k = diagonalize(S, n, m) if k < m: for i in range(k, m): if not is_zero(S[i][n]): return GJ_ZERO_SOLUTIONS for j in range(k): x[S[m][j]] = S[j][n] if k < n: for j in range(k, n): x[S[m][j]] = 0 return GJ_SEVERAL_SOLUTIONS return GJ_SINGLE_SOLUTION
[ "def", "gauss_jordan", "(", "A", ",", "x", ",", "b", ")", ":", "n", "=", "len", "(", "x", ")", "m", "=", "len", "(", "b", ")", "assert", "len", "(", "A", ")", "==", "m", "and", "len", "(", "A", "[", "0", "]", ")", "==", "n", "S", "=", ...
Linear equation system Ax=b by Gauss-Jordan :param A: n by m matrix :param x: table of size n :param b: table of size m :modifies: x will contain solution if any :returns int: 0 if no solution, 1 if solution unique, 2 otherwise :complexity: :math:`O(n^2m)`
[ "Linear", "equation", "system", "Ax", "=", "b", "by", "Gauss", "-", "Jordan" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/gauss_jordan.py#L23-L54
train
208,763
jilljenn/tryalgo
tryalgo/rabin_karp.py
rabin_karp_matching
def rabin_karp_matching(s, t): """Find a substring by Rabin-Karp :param s: the haystack string :param t: the needle string :returns: index i such that s[i: i + len(t)] == t, or -1 :complexity: O(len(s) + len(t)) in expected time, and O(len(s) * len(t)) in worst case """ hash_s = 0 hash_t = 0 len_s = len(s) len_t = len(t) last_pos = pow(DOMAIN, len_t - 1) % PRIME if len_s < len_t: return -1 for i in range(len_t): # preprocessing hash_s = (DOMAIN * hash_s + ord(s[i])) % PRIME hash_t = (DOMAIN * hash_t + ord(t[i])) % PRIME for i in range(len_s - len_t + 1): if hash_s == hash_t: # check character by character if matches(s, t, i, 0, len_t): return i if i < len_s - len_t: hash_s = roll_hash(hash_s, ord(s[i]), ord(s[i + len_t]), last_pos) return -1
python
def rabin_karp_matching(s, t): """Find a substring by Rabin-Karp :param s: the haystack string :param t: the needle string :returns: index i such that s[i: i + len(t)] == t, or -1 :complexity: O(len(s) + len(t)) in expected time, and O(len(s) * len(t)) in worst case """ hash_s = 0 hash_t = 0 len_s = len(s) len_t = len(t) last_pos = pow(DOMAIN, len_t - 1) % PRIME if len_s < len_t: return -1 for i in range(len_t): # preprocessing hash_s = (DOMAIN * hash_s + ord(s[i])) % PRIME hash_t = (DOMAIN * hash_t + ord(t[i])) % PRIME for i in range(len_s - len_t + 1): if hash_s == hash_t: # check character by character if matches(s, t, i, 0, len_t): return i if i < len_s - len_t: hash_s = roll_hash(hash_s, ord(s[i]), ord(s[i + len_t]), last_pos) return -1
[ "def", "rabin_karp_matching", "(", "s", ",", "t", ")", ":", "hash_s", "=", "0", "hash_t", "=", "0", "len_s", "=", "len", "(", "s", ")", "len_t", "=", "len", "(", "t", ")", "last_pos", "=", "pow", "(", "DOMAIN", ",", "len_t", "-", "1", ")", "%",...
Find a substring by Rabin-Karp :param s: the haystack string :param t: the needle string :returns: index i such that s[i: i + len(t)] == t, or -1 :complexity: O(len(s) + len(t)) in expected time, and O(len(s) * len(t)) in worst case
[ "Find", "a", "substring", "by", "Rabin", "-", "Karp" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/rabin_karp.py#L30-L57
train
208,764
jilljenn/tryalgo
tryalgo/rabin_karp.py
rabin_karp_factor
def rabin_karp_factor(s, t, k): """Find a common factor by Rabin-Karp :param string s: haystack :param string t: needle :param int k: factor length :returns: (i, j) such that s[i:i + k] == t[j:j + k] or None. In case of tie, lexicographical minimum (i, j) is returned :complexity: O(len(s) + len(t)) in expected time, and O(len(s) + len(t) * k) in worst case """ last_pos = pow(DOMAIN, k - 1) % PRIME pos = {} assert k > 0 if len(s) < k or len(t) < k: return None hash_t = 0 for j in range(k): # store hashing values hash_t = (DOMAIN * hash_t + ord(t[j])) % PRIME for j in range(len(t) - k + 1): if hash_t in pos: pos[hash_t].append(j) else: pos[hash_t] = [j] if j < len(t) - k: hash_t = roll_hash(hash_t, ord(t[j]), ord(t[j + k]), last_pos) hash_s = 0 for i in range(k): # preprocessing hash_s = (DOMAIN * hash_s + ord(s[i])) % PRIME for i in range(len(s) - k + 1): if hash_s in pos: # is this signature in s? for j in pos[hash_s]: if matches(s, t, i, j, k): return (i, j) if i < len(s) - k: hash_s = roll_hash(hash_s, ord(s[i]), ord(s[i + k]), last_pos) return None
python
def rabin_karp_factor(s, t, k): """Find a common factor by Rabin-Karp :param string s: haystack :param string t: needle :param int k: factor length :returns: (i, j) such that s[i:i + k] == t[j:j + k] or None. In case of tie, lexicographical minimum (i, j) is returned :complexity: O(len(s) + len(t)) in expected time, and O(len(s) + len(t) * k) in worst case """ last_pos = pow(DOMAIN, k - 1) % PRIME pos = {} assert k > 0 if len(s) < k or len(t) < k: return None hash_t = 0 for j in range(k): # store hashing values hash_t = (DOMAIN * hash_t + ord(t[j])) % PRIME for j in range(len(t) - k + 1): if hash_t in pos: pos[hash_t].append(j) else: pos[hash_t] = [j] if j < len(t) - k: hash_t = roll_hash(hash_t, ord(t[j]), ord(t[j + k]), last_pos) hash_s = 0 for i in range(k): # preprocessing hash_s = (DOMAIN * hash_s + ord(s[i])) % PRIME for i in range(len(s) - k + 1): if hash_s in pos: # is this signature in s? for j in pos[hash_s]: if matches(s, t, i, j, k): return (i, j) if i < len(s) - k: hash_s = roll_hash(hash_s, ord(s[i]), ord(s[i + k]), last_pos) return None
[ "def", "rabin_karp_factor", "(", "s", ",", "t", ",", "k", ")", ":", "last_pos", "=", "pow", "(", "DOMAIN", ",", "k", "-", "1", ")", "%", "PRIME", "pos", "=", "{", "}", "assert", "k", ">", "0", "if", "len", "(", "s", ")", "<", "k", "or", "le...
Find a common factor by Rabin-Karp :param string s: haystack :param string t: needle :param int k: factor length :returns: (i, j) such that s[i:i + k] == t[j:j + k] or None. In case of tie, lexicographical minimum (i, j) is returned :complexity: O(len(s) + len(t)) in expected time, and O(len(s) + len(t) * k) in worst case
[ "Find", "a", "common", "factor", "by", "Rabin", "-", "Karp" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/rabin_karp.py#L62-L98
train
208,765
jilljenn/tryalgo
tryalgo/rectangles_from_histogram.py
rectangles_from_histogram
def rectangles_from_histogram(H): """Largest Rectangular Area in a Histogram :param H: histogram table :returns: area, left, height, right, rect. is [0, height] * [left, right) :complexity: linear """ best = (float('-inf'), 0, 0, 0) S = [] H2 = H + [float('-inf')] # extra element to empty the queue for right in range(len(H2)): x = H2[right] left = right while len(S) > 0 and S[-1][1] >= x: left, height = S.pop() # first element is area of candidate rect = (height * (right - left), left, height, right) if rect > best: best = rect S.append((left, x)) return best
python
def rectangles_from_histogram(H): """Largest Rectangular Area in a Histogram :param H: histogram table :returns: area, left, height, right, rect. is [0, height] * [left, right) :complexity: linear """ best = (float('-inf'), 0, 0, 0) S = [] H2 = H + [float('-inf')] # extra element to empty the queue for right in range(len(H2)): x = H2[right] left = right while len(S) > 0 and S[-1][1] >= x: left, height = S.pop() # first element is area of candidate rect = (height * (right - left), left, height, right) if rect > best: best = rect S.append((left, x)) return best
[ "def", "rectangles_from_histogram", "(", "H", ")", ":", "best", "=", "(", "float", "(", "'-inf'", ")", ",", "0", ",", "0", ",", "0", ")", "S", "=", "[", "]", "H2", "=", "H", "+", "[", "float", "(", "'-inf'", ")", "]", "# extra element to empty the ...
Largest Rectangular Area in a Histogram :param H: histogram table :returns: area, left, height, right, rect. is [0, height] * [left, right) :complexity: linear
[ "Largest", "Rectangular", "Area", "in", "a", "Histogram" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/rectangles_from_histogram.py#L8-L28
train
208,766
jilljenn/tryalgo
tryalgo/topological_order.py
topological_order_dfs
def topological_order_dfs(graph): """Topological sorting by depth first search :param graph: directed graph in listlist format, cannot be listdict :returns: list of vertices in order :complexity: `O(|V|+|E|)` """ n = len(graph) order = [] times_seen = [-1] * n for start in range(n): if times_seen[start] == -1: times_seen[start] = 0 to_visit = [start] while to_visit: node = to_visit[-1] children = graph[node] if times_seen[node] == len(children): to_visit.pop() order.append(node) else: child = children[times_seen[node]] times_seen[node] += 1 if times_seen[child] == -1: times_seen[child] = 0 to_visit.append(child) return order[::-1]
python
def topological_order_dfs(graph): """Topological sorting by depth first search :param graph: directed graph in listlist format, cannot be listdict :returns: list of vertices in order :complexity: `O(|V|+|E|)` """ n = len(graph) order = [] times_seen = [-1] * n for start in range(n): if times_seen[start] == -1: times_seen[start] = 0 to_visit = [start] while to_visit: node = to_visit[-1] children = graph[node] if times_seen[node] == len(children): to_visit.pop() order.append(node) else: child = children[times_seen[node]] times_seen[node] += 1 if times_seen[child] == -1: times_seen[child] = 0 to_visit.append(child) return order[::-1]
[ "def", "topological_order_dfs", "(", "graph", ")", ":", "n", "=", "len", "(", "graph", ")", "order", "=", "[", "]", "times_seen", "=", "[", "-", "1", "]", "*", "n", "for", "start", "in", "range", "(", "n", ")", ":", "if", "times_seen", "[", "star...
Topological sorting by depth first search :param graph: directed graph in listlist format, cannot be listdict :returns: list of vertices in order :complexity: `O(|V|+|E|)`
[ "Topological", "sorting", "by", "depth", "first", "search" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/topological_order.py#L8-L34
train
208,767
jilljenn/tryalgo
tryalgo/topological_order.py
topological_order
def topological_order(graph): """Topological sorting by maintaining indegree :param graph: directed graph in listlist format, cannot be listdict :returns: list of vertices in order :complexity: `O(|V|+|E|)` """ V = range(len(graph)) indeg = [0 for _ in V] for node in V: # compute indegree for neighbor in graph[node]: indeg[neighbor] += 1 Q = [node for node in V if indeg[node] == 0] order = [] while Q: node = Q.pop() # node without incoming arrows order.append(node) for neighbor in graph[node]: indeg[neighbor] -= 1 if indeg[neighbor] == 0: Q.append(neighbor) return order
python
def topological_order(graph): """Topological sorting by maintaining indegree :param graph: directed graph in listlist format, cannot be listdict :returns: list of vertices in order :complexity: `O(|V|+|E|)` """ V = range(len(graph)) indeg = [0 for _ in V] for node in V: # compute indegree for neighbor in graph[node]: indeg[neighbor] += 1 Q = [node for node in V if indeg[node] == 0] order = [] while Q: node = Q.pop() # node without incoming arrows order.append(node) for neighbor in graph[node]: indeg[neighbor] -= 1 if indeg[neighbor] == 0: Q.append(neighbor) return order
[ "def", "topological_order", "(", "graph", ")", ":", "V", "=", "range", "(", "len", "(", "graph", ")", ")", "indeg", "=", "[", "0", "for", "_", "in", "V", "]", "for", "node", "in", "V", ":", "# compute indegree", "for", "neighbor", "in", "graph", "[...
Topological sorting by maintaining indegree :param graph: directed graph in listlist format, cannot be listdict :returns: list of vertices in order :complexity: `O(|V|+|E|)`
[ "Topological", "sorting", "by", "maintaining", "indegree" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/topological_order.py#L39-L60
train
208,768
jilljenn/tryalgo
tryalgo/skip_list.py
AbstractSkipList.getkth
def getkth(self, k): "starts from 0" if k >= len(self): raise IndexError k += 1 # self has index -1 h = len(self.next) - 1 x = self while k: while x.next[h] is None or x.count[h] > k: h -= 1 k -= x.count[h] x = x.next[h] return x.key
python
def getkth(self, k): "starts from 0" if k >= len(self): raise IndexError k += 1 # self has index -1 h = len(self.next) - 1 x = self while k: while x.next[h] is None or x.count[h] > k: h -= 1 k -= x.count[h] x = x.next[h] return x.key
[ "def", "getkth", "(", "self", ",", "k", ")", ":", "if", "k", ">=", "len", "(", "self", ")", ":", "raise", "IndexError", "k", "+=", "1", "# self has index -1", "h", "=", "len", "(", "self", ".", "next", ")", "-", "1", "x", "=", "self", "while", ...
starts from 0
[ "starts", "from", "0" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/skip_list.py#L55-L67
train
208,769
jilljenn/tryalgo
tryalgo/skip_list.py
SortedSet.pop
def pop(self): """Pops the first element""" try: x = next(iter(self)) self.remove(x) return x except StopIteration: raise KeyError('pop from an empty set')
python
def pop(self): """Pops the first element""" try: x = next(iter(self)) self.remove(x) return x except StopIteration: raise KeyError('pop from an empty set')
[ "def", "pop", "(", "self", ")", ":", "try", ":", "x", "=", "next", "(", "iter", "(", "self", ")", ")", "self", ".", "remove", "(", "x", ")", "return", "x", "except", "StopIteration", ":", "raise", "KeyError", "(", "'pop from an empty set'", ")" ]
Pops the first element
[ "Pops", "the", "first", "element" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/skip_list.py#L153-L160
train
208,770
jilljenn/tryalgo
tryalgo/merge_ordered_lists.py
merge
def merge(x, y): """Merge two ordered lists :param x: :param y: x,y are non decreasing ordered lists :returns: union of x and y in order :complexity: linear """ z = [] i = 0 j = 0 while i < len(x) or j < len(y): if j == len(y) or i < len(x) and x[i] <= y[j]: # priority on x z.append(x[i]) i += 1 else: z.append(y[j]) j += 1 return z
python
def merge(x, y): """Merge two ordered lists :param x: :param y: x,y are non decreasing ordered lists :returns: union of x and y in order :complexity: linear """ z = [] i = 0 j = 0 while i < len(x) or j < len(y): if j == len(y) or i < len(x) and x[i] <= y[j]: # priority on x z.append(x[i]) i += 1 else: z.append(y[j]) j += 1 return z
[ "def", "merge", "(", "x", ",", "y", ")", ":", "z", "=", "[", "]", "i", "=", "0", "j", "=", "0", "while", "i", "<", "len", "(", "x", ")", "or", "j", "<", "len", "(", "y", ")", ":", "if", "j", "==", "len", "(", "y", ")", "or", "i", "<...
Merge two ordered lists :param x: :param y: x,y are non decreasing ordered lists :returns: union of x and y in order :complexity: linear
[ "Merge", "two", "ordered", "lists" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/merge_ordered_lists.py#L8-L26
train
208,771
jilljenn/tryalgo
tryalgo/pq_tree.py
consecutive_ones_property
def consecutive_ones_property(sets, universe=None): """ Check the consecutive ones property. :param list sets: is a list of subsets of the ground set. :param groundset: is the set of all elements, by default it is the union of the given sets :returns: returns a list of the ordered ground set where every given set is consecutive, or None if there is no solution. :complexity: O(len(groundset) * len(sets)) :disclaimer: an optimal implementation would have complexity O(len(groundset) + len(sets) + sum(map(len,sets))), and there are more recent easier algorithms for this problem. """ if universe is None: universe = set() for S in sets: universe |= set(S) tree = PQ_tree(universe) try: for S in sets: tree.reduce(S) return tree.border() except IsNotC1P: return None
python
def consecutive_ones_property(sets, universe=None): """ Check the consecutive ones property. :param list sets: is a list of subsets of the ground set. :param groundset: is the set of all elements, by default it is the union of the given sets :returns: returns a list of the ordered ground set where every given set is consecutive, or None if there is no solution. :complexity: O(len(groundset) * len(sets)) :disclaimer: an optimal implementation would have complexity O(len(groundset) + len(sets) + sum(map(len,sets))), and there are more recent easier algorithms for this problem. """ if universe is None: universe = set() for S in sets: universe |= set(S) tree = PQ_tree(universe) try: for S in sets: tree.reduce(S) return tree.border() except IsNotC1P: return None
[ "def", "consecutive_ones_property", "(", "sets", ",", "universe", "=", "None", ")", ":", "if", "universe", "is", "None", ":", "universe", "=", "set", "(", ")", "for", "S", "in", "sets", ":", "universe", "|=", "set", "(", "S", ")", "tree", "=", "PQ_tr...
Check the consecutive ones property. :param list sets: is a list of subsets of the ground set. :param groundset: is the set of all elements, by default it is the union of the given sets :returns: returns a list of the ordered ground set where every given set is consecutive, or None if there is no solution. :complexity: O(len(groundset) * len(sets)) :disclaimer: an optimal implementation would have complexity O(len(groundset) + len(sets) + sum(map(len,sets))), and there are more recent easier algorithms for this problem.
[ "Check", "the", "consecutive", "ones", "property", "." ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/pq_tree.py#L247-L271
train
208,772
jilljenn/tryalgo
tryalgo/pq_tree.py
PQ_node.add
def add(self, node): """Add one node as descendant """ self.sons.append(node) node.parent = self
python
def add(self, node): """Add one node as descendant """ self.sons.append(node) node.parent = self
[ "def", "add", "(", "self", ",", "node", ")", ":", "self", ".", "sons", ".", "append", "(", "node", ")", "node", ".", "parent", "=", "self" ]
Add one node as descendant
[ "Add", "one", "node", "as", "descendant" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/pq_tree.py#L73-L77
train
208,773
jilljenn/tryalgo
tryalgo/pq_tree.py
PQ_node.add_group
def add_group(self, L): """Add elements of L as descendants of the node. If there are several elements in L, group them in a P-node first """ if len(L) == 1: self.add(L[0]) elif len(L) >= 2: x = PQ_node(P_shape) x.add_all(L) self.add(x)
python
def add_group(self, L): """Add elements of L as descendants of the node. If there are several elements in L, group them in a P-node first """ if len(L) == 1: self.add(L[0]) elif len(L) >= 2: x = PQ_node(P_shape) x.add_all(L) self.add(x)
[ "def", "add_group", "(", "self", ",", "L", ")", ":", "if", "len", "(", "L", ")", "==", "1", ":", "self", ".", "add", "(", "L", "[", "0", "]", ")", "elif", "len", "(", "L", ")", ">=", "2", ":", "x", "=", "PQ_node", "(", "P_shape", ")", "x"...
Add elements of L as descendants of the node. If there are several elements in L, group them in a P-node first
[ "Add", "elements", "of", "L", "as", "descendants", "of", "the", "node", ".", "If", "there", "are", "several", "elements", "in", "L", "group", "them", "in", "a", "P", "-", "node", "first" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/pq_tree.py#L83-L92
train
208,774
jilljenn/tryalgo
tryalgo/pq_tree.py
PQ_node.border
def border(self, L): """Append to L the border of the subtree. """ if self.shape == L_shape: L.append(self.value) else: for x in self.sons: x.border(L)
python
def border(self, L): """Append to L the border of the subtree. """ if self.shape == L_shape: L.append(self.value) else: for x in self.sons: x.border(L)
[ "def", "border", "(", "self", ",", "L", ")", ":", "if", "self", ".", "shape", "==", "L_shape", ":", "L", ".", "append", "(", "self", ".", "value", ")", "else", ":", "for", "x", "in", "self", ".", "sons", ":", "x", ".", "border", "(", "L", ")"...
Append to L the border of the subtree.
[ "Append", "to", "L", "the", "border", "of", "the", "subtree", "." ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/pq_tree.py#L95-L102
train
208,775
jilljenn/tryalgo
tryalgo/knuth_morris_pratt.py
maximum_border_length
def maximum_border_length(w): """Maximum string borders by Knuth-Morris-Pratt :param w: string :returns: table f such that f[i] is the longest border length of w[:i + 1] :complexity: linear """ n = len(w) f = [0] * n # init f[0] = 0 k = 0 # current longest border length for i in range(1, n): # compute f[i] while w[k] != w[i] and k > 0: k = f[k - 1] # try shorter lengths if w[k] == w[i]: # last caracters match k += 1 # we can increment the border length f[i] = k # we found the maximal border of w[:i + 1] return f
python
def maximum_border_length(w): """Maximum string borders by Knuth-Morris-Pratt :param w: string :returns: table f such that f[i] is the longest border length of w[:i + 1] :complexity: linear """ n = len(w) f = [0] * n # init f[0] = 0 k = 0 # current longest border length for i in range(1, n): # compute f[i] while w[k] != w[i] and k > 0: k = f[k - 1] # try shorter lengths if w[k] == w[i]: # last caracters match k += 1 # we can increment the border length f[i] = k # we found the maximal border of w[:i + 1] return f
[ "def", "maximum_border_length", "(", "w", ")", ":", "n", "=", "len", "(", "w", ")", "f", "=", "[", "0", "]", "*", "n", "# init f[0] = 0", "k", "=", "0", "# current longest border length", "for", "i", "in", "range", "(", "1", ",", "n", ")", ":", "# ...
Maximum string borders by Knuth-Morris-Pratt :param w: string :returns: table f such that f[i] is the longest border length of w[:i + 1] :complexity: linear
[ "Maximum", "string", "borders", "by", "Knuth", "-", "Morris", "-", "Pratt" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/knuth_morris_pratt.py#L10-L26
train
208,776
jilljenn/tryalgo
tryalgo/knuth_morris_pratt.py
knuth_morris_pratt
def knuth_morris_pratt(s, t): """Find a substring by Knuth-Morris-Pratt :param s: the haystack string :param t: the needle string :returns: index i such that s[i: i + len(t)] == t, or -1 :complexity: O(len(s) + len(t)) """ sep = '\x00' # special unused character assert sep not in t and sep not in s f = maximum_border_length(t + sep + s) n = len(t) for i, fi in enumerate(f): if fi == n: # found a border of the length of t return i - 2 * n # beginning of the border in s return -1
python
def knuth_morris_pratt(s, t): """Find a substring by Knuth-Morris-Pratt :param s: the haystack string :param t: the needle string :returns: index i such that s[i: i + len(t)] == t, or -1 :complexity: O(len(s) + len(t)) """ sep = '\x00' # special unused character assert sep not in t and sep not in s f = maximum_border_length(t + sep + s) n = len(t) for i, fi in enumerate(f): if fi == n: # found a border of the length of t return i - 2 * n # beginning of the border in s return -1
[ "def", "knuth_morris_pratt", "(", "s", ",", "t", ")", ":", "sep", "=", "'\\x00'", "# special unused character", "assert", "sep", "not", "in", "t", "and", "sep", "not", "in", "s", "f", "=", "maximum_border_length", "(", "t", "+", "sep", "+", "s", ")", "...
Find a substring by Knuth-Morris-Pratt :param s: the haystack string :param t: the needle string :returns: index i such that s[i: i + len(t)] == t, or -1 :complexity: O(len(s) + len(t))
[ "Find", "a", "substring", "by", "Knuth", "-", "Morris", "-", "Pratt" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/knuth_morris_pratt.py#L31-L46
train
208,777
jilljenn/tryalgo
tryalgo/knuth_morris_pratt.py
powerstring_by_border
def powerstring_by_border(u): """Power string by Knuth-Morris-Pratt :param x: string :returns: largest k such that there is a string y with x = y^k :complexity: O(len(x)) """ f = maximum_border_length(u) n = len(u) if n % (n - f[-1]) == 0: # does the alignment shift divide n ? return n // (n - f[-1]) # we found a power decomposition return 1
python
def powerstring_by_border(u): """Power string by Knuth-Morris-Pratt :param x: string :returns: largest k such that there is a string y with x = y^k :complexity: O(len(x)) """ f = maximum_border_length(u) n = len(u) if n % (n - f[-1]) == 0: # does the alignment shift divide n ? return n // (n - f[-1]) # we found a power decomposition return 1
[ "def", "powerstring_by_border", "(", "u", ")", ":", "f", "=", "maximum_border_length", "(", "u", ")", "n", "=", "len", "(", "u", ")", "if", "n", "%", "(", "n", "-", "f", "[", "-", "1", "]", ")", "==", "0", ":", "# does the alignment shift divide n ?"...
Power string by Knuth-Morris-Pratt :param x: string :returns: largest k such that there is a string y with x = y^k :complexity: O(len(x))
[ "Power", "string", "by", "Knuth", "-", "Morris", "-", "Pratt" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/knuth_morris_pratt.py#L51-L62
train
208,778
jilljenn/tryalgo
tryalgo/matrix_chain_mult.py
matrix_mult_opt_order
def matrix_mult_opt_order(M): """Matrix chain multiplication optimal order :param M: list of matrices :returns: matrices opt, arg, such that opt[i][j] is the optimal number of operations to compute M[i] * ... * M[j] when done in the order (M[i] * ... * M[k]) * (M[k + 1] * ... * M[j]) for k = arg[i][j] :complexity: :math:`O(n^2)` """ n = len(M) r = [len(Mi) for Mi in M] c = [len(Mi[0]) for Mi in M] opt = [[0 for j in range(n)] for i in range(n)] arg = [[None for j in range(n)] for i in range(n)] for j_i in range(1, n): # loop on i, j of increasing j - i = j_i for i in range(n - j_i): j = i + j_i opt[i][j] = float('inf') for k in range(i, j): alt = opt[i][k] + opt[k + 1][j] + r[i] * c[k] * c[j] if opt[i][j] > alt: opt[i][j] = alt arg[i][j] = k return opt, arg
python
def matrix_mult_opt_order(M): """Matrix chain multiplication optimal order :param M: list of matrices :returns: matrices opt, arg, such that opt[i][j] is the optimal number of operations to compute M[i] * ... * M[j] when done in the order (M[i] * ... * M[k]) * (M[k + 1] * ... * M[j]) for k = arg[i][j] :complexity: :math:`O(n^2)` """ n = len(M) r = [len(Mi) for Mi in M] c = [len(Mi[0]) for Mi in M] opt = [[0 for j in range(n)] for i in range(n)] arg = [[None for j in range(n)] for i in range(n)] for j_i in range(1, n): # loop on i, j of increasing j - i = j_i for i in range(n - j_i): j = i + j_i opt[i][j] = float('inf') for k in range(i, j): alt = opt[i][k] + opt[k + 1][j] + r[i] * c[k] * c[j] if opt[i][j] > alt: opt[i][j] = alt arg[i][j] = k return opt, arg
[ "def", "matrix_mult_opt_order", "(", "M", ")", ":", "n", "=", "len", "(", "M", ")", "r", "=", "[", "len", "(", "Mi", ")", "for", "Mi", "in", "M", "]", "c", "=", "[", "len", "(", "Mi", "[", "0", "]", ")", "for", "Mi", "in", "M", "]", "opt"...
Matrix chain multiplication optimal order :param M: list of matrices :returns: matrices opt, arg, such that opt[i][j] is the optimal number of operations to compute M[i] * ... * M[j] when done in the order (M[i] * ... * M[k]) * (M[k + 1] * ... * M[j]) for k = arg[i][j] :complexity: :math:`O(n^2)`
[ "Matrix", "chain", "multiplication", "optimal", "order" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/matrix_chain_mult.py#L9-L32
train
208,779
jilljenn/tryalgo
tryalgo/matrix_chain_mult.py
matrix_chain_mult
def matrix_chain_mult(M): """Matrix chain multiplication :param M: list of matrices :returns: M[0] * ... * M[-1], computed in time optimal order :complexity: whatever is needed by the multiplications """ opt, arg = matrix_mult_opt_order(M) return _apply_order(M, arg, 0, len(M)-1)
python
def matrix_chain_mult(M): """Matrix chain multiplication :param M: list of matrices :returns: M[0] * ... * M[-1], computed in time optimal order :complexity: whatever is needed by the multiplications """ opt, arg = matrix_mult_opt_order(M) return _apply_order(M, arg, 0, len(M)-1)
[ "def", "matrix_chain_mult", "(", "M", ")", ":", "opt", ",", "arg", "=", "matrix_mult_opt_order", "(", "M", ")", "return", "_apply_order", "(", "M", ",", "arg", ",", "0", ",", "len", "(", "M", ")", "-", "1", ")" ]
Matrix chain multiplication :param M: list of matrices :returns: M[0] * ... * M[-1], computed in time optimal order :complexity: whatever is needed by the multiplications
[ "Matrix", "chain", "multiplication" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/matrix_chain_mult.py#L35-L43
train
208,780
jilljenn/tryalgo
tryalgo/levenshtein.py
levenshtein
def levenshtein(x, y): """Levenshtein edit distance :param x: :param y: strings :returns: distance :complexity: `O(|x|*|y|)` """ n = len(x) m = len(y) # initializing row 0 and column 0 A = [[i + j for j in range(m + 1)] for i in range(n + 1)] for i in range(n): for j in range(m): A[i + 1][j + 1] = min(A[i][j + 1] + 1, # insert A[i + 1][j] + 1, # delete A[i][j] + int(x[i] != y[j])) # subst. return A[n][m]
python
def levenshtein(x, y): """Levenshtein edit distance :param x: :param y: strings :returns: distance :complexity: `O(|x|*|y|)` """ n = len(x) m = len(y) # initializing row 0 and column 0 A = [[i + j for j in range(m + 1)] for i in range(n + 1)] for i in range(n): for j in range(m): A[i + 1][j + 1] = min(A[i][j + 1] + 1, # insert A[i + 1][j] + 1, # delete A[i][j] + int(x[i] != y[j])) # subst. return A[n][m]
[ "def", "levenshtein", "(", "x", ",", "y", ")", ":", "n", "=", "len", "(", "x", ")", "m", "=", "len", "(", "y", ")", "# initializing row 0 and column 0", "A", "=", "[", "[", "i", "+", "j", "for", "j", "in", "range", "(", "m", ...
Levenshtein edit distance :param x: :param y: strings :returns: distance :complexity: `O(|x|*|y|)`
[ "Levenshtein", "edit", "distance" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/levenshtein.py#L8-L25
train
208,781
jilljenn/tryalgo
tryalgo/gale_shapley.py
gale_shapley
def gale_shapley(men, women): """Stable matching by Gale-Shapley :param men: table of size n, men[i] is preference list of women for men i :param women: similar :returns: matching table, from women to men :complexity: :math:`O(n^2)` """ n = len(men) assert n == len(women) current_suitor = [0] * n spouse = [None] * n rank = [[0] * n for j in range(n)] # build rank for j in range(n): for r in range(n): rank[j][women[j][r]] = r singles = deque(range(n)) # all men are single and get in the queue while singles: i = singles.popleft() j = men[i][current_suitor[i]] current_suitor[i] += 1 if spouse[j] is None: spouse[j] = i elif rank[j][spouse[j]] < rank[j][i]: singles.append(i) else: singles.put(spouse[j]) # sorry for spouse[j] spouse[j] = i return spouse
python
def gale_shapley(men, women): """Stable matching by Gale-Shapley :param men: table of size n, men[i] is preference list of women for men i :param women: similar :returns: matching table, from women to men :complexity: :math:`O(n^2)` """ n = len(men) assert n == len(women) current_suitor = [0] * n spouse = [None] * n rank = [[0] * n for j in range(n)] # build rank for j in range(n): for r in range(n): rank[j][women[j][r]] = r singles = deque(range(n)) # all men are single and get in the queue while singles: i = singles.popleft() j = men[i][current_suitor[i]] current_suitor[i] += 1 if spouse[j] is None: spouse[j] = i elif rank[j][spouse[j]] < rank[j][i]: singles.append(i) else: singles.put(spouse[j]) # sorry for spouse[j] spouse[j] = i return spouse
[ "def", "gale_shapley", "(", "men", ",", "women", ")", ":", "n", "=", "len", "(", "men", ")", "assert", "n", "==", "len", "(", "women", ")", "current_suitor", "=", "[", "0", "]", "*", "n", "spouse", "=", "[", "None", "]", "*", "n", "rank", "=", ...
Stable matching by Gale-Shapley :param men: table of size n, men[i] is preference list of women for men i :param women: similar :returns: matching table, from women to men :complexity: :math:`O(n^2)`
[ "Stable", "matching", "by", "Gale", "-", "Shapley" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/gale_shapley.py#L12-L40
train
208,782
jilljenn/tryalgo
tryalgo/eulerian_tour.py
eulerian_tour_directed
def eulerian_tour_directed(graph): """Eulerian tour on a directed graph :param graph: directed graph in listlist format, cannot be listdict :assumes: graph is eulerian :returns: eulerian cycle as a vertex list :complexity: `O(|V|+|E|)` """ P = [] Q = [0] R = [] succ = [0] * len(graph) while Q: node = Q.pop() P.append(node) while succ[node] < len(graph[node]): neighbor = graph[node][succ[node]] succ[node] += 1 R.append(neighbor) node = neighbor while R: Q.append(R.pop()) return P
python
def eulerian_tour_directed(graph): """Eulerian tour on a directed graph :param graph: directed graph in listlist format, cannot be listdict :assumes: graph is eulerian :returns: eulerian cycle as a vertex list :complexity: `O(|V|+|E|)` """ P = [] Q = [0] R = [] succ = [0] * len(graph) while Q: node = Q.pop() P.append(node) while succ[node] < len(graph[node]): neighbor = graph[node][succ[node]] succ[node] += 1 R.append(neighbor) node = neighbor while R: Q.append(R.pop()) return P
[ "def", "eulerian_tour_directed", "(", "graph", ")", ":", "P", "=", "[", "]", "Q", "=", "[", "0", "]", "R", "=", "[", "]", "succ", "=", "[", "0", "]", "*", "len", "(", "graph", ")", "while", "Q", ":", "node", "=", "Q", ".", "pop", "(", ")", ...
Eulerian tour on a directed graph :param graph: directed graph in listlist format, cannot be listdict :assumes: graph is eulerian :returns: eulerian cycle as a vertex list :complexity: `O(|V|+|E|)`
[ "Eulerian", "tour", "on", "a", "directed", "graph" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/eulerian_tour.py#L41-L63
train
208,783
jilljenn/tryalgo
tryalgo/eulerian_tour.py
write_cycle
def write_cycle(filename, graph, cycle, directed): """Write an eulerian tour in DOT format :param filename: the file to be written in DOT format :param graph: graph in listlist format, cannot be listdict :param bool directed: describes the graph :param cycle: tour as a vertex list :returns: nothing :complexity: `O(|V|^2 + |E|)` """ n = len(graph) weight = [[float('inf')] * n for _ in range(n)] for r in range(1, len(cycle)): weight[cycle[r-1]][cycle[r]] = r if not directed: weight[cycle[r]][cycle[r-1]] = r write_graph(filename, graph, arc_label=weight, directed=directed)
python
def write_cycle(filename, graph, cycle, directed): """Write an eulerian tour in DOT format :param filename: the file to be written in DOT format :param graph: graph in listlist format, cannot be listdict :param bool directed: describes the graph :param cycle: tour as a vertex list :returns: nothing :complexity: `O(|V|^2 + |E|)` """ n = len(graph) weight = [[float('inf')] * n for _ in range(n)] for r in range(1, len(cycle)): weight[cycle[r-1]][cycle[r]] = r if not directed: weight[cycle[r]][cycle[r-1]] = r write_graph(filename, graph, arc_label=weight, directed=directed)
[ "def", "write_cycle", "(", "filename", ",", "graph", ",", "cycle", ",", "directed", ")", ":", "n", "=", "len", "(", "graph", ")", "weight", "=", "[", "[", "float", "(", "'inf'", ")", "]", "*", "n", "for", "_", "in", "range", "(", "n", ")", "]",...
Write an eulerian tour in DOT format :param filename: the file to be written in DOT format :param graph: graph in listlist format, cannot be listdict :param bool directed: describes the graph :param cycle: tour as a vertex list :returns: nothing :complexity: `O(|V|^2 + |E|)`
[ "Write", "an", "eulerian", "tour", "in", "DOT", "format" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/eulerian_tour.py#L67-L83
train
208,784
jilljenn/tryalgo
tryalgo/eulerian_tour.py
random_eulerien_graph
def random_eulerien_graph(n): """Generates some random eulerian graph :param int n: number of vertices :returns: undirected graph in listlist representation :complexity: linear """ graphe = [[] for _ in range(n)] for v in range(n - 1): noeuds = random.sample(range(v + 1, n), random.choice( range(0 if len(graphe[v]) % 2 == 0 else 1, (n - v), 2))) graphe[v].extend(noeuds) for w in graphe[v]: if w > v: graphe[w].append(v) return graphe
python
def random_eulerien_graph(n): """Generates some random eulerian graph :param int n: number of vertices :returns: undirected graph in listlist representation :complexity: linear """ graphe = [[] for _ in range(n)] for v in range(n - 1): noeuds = random.sample(range(v + 1, n), random.choice( range(0 if len(graphe[v]) % 2 == 0 else 1, (n - v), 2))) graphe[v].extend(noeuds) for w in graphe[v]: if w > v: graphe[w].append(v) return graphe
[ "def", "random_eulerien_graph", "(", "n", ")", ":", "graphe", "=", "[", "[", "]", "for", "_", "in", "range", "(", "n", ")", "]", "for", "v", "in", "range", "(", "n", "-", "1", ")", ":", "noeuds", "=", "random", ".", "sample", "(", "range", "(",...
Generates some random eulerian graph :param int n: number of vertices :returns: undirected graph in listlist representation :complexity: linear
[ "Generates", "some", "random", "eulerian", "graph" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/eulerian_tour.py#L86-L101
train
208,785
jilljenn/tryalgo
tryalgo/longest_common_subsequence.py
longest_common_subsequence
def longest_common_subsequence(x, y): """Longest common subsequence Dynamic programming :param x: :param y: x, y are lists or strings :returns: longest common subsequence in form of a string :complexity: `O(|x|*|y|)` """ n = len(x) m = len(y) # -- compute optimal length A = [[0 for j in range(m + 1)] for i in range(n + 1)] for i in range(n): for j in range(m): if x[i] == y[j]: A[i + 1][j + 1] = A[i][j] + 1 else: A[i + 1][j + 1] = max(A[i][j + 1], A[i + 1][j]) # -- extract solution sol = [] i, j = n, m while A[i][j] > 0: if A[i][j] == A[i - 1][j]: i -= 1 elif A[i][j] == A[i][j - 1]: j -= 1 else: i -= 1 j -= 1 sol.append(x[i]) return ''.join(sol[::-1])
python
def longest_common_subsequence(x, y): """Longest common subsequence Dynamic programming :param x: :param y: x, y are lists or strings :returns: longest common subsequence in form of a string :complexity: `O(|x|*|y|)` """ n = len(x) m = len(y) # -- compute optimal length A = [[0 for j in range(m + 1)] for i in range(n + 1)] for i in range(n): for j in range(m): if x[i] == y[j]: A[i + 1][j + 1] = A[i][j] + 1 else: A[i + 1][j + 1] = max(A[i][j + 1], A[i + 1][j]) # -- extract solution sol = [] i, j = n, m while A[i][j] > 0: if A[i][j] == A[i - 1][j]: i -= 1 elif A[i][j] == A[i][j - 1]: j -= 1 else: i -= 1 j -= 1 sol.append(x[i]) return ''.join(sol[::-1])
[ "def", "longest_common_subsequence", "(", "x", ",", "y", ")", ":", "n", "=", "len", "(", "x", ")", "m", "=", "len", "(", "y", ")", "# -- compute optimal length", "A", "=", "[", "[", "0", "for", "j", "in", "range", "(", "m", "+", ...
Longest common subsequence Dynamic programming :param x: :param y: x, y are lists or strings :returns: longest common subsequence in form of a string :complexity: `O(|x|*|y|)`
[ "Longest", "common", "subsequence" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/longest_common_subsequence.py#L8-L40
train
208,786
jilljenn/tryalgo
tryalgo/kuhn_munkres_n4.py
kuhn_munkres
def kuhn_munkres(G): # maximum profit bipartite matching in O(n^4) """Maximum profit perfect matching for minimum cost perfect matching just inverse the weights :param G: squared weight matrix of a complete bipartite graph :complexity: :math:`O(n^4)` """ assert len(G) == len(G[0]) n = len(G) mu = [None] * n # Empty matching mv = [None] * n lu = [max(row) for row in G] # Trivial labels lv = [0] * n for u0 in range(n): if mu[u0] is None: # Free node while True: au = [False] * n # Empty alternating tree av = [False] * n if improve_matching(G, u0, mu, mv, au, av, lu, lv): break improve_labels(G, au, av, lu, lv) return (mu, sum(lu) + sum(lv))
python
def kuhn_munkres(G): # maximum profit bipartite matching in O(n^4) """Maximum profit perfect matching for minimum cost perfect matching just inverse the weights :param G: squared weight matrix of a complete bipartite graph :complexity: :math:`O(n^4)` """ assert len(G) == len(G[0]) n = len(G) mu = [None] * n # Empty matching mv = [None] * n lu = [max(row) for row in G] # Trivial labels lv = [0] * n for u0 in range(n): if mu[u0] is None: # Free node while True: au = [False] * n # Empty alternating tree av = [False] * n if improve_matching(G, u0, mu, mv, au, av, lu, lv): break improve_labels(G, au, av, lu, lv) return (mu, sum(lu) + sum(lv))
[ "def", "kuhn_munkres", "(", "G", ")", ":", "# maximum profit bipartite matching in O(n^4)", "assert", "len", "(", "G", ")", "==", "len", "(", "G", "[", "0", "]", ")", "n", "=", "len", "(", "G", ")", "mu", "=", "[", "None", "]", "*", "n", "# Empty mat...
Maximum profit perfect matching for minimum cost perfect matching just inverse the weights :param G: squared weight matrix of a complete bipartite graph :complexity: :math:`O(n^4)`
[ "Maximum", "profit", "perfect", "matching" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/kuhn_munkres_n4.py#L35-L57
train
208,787
jilljenn/tryalgo
tryalgo/kuhn_munkres.py
kuhn_munkres
def kuhn_munkres(G, TOLERANCE=1e-6): """Maximum profit bipartite matching by Kuhn-Munkres :param G: weight matrix where G[u][v] is the weight of edge (u,v), :param TOLERANCE: a value with absolute value below tolerance is considered as being zero. If G consists of integer or fractional values then TOLERANCE can be chosen 0. :requires: graph (U,V,E) is complete bi-partite graph with len(U) <= len(V). float('-inf') or float('inf') entries in G are allowed but not None. :returns: matching table from U to V, value of matching :complexity: :math:`O(|U|^2 |V|)` """ nU = len(G) U = range(nU) nV = len(G[0]) V = range(nV) assert nU <= nV mu = [None] * nU # empty matching mv = [None] * nV lu = [max(row) for row in G] # trivial labels lv = [0] * nV for root in U: # build an alternate tree au = [False] * nU # au, av mark nodes... au[root] = True # ... covered by the tree Av = [None] * nV # Av[v] successor of v in the tree # for every vertex u, slack[u] := (val, v) such that # val is the smallest slack on the constraints (*) # with fixed u and v being the corresponding vertex slack = [(lu[root] + lv[v] - G[root][v], root) for v in V] while True: ((delta, u), v) = min((slack[v], v) for v in V if Av[v] is None) assert au[u] if delta > TOLERANCE: # tree is full for u0 in U: # improve labels if au[u0]: lu[u0] -= delta for v0 in V: if Av[v0] is not None: lv[v0] += delta else: (val, arg) = slack[v0] slack[v0] = (val - delta, arg) assert abs(lu[u] + lv[v] - G[u][v]) <= TOLERANCE # equality Av[v] = u # add (u, v) to A if mv[v] is None: break # alternating path found u1 = mv[v] assert not au[u1] au[u1] = True # add (u1, v) to A for v1 in V: if Av[v1] is None: # update margins alt = (lu[u1] + lv[v1] - G[u1][v1], u1) if slack[v1] > alt: slack[v1] = alt while v is not None: # ... alternating path found u = Av[v] # along path to root prec = mu[u] mv[v] = u # augment matching mu[u] = v v = prec return (mu, sum(lu) + sum(lv))
python
def kuhn_munkres(G, TOLERANCE=1e-6): """Maximum profit bipartite matching by Kuhn-Munkres :param G: weight matrix where G[u][v] is the weight of edge (u,v), :param TOLERANCE: a value with absolute value below tolerance is considered as being zero. If G consists of integer or fractional values then TOLERANCE can be chosen 0. :requires: graph (U,V,E) is complete bi-partite graph with len(U) <= len(V). float('-inf') or float('inf') entries in G are allowed but not None. :returns: matching table from U to V, value of matching :complexity: :math:`O(|U|^2 |V|)` """ nU = len(G) U = range(nU) nV = len(G[0]) V = range(nV) assert nU <= nV mu = [None] * nU # empty matching mv = [None] * nV lu = [max(row) for row in G] # trivial labels lv = [0] * nV for root in U: # build an alternate tree au = [False] * nU # au, av mark nodes... au[root] = True # ... covered by the tree Av = [None] * nV # Av[v] successor of v in the tree # for every vertex u, slack[u] := (val, v) such that # val is the smallest slack on the constraints (*) # with fixed u and v being the corresponding vertex slack = [(lu[root] + lv[v] - G[root][v], root) for v in V] while True: ((delta, u), v) = min((slack[v], v) for v in V if Av[v] is None) assert au[u] if delta > TOLERANCE: # tree is full for u0 in U: # improve labels if au[u0]: lu[u0] -= delta for v0 in V: if Av[v0] is not None: lv[v0] += delta else: (val, arg) = slack[v0] slack[v0] = (val - delta, arg) assert abs(lu[u] + lv[v] - G[u][v]) <= TOLERANCE # equality Av[v] = u # add (u, v) to A if mv[v] is None: break # alternating path found u1 = mv[v] assert not au[u1] au[u1] = True # add (u1, v) to A for v1 in V: if Av[v1] is None: # update margins alt = (lu[u1] + lv[v1] - G[u1][v1], u1) if slack[v1] > alt: slack[v1] = alt while v is not None: # ... alternating path found u = Av[v] # along path to root prec = mu[u] mv[v] = u # augment matching mu[u] = v v = prec return (mu, sum(lu) + sum(lv))
[ "def", "kuhn_munkres", "(", "G", ",", "TOLERANCE", "=", "1e-6", ")", ":", "nU", "=", "len", "(", "G", ")", "U", "=", "range", "(", "nU", ")", "nV", "=", "len", "(", "G", "[", "0", "]", ")", "V", "=", "range", "(", "nV", ")", "assert", "nU",...
Maximum profit bipartite matching by Kuhn-Munkres :param G: weight matrix where G[u][v] is the weight of edge (u,v), :param TOLERANCE: a value with absolute value below tolerance is considered as being zero. If G consists of integer or fractional values then TOLERANCE can be chosen 0. :requires: graph (U,V,E) is complete bi-partite graph with len(U) <= len(V). float('-inf') or float('inf') entries in G are allowed but not None. :returns: matching table from U to V, value of matching :complexity: :math:`O(|U|^2 |V|)`
[ "Maximum", "profit", "bipartite", "matching", "by", "Kuhn", "-", "Munkres" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/kuhn_munkres.py#L42-L104
train
208,788
jilljenn/tryalgo
tryalgo/interval_cover.py
interval_cover
def interval_cover(I): """Minimum interval cover :param I: list of closed intervals :returns: minimum list of points covering all intervals :complexity: O(n log n) """ S = [] for start, end in sorted(I, key=lambda v: v[1]): if not S or S[-1] < start: S.append(end) return S
python
def interval_cover(I): """Minimum interval cover :param I: list of closed intervals :returns: minimum list of points covering all intervals :complexity: O(n log n) """ S = [] for start, end in sorted(I, key=lambda v: v[1]): if not S or S[-1] < start: S.append(end) return S
[ "def", "interval_cover", "(", "I", ")", ":", "S", "=", "[", "]", "for", "start", ",", "end", "in", "sorted", "(", "I", ",", "key", "=", "lambda", "v", ":", "v", "[", "1", "]", ")", ":", "if", "not", "S", "or", "S", "[", "-", "1", "]", "<"...
Minimum interval cover :param I: list of closed intervals :returns: minimum list of points covering all intervals :complexity: O(n log n)
[ "Minimum", "interval", "cover" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/interval_cover.py#L31-L42
train
208,789
jilljenn/tryalgo
tryalgo/graph01.py
dist01
def dist01(graph, weight, source=0, target=None): """Shortest path in a 0,1 weighted graph :param graph: directed graph in listlist or listdict format :param weight: matrix or adjacency dictionary :param int source: vertex :param target: exploration stops once distance to target is found :returns: distance table, predecessor table :complexity: `O(|V|+|E|)` """ n = len(graph) dist = [float('inf')] * n prec = [None] * n black = [False] * n dist[source] = 0 gray = deque([source]) while gray: node = gray.pop() if black[node]: continue black[node] = True if node == target: break for neighbor in graph[node]: ell = dist[node] + weight[node][neighbor] if black[neighbor] or dist[neighbor] <= ell: continue dist[neighbor] = ell prec[neighbor] = node if weight[node][neighbor] == 0: gray.append(neighbor) else: gray.appendleft(neighbor) return dist, prec
python
def dist01(graph, weight, source=0, target=None): """Shortest path in a 0,1 weighted graph :param graph: directed graph in listlist or listdict format :param weight: matrix or adjacency dictionary :param int source: vertex :param target: exploration stops once distance to target is found :returns: distance table, predecessor table :complexity: `O(|V|+|E|)` """ n = len(graph) dist = [float('inf')] * n prec = [None] * n black = [False] * n dist[source] = 0 gray = deque([source]) while gray: node = gray.pop() if black[node]: continue black[node] = True if node == target: break for neighbor in graph[node]: ell = dist[node] + weight[node][neighbor] if black[neighbor] or dist[neighbor] <= ell: continue dist[neighbor] = ell prec[neighbor] = node if weight[node][neighbor] == 0: gray.append(neighbor) else: gray.appendleft(neighbor) return dist, prec
[ "def", "dist01", "(", "graph", ",", "weight", ",", "source", "=", "0", ",", "target", "=", "None", ")", ":", "n", "=", "len", "(", "graph", ")", "dist", "=", "[", "float", "(", "'inf'", ")", "]", "*", "n", "prec", "=", "[", "None", "]", "*", ...
Shortest path in a 0,1 weighted graph :param graph: directed graph in listlist or listdict format :param weight: matrix or adjacency dictionary :param int source: vertex :param target: exploration stops once distance to target is found :returns: distance table, predecessor table :complexity: `O(|V|+|E|)`
[ "Shortest", "path", "in", "a", "0", "1", "weighted", "graph" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/graph01.py#L10-L43
train
208,790
jilljenn/tryalgo
tryalgo/max_interval_intersec.py
max_interval_intersec
def max_interval_intersec(S): """determine a value that is contained in a largest number of given intervals :param S: list of half open intervals :complexity: O(n log n), where n = len(S) """ B = ([(left, +1) for left, right in S] + [(right, -1) for left, right in S]) B.sort() c = 0 best = (c, None) for x, d in B: c += d if best[0] < c: best = (c, x) return best
python
def max_interval_intersec(S): """determine a value that is contained in a largest number of given intervals :param S: list of half open intervals :complexity: O(n log n), where n = len(S) """ B = ([(left, +1) for left, right in S] + [(right, -1) for left, right in S]) B.sort() c = 0 best = (c, None) for x, d in B: c += d if best[0] < c: best = (c, x) return best
[ "def", "max_interval_intersec", "(", "S", ")", ":", "B", "=", "(", "[", "(", "left", ",", "+", "1", ")", "for", "left", ",", "right", "in", "S", "]", "+", "[", "(", "right", ",", "-", "1", ")", "for", "left", ",", "right", "in", "S", "]", "...
determine a value that is contained in a largest number of given intervals :param S: list of half open intervals :complexity: O(n log n), where n = len(S)
[ "determine", "a", "value", "that", "is", "contained", "in", "a", "largest", "number", "of", "given", "intervals" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/max_interval_intersec.py#L8-L23
train
208,791
jilljenn/tryalgo
tryalgo/dist_grid.py
dist_grid
def dist_grid(grid, source, target=None): """Distances in a grid by BFS :param grid: matrix with 4-neighborhood :param (int,int) source: pair of row, column indices :param (int,int) target: exploration stops if target is reached :complexity: linear in grid size """ rows = len(grid) cols = len(grid[0]) dirs = [(0, +1, '>'), (0, -1, '<'), (+1, 0, 'v'), (-1, 0, '^')] i, j = source grid[i][j] = 's' Q = deque() Q.append(source) while Q: i1, j1 = Q.popleft() for di, dj, symbol in dirs: # explore all directions i2 = i1 + di j2 = j1 + dj if not (0 <= i2 and i2 < rows and 0 <= j2 and j2 < cols): continue # reached the bounds of the grid if grid[i2][j2] != ' ': # inaccessible or already visited continue grid[i2][j2] = symbol # mark visit if (i2, j2) == target: grid[i2][j2] = 't' # goal is reached return Q.append((i2, j2))
python
def dist_grid(grid, source, target=None): """Distances in a grid by BFS :param grid: matrix with 4-neighborhood :param (int,int) source: pair of row, column indices :param (int,int) target: exploration stops if target is reached :complexity: linear in grid size """ rows = len(grid) cols = len(grid[0]) dirs = [(0, +1, '>'), (0, -1, '<'), (+1, 0, 'v'), (-1, 0, '^')] i, j = source grid[i][j] = 's' Q = deque() Q.append(source) while Q: i1, j1 = Q.popleft() for di, dj, symbol in dirs: # explore all directions i2 = i1 + di j2 = j1 + dj if not (0 <= i2 and i2 < rows and 0 <= j2 and j2 < cols): continue # reached the bounds of the grid if grid[i2][j2] != ' ': # inaccessible or already visited continue grid[i2][j2] = symbol # mark visit if (i2, j2) == target: grid[i2][j2] = 't' # goal is reached return Q.append((i2, j2))
[ "def", "dist_grid", "(", "grid", ",", "source", ",", "target", "=", "None", ")", ":", "rows", "=", "len", "(", "grid", ")", "cols", "=", "len", "(", "grid", "[", "0", "]", ")", "dirs", "=", "[", "(", "0", ",", "+", "1", ",", "'>'", ")", ","...
Distances in a grid by BFS :param grid: matrix with 4-neighborhood :param (int,int) source: pair of row, column indices :param (int,int) target: exploration stops if target is reached :complexity: linear in grid size
[ "Distances", "in", "a", "grid", "by", "BFS" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/dist_grid.py#L10-L38
train
208,792
jilljenn/tryalgo
tryalgo/range_minimum_query.py
RangeMinQuery._range_min
def _range_min(self, p, start, span, i, k): """returns the minimum in t in the indexes [i, k) intersected with [start, start + span). p is the node associated to the later interval. """ if start + span <= i or k <= start: # disjoint intervals return self.INF if i <= start and start + span <= k: # included intervals return self.s[p] left = self._range_min(2 * p, start, span // 2, i, k) right = self._range_min(2 * p + 1, start + span // 2, span // 2, i, k) return min(left, right)
python
def _range_min(self, p, start, span, i, k): """returns the minimum in t in the indexes [i, k) intersected with [start, start + span). p is the node associated to the later interval. """ if start + span <= i or k <= start: # disjoint intervals return self.INF if i <= start and start + span <= k: # included intervals return self.s[p] left = self._range_min(2 * p, start, span // 2, i, k) right = self._range_min(2 * p + 1, start + span // 2, span // 2, i, k) return min(left, right)
[ "def", "_range_min", "(", "self", ",", "p", ",", "start", ",", "span", ",", "i", ",", "k", ")", ":", "if", "start", "+", "span", "<=", "i", "or", "k", "<=", "start", ":", "# disjoint intervals", "return", "self", ".", "INF", "if", "i", "<=", "sta...
returns the minimum in t in the indexes [i, k) intersected with [start, start + span). p is the node associated to the later interval.
[ "returns", "the", "minimum", "in", "t", "in", "the", "indexes", "[", "i", "k", ")", "intersected", "with", "[", "start", "start", "+", "span", ")", ".", "p", "is", "the", "node", "associated", "to", "the", "later", "interval", "." ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/range_minimum_query.py#L50-L63
train
208,793
jilljenn/tryalgo
tryalgo/range_minimum_query.py
LazySegmentTree._clear
def _clear(self, node, left, right): """propagates the lazy updates for this node to the subtrees. as a result the maxval, minval, sumval values for the node are up to date. """ if self.lazyset[node] is not None: # first do the pending set val = self.lazyset[node] self.minval[node] = val self.maxval[node] = val self.sumval[node] = val * (right - left) self.lazyset[node] = None if left < right - 1: # not a leaf self.lazyset[2 * node] = val # propagate to direct descendents self.lazyadd[2 * node] = 0 self.lazyset[2 * node + 1] = val self.lazyadd[2 * node + 1] = 0 if self.lazyadd[node] != 0: # then do the pending add val = self.lazyadd[node] self.minval[node] += val self.maxval[node] += val self.sumval[node] += val * (right - left) self.lazyadd[node] = 0 if left < right - 1: # not at a leaf self.lazyadd[2 * node] += val # propagate to direct descendents self.lazyadd[2 * node + 1] += val
python
def _clear(self, node, left, right): """propagates the lazy updates for this node to the subtrees. as a result the maxval, minval, sumval values for the node are up to date. """ if self.lazyset[node] is not None: # first do the pending set val = self.lazyset[node] self.minval[node] = val self.maxval[node] = val self.sumval[node] = val * (right - left) self.lazyset[node] = None if left < right - 1: # not a leaf self.lazyset[2 * node] = val # propagate to direct descendents self.lazyadd[2 * node] = 0 self.lazyset[2 * node + 1] = val self.lazyadd[2 * node + 1] = 0 if self.lazyadd[node] != 0: # then do the pending add val = self.lazyadd[node] self.minval[node] += val self.maxval[node] += val self.sumval[node] += val * (right - left) self.lazyadd[node] = 0 if left < right - 1: # not at a leaf self.lazyadd[2 * node] += val # propagate to direct descendents self.lazyadd[2 * node + 1] += val
[ "def", "_clear", "(", "self", ",", "node", ",", "left", ",", "right", ")", ":", "if", "self", ".", "lazyset", "[", "node", "]", "is", "not", "None", ":", "# first do the pending set", "val", "=", "self", ".", "lazyset", "[", "node", "]", "self", ".",...
propagates the lazy updates for this node to the subtrees. as a result the maxval, minval, sumval values for the node are up to date.
[ "propagates", "the", "lazy", "updates", "for", "this", "node", "to", "the", "subtrees", ".", "as", "a", "result", "the", "maxval", "minval", "sumval", "values", "for", "the", "node", "are", "up", "to", "date", "." ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/range_minimum_query.py#L126-L150
train
208,794
jilljenn/tryalgo
tryalgo/left_right_inversions.py
left_right_inversions
def left_right_inversions(tab): """ Compute left and right inversions of each element of a table. :param tab: list with comparable elements :returns: lists left and right. left[j] = the number of i<j such that tab[i] > tab[j]. right[i] = the number of i<j such that tab[i] > tab[j]. :complexity: `O(n \log n)` """ n = len(tab) left = [0] * n right = [0] * n tmp = [None] * n # temporary table rank = list(range(n)) _merge_sort(tab, tmp, rank, left, right, 0, n) return left, right
python
def left_right_inversions(tab): """ Compute left and right inversions of each element of a table. :param tab: list with comparable elements :returns: lists left and right. left[j] = the number of i<j such that tab[i] > tab[j]. right[i] = the number of i<j such that tab[i] > tab[j]. :complexity: `O(n \log n)` """ n = len(tab) left = [0] * n right = [0] * n tmp = [None] * n # temporary table rank = list(range(n)) _merge_sort(tab, tmp, rank, left, right, 0, n) return left, right
[ "def", "left_right_inversions", "(", "tab", ")", ":", "n", "=", "len", "(", "tab", ")", "left", "=", "[", "0", "]", "*", "n", "right", "=", "[", "0", "]", "*", "n", "tmp", "=", "[", "None", "]", "*", "n", "# temporary table", "rank", "=", "list...
Compute left and right inversions of each element of a table. :param tab: list with comparable elements :returns: lists left and right. left[j] = the number of i<j such that tab[i] > tab[j]. right[i] = the number of i<j such that tab[i] > tab[j]. :complexity: `O(n \log n)`
[ "Compute", "left", "and", "right", "inversions", "of", "each", "element", "of", "a", "table", "." ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/left_right_inversions.py#L31-L45
train
208,795
jilljenn/tryalgo
tryalgo/interval_tree.py
interval_tree
def interval_tree(intervals): """Construct an interval tree :param intervals: list of half-open intervals encoded as value pairs *[left, right)* :assumes: intervals are lexicographically ordered ``>>> assert intervals == sorted(intervals)`` :returns: the root of the interval tree :complexity: :math:`O(n)` """ if intervals == []: return None center = intervals[len(intervals) // 2][0] L = [] R = [] C = [] for I in intervals: if I[1] <= center: L.append(I) elif center < I[0]: R.append(I) else: C.append(I) by_low = sorted((I[0], I) for I in C) by_high = sorted((I[1], I) for I in C) IL = interval_tree(L) IR = interval_tree(R) return _Node(center, by_low, by_high, IL, IR)
python
def interval_tree(intervals): """Construct an interval tree :param intervals: list of half-open intervals encoded as value pairs *[left, right)* :assumes: intervals are lexicographically ordered ``>>> assert intervals == sorted(intervals)`` :returns: the root of the interval tree :complexity: :math:`O(n)` """ if intervals == []: return None center = intervals[len(intervals) // 2][0] L = [] R = [] C = [] for I in intervals: if I[1] <= center: L.append(I) elif center < I[0]: R.append(I) else: C.append(I) by_low = sorted((I[0], I) for I in C) by_high = sorted((I[1], I) for I in C) IL = interval_tree(L) IR = interval_tree(R) return _Node(center, by_low, by_high, IL, IR)
[ "def", "interval_tree", "(", "intervals", ")", ":", "if", "intervals", "==", "[", "]", ":", "return", "None", "center", "=", "intervals", "[", "len", "(", "intervals", ")", "//", "2", "]", "[", "0", "]", "L", "=", "[", "]", "R", "=", "[", "]", ...
Construct an interval tree :param intervals: list of half-open intervals encoded as value pairs *[left, right)* :assumes: intervals are lexicographically ordered ``>>> assert intervals == sorted(intervals)`` :returns: the root of the interval tree :complexity: :math:`O(n)`
[ "Construct", "an", "interval", "tree" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/interval_tree.py#L19-L46
train
208,796
jilljenn/tryalgo
tryalgo/interval_tree.py
intervals_containing
def intervals_containing(t, p): """Query the interval tree :param t: root of the interval tree :param p: value :returns: a list of intervals containing p :complexity: O(log n + m), where n is the number of intervals in t, and m the length of the returned list """ INF = float('inf') if t is None: return [] if p < t.center: retval = intervals_containing(t.left, p) j = bisect_right(t.by_low, (p, (INF, INF))) for i in range(j): retval.append(t.by_low[i][1]) else: retval = intervals_containing(t.right, p) i = bisect_right(t.by_high, (p, (INF, INF))) for j in range(i, len(t.by_high)): retval.append(t.by_high[j][1]) return retval
python
def intervals_containing(t, p): """Query the interval tree :param t: root of the interval tree :param p: value :returns: a list of intervals containing p :complexity: O(log n + m), where n is the number of intervals in t, and m the length of the returned list """ INF = float('inf') if t is None: return [] if p < t.center: retval = intervals_containing(t.left, p) j = bisect_right(t.by_low, (p, (INF, INF))) for i in range(j): retval.append(t.by_low[i][1]) else: retval = intervals_containing(t.right, p) i = bisect_right(t.by_high, (p, (INF, INF))) for j in range(i, len(t.by_high)): retval.append(t.by_high[j][1]) return retval
[ "def", "intervals_containing", "(", "t", ",", "p", ")", ":", "INF", "=", "float", "(", "'inf'", ")", "if", "t", "is", "None", ":", "return", "[", "]", "if", "p", "<", "t", ".", "center", ":", "retval", "=", "intervals_containing", "(", "t", ".", ...
Query the interval tree :param t: root of the interval tree :param p: value :returns: a list of intervals containing p :complexity: O(log n + m), where n is the number of intervals in t, and m the length of the returned list
[ "Query", "the", "interval", "tree" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/interval_tree.py#L49-L71
train
208,797
jilljenn/tryalgo
tryalgo/convex_hull.py
andrew
def andrew(S): """Convex hull by Andrew :param S: list of points as coordinate pairs :requires: S has at least 2 points :returns: list of points of the convex hull :complexity: `O(n log n)` """ S.sort() top = [] bot = [] for p in S: while len(top) >= 2 and not left_turn(p, top[-1], top[-2]): top.pop() top.append(p) while len(bot) >= 2 and not left_turn(bot[-2], bot[-1], p): bot.pop() bot.append(p) return bot[:-1] + top[:0:-1]
python
def andrew(S): """Convex hull by Andrew :param S: list of points as coordinate pairs :requires: S has at least 2 points :returns: list of points of the convex hull :complexity: `O(n log n)` """ S.sort() top = [] bot = [] for p in S: while len(top) >= 2 and not left_turn(p, top[-1], top[-2]): top.pop() top.append(p) while len(bot) >= 2 and not left_turn(bot[-2], bot[-1], p): bot.pop() bot.append(p) return bot[:-1] + top[:0:-1]
[ "def", "andrew", "(", "S", ")", ":", "S", ".", "sort", "(", ")", "top", "=", "[", "]", "bot", "=", "[", "]", "for", "p", "in", "S", ":", "while", "len", "(", "top", ")", ">=", "2", "and", "not", "left_turn", "(", "p", ",", "top", "[", "-"...
Convex hull by Andrew :param S: list of points as coordinate pairs :requires: S has at least 2 points :returns: list of points of the convex hull :complexity: `O(n log n)`
[ "Convex", "hull", "by", "Andrew" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/convex_hull.py#L20-L38
train
208,798
jilljenn/tryalgo
tryalgo/binary_search.py
discrete_binary_search
def discrete_binary_search(tab, lo, hi): """Binary search in a table :param tab: boolean monotone table with tab[hi] = True :param int lo: :param int hi: with hi >= lo :returns: first index i in [lo,hi] such that tab[i] :complexity: `O(log(hi-lo))` """ while lo < hi: mid = lo + (hi - lo) // 2 if tab[mid]: hi = mid else: lo = mid + 1 return lo
python
def discrete_binary_search(tab, lo, hi): """Binary search in a table :param tab: boolean monotone table with tab[hi] = True :param int lo: :param int hi: with hi >= lo :returns: first index i in [lo,hi] such that tab[i] :complexity: `O(log(hi-lo))` """ while lo < hi: mid = lo + (hi - lo) // 2 if tab[mid]: hi = mid else: lo = mid + 1 return lo
[ "def", "discrete_binary_search", "(", "tab", ",", "lo", ",", "hi", ")", ":", "while", "lo", "<", "hi", ":", "mid", "=", "lo", "+", "(", "hi", "-", "lo", ")", "//", "2", "if", "tab", "[", "mid", "]", ":", "hi", "=", "mid", "else", ":", "lo", ...
Binary search in a table :param tab: boolean monotone table with tab[hi] = True :param int lo: :param int hi: with hi >= lo :returns: first index i in [lo,hi] such that tab[i] :complexity: `O(log(hi-lo))`
[ "Binary", "search", "in", "a", "table" ]
89a4dd9655e7b6b0a176f72b4c60d0196420dfe1
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/binary_search.py#L26-L41
train
208,799