text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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. |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 :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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tolist(self):
"""produce a list representation of the partition """ |
return [[x.val for x in theclass.items] for theclass in self.classes] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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])) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add(self, node):
"""Add one node as descendant """ |
self.sons.append(node)
node.parent = self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 :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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def matrix_chain_mult(M):
"""Matrix chain multiplication :param M: list of matrices :complexity: whatever is needed by the multiplications """ |
opt, arg = matrix_mult_opt_order(M)
return _apply_order(M, arg, 0, len(M)-1) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 :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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def continuous_binary_search(f, lo, hi, gap=1e-4):
"""Binary search for a function :param f: boolean monotone function with f(hi) = True :param int lo: :param int hi: with hi >= lo :param float gap: :returns: first value x in [lo,hi] such that f(x), x is computed up to some precision :complexity: `O(log((hi-lo)/gap))` """ |
while hi - lo > gap:
# in other languages you can force floating division by using 2.0
mid = (lo + hi) / 2.
if f(mid):
hi = mid
else:
lo = mid
return lo |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ternary_search(f, lo, hi, gap=1e-10):
"""Ternary maximum search for a bitonic function :param f: boolean bitonic function (increasing then decreasing, not necessarily strictly) :param int lo: :param int hi: with hi >= lo :param float gap: :returns: value x in [lo,hi] maximizing f(x), x is computed up to some precision :complexity: `O(log((hi-lo)/gap))` """ |
while hi - lo > gap:
step = (hi - lo) / 3.
if f(lo + step) < f(lo + 2 * step):
lo += step
else:
hi -= step
return lo |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def anagrams(w):
"""group a list of words into anagrams :param w: list of strings :returns: list of lists :complexity: :math:`O(n k \log k)` in average, for n words of length at most k. :math:`O(n^2 k \log k)` in worst case due to the usage of a dictionary. """ |
w = list(set(w)) # remove duplicates
d = {} # group words according to some signature
for i in range(len(w)):
s = ''.join(sorted(w[i])) # signature
if s in d:
d[s].append(i)
else:
d[s] = [i]
# -- extract anagrams
answer = []
for s in d:
if len(d[s]) > 1: # ignore words without anagram
answer.append([w[i] for i in d[s]])
return answer |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def subset_sum(x, R):
"""Subsetsum by splitting :param x: table of values :param R: target value :returns bool: if there is a subsequence of x with total sum R :complexity: :math:`O(n^{\\lceil n/2 \\rceil})` """ |
k = len(x) // 2 # divide input
Y = [v for v in part_sum(x[:k])]
Z = [R - v for v in part_sum(x[k:])]
Y.sort() # test of intersection between Y and Z
Z.sort()
i = 0
j = 0
while i < len(Y) and j < len(Z):
if Y[i] == Z[j]:
return True
elif Y[i] < Z[j]: # increment index of smallest element
i += 1
else:
j += 1
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tarjan_recursif(graph):
"""Strongly connected components by Tarjan, recursive implementation :param graph: directed graph in listlist format, cannot be listdict :returns: list of lists for each component :complexity: linear """ |
global sccp, waiting, dfs_time, dfs_num
sccp = []
waiting = []
waits = [False] * len(graph)
dfs_time = 0
dfs_num = [None] * len(graph)
def dfs(node):
global sccp, waiting, dfs_time, dfs_num
waiting.append(node) # new node is waiting
waits[node] = True
dfs_num[node] = dfs_time # mark visit
dfs_time += 1
dfs_min = dfs_num[node] # compute dfs_min
for neighbor in graph[node]:
if dfs_num[neighbor] is None:
dfs_min = min(dfs_min, dfs(neighbor))
elif waits[neighbor] and dfs_min > dfs_num[neighbor]:
dfs_min = dfs_num[neighbor]
if dfs_min == dfs_num[node]: # representative of a component
sccp.append([]) # make a component
while True: # add waiting nodes
u = waiting.pop()
waits[u] = False
sccp[-1].append(u)
if u == node: # until representative
break
return dfs_min
for node in range(len(graph)):
if dfs_num[node] is None:
dfs(node)
return sccp |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tarjan(graph):
"""Strongly connected components by Tarjan, iterative implementation :param graph: directed graph in listlist format, cannot be listdict :returns: list of lists for each component :complexity: linear """ |
n = len(graph)
dfs_num = [None] * n
dfs_min = [n] * n
waiting = []
waits = [False] * n # invariant: waits[v] iff v in waiting
sccp = [] # list of detected components
dfs_time = 0
times_seen = [-1] * n
for start in range(n):
if times_seen[start] == -1: # initiate path
times_seen[start] = 0
to_visit = [start]
while to_visit:
node = to_visit[-1] # top of stack
if times_seen[node] == 0: # start process
dfs_num[node] = dfs_time
dfs_min[node] = dfs_time
dfs_time += 1
waiting.append(node)
waits[node] = True
children = graph[node]
if times_seen[node] == len(children): # end of process
to_visit.pop() # remove from stack
dfs_min[node] = dfs_num[node] # compute dfs_min
for child in children:
if waits[child] and dfs_min[child] < dfs_min[node]:
dfs_min[node] = dfs_min[child]
if dfs_min[node] == dfs_num[node]: # representative
component = [] # make component
while True: # add nodes
u = waiting.pop()
waits[u] = False
component.append(u)
if u == node: # until repr.
break
sccp.append(component)
else:
child = children[times_seen[node]]
times_seen[node] += 1
if times_seen[child] == -1: # not visited yet
times_seen[child] = 0
to_visit.append(child)
return sccp |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def kosaraju(graph):
"""Strongly connected components by Kosaraju :param graph: directed graph in listlist format, cannot be listdict :returns: list of lists for each component :complexity: linear """ |
n = len(graph)
order = []
sccp = []
kosaraju_dfs(graph, range(n), order, [])
kosaraju_dfs(reverse(graph), order[::-1], [], sccp)
return sccp[::-1] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_template_dirs():
"""Return a set of all template directories.""" |
temp_glob = rel_to_cwd('templates', '**', 'templates', 'config.yaml')
temp_groups = glob(temp_glob)
temp_groups = [get_parent_dir(path, 2) for path in temp_groups]
return set(temp_groups) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_scheme_dirs():
"""Return a set of all scheme directories.""" |
scheme_glob = rel_to_cwd('schemes', '**', '*.yaml')
scheme_groups = glob(scheme_glob)
scheme_groups = [get_parent_dir(path) for path in scheme_groups]
return set(scheme_groups) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build(templates=None, schemes=None, base_output_dir=None):
"""Main build function to initiate building process.""" |
template_dirs = templates or get_template_dirs()
scheme_files = get_scheme_files(schemes)
base_output_dir = base_output_dir or rel_to_cwd('output')
# raise LookupError if there is not at least one template or scheme
# to work with
if not template_dirs or not scheme_files:
raise LookupError
# raise PermissionError if user has no write acces for $base_output_dir
try:
os.makedirs(base_output_dir)
except FileExistsError:
pass
if not os.access(base_output_dir, os.W_OK):
raise PermissionError
templates = [TemplateGroup(path) for path in template_dirs]
build_from_job_list(scheme_files, templates, base_output_dir)
print('Finished building process.') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_sources_file():
"""Write a sources.yaml file to current working dir.""" |
file_content = (
'schemes: '
'https://github.com/chriskempson/base16-schemes-source.git\n'
'templates: '
'https://github.com/chriskempson/base16-templates-source.git'
)
file_path = rel_to_cwd('sources.yaml')
with open(file_path, 'w') as file_:
file_.write(file_content) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_yaml_dict(yaml_file):
"""Return a yaml_dict from reading yaml_file. If yaml_file is empty or doesn't exist, return an empty dict instead.""" |
try:
with open(yaml_file, 'r') as file_:
yaml_dict = yaml.safe_load(file_.read()) or {}
return yaml_dict
except FileNotFoundError:
return {} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_temp(self, content):
"""Get the string that points to a specific base16 scheme.""" |
temp = None
for line in content.splitlines():
# make sure there's both start and end line
if not temp:
match = TEMP_NEEDLE.match(line)
if match:
temp = match.group(1).strip()
continue
else:
match = TEMP_END_NEEDLE.match(line)
if match:
return temp
raise IndexError(self.path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_colorscheme(self, scheme_file):
"""Return a string object with the colorscheme that is to be inserted.""" |
scheme = get_yaml_dict(scheme_file)
scheme_slug = builder.slugify(scheme_file)
builder.format_scheme(scheme, scheme_slug)
try:
temp_base, temp_sub = self.temp.split('##')
except ValueError:
temp_base, temp_sub = (self.temp.strip('##'), 'default')
temp_path = rel_to_cwd('templates', temp_base)
temp_group = builder.TemplateGroup(temp_path)
try:
single_temp = temp_group.templates[temp_sub]
except KeyError:
raise FileNotFoundError(None,
None,
self.path + ' (sub-template)')
colorscheme = pystache.render(single_temp['parsed'], scheme)
return colorscheme |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write(self):
"""Write content back to file.""" |
with open(self.path, 'w') as file_:
file_.write(self.content) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_mode(arg_namespace):
"""Check command line arguments and run update function.""" |
try:
updater.update(custom_sources=arg_namespace.custom)
except (PermissionError, FileNotFoundError) as exception:
if isinstance(exception, PermissionError):
print('No write permission for current working directory.')
if isinstance(exception, FileNotFoundError):
print('Necessary resources for updating not found in current '
'working directory.') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_address_details(address, coin_symbol='btc', txn_limit=None, api_key=None, before_bh=None, after_bh=None, unspent_only=False, show_confidence=False, confirmations=0, include_script=False):
'''
Takes an address and coin_symbol and returns the address details
Optional:
- txn_limit: # transactions to include
- before_bh: filters response to only include transactions below before
height in the blockchain.
- after_bh: filters response to only include transactions above after
height in the blockchain.
- confirmations: returns the balance and TXRefs that have this number
of confirmations
- unspent_only: filters response to only include unspent TXRefs.
- show_confidence: adds confidence information to unconfirmed TXRefs.
For batching a list of addresses, see get_addresses_details
'''
assert is_valid_address_for_coinsymbol(
b58_address=address,
coin_symbol=coin_symbol), address
assert isinstance(show_confidence, bool), show_confidence
url = make_url(coin_symbol, **dict(addrs=address))
params = {}
if txn_limit:
params['limit'] = txn_limit
if api_key:
params['token'] = api_key
if before_bh:
params['before'] = before_bh
if after_bh:
params['after'] = after_bh
if confirmations:
params['confirmations'] = confirmations
if unspent_only:
params['unspentOnly'] = 'true'
if show_confidence:
params['includeConfidence'] = 'true'
if include_script:
params['includeScript'] = 'true'
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
r = get_valid_json(r)
return _clean_tx(response_dict=r) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_addresses_details(address_list, coin_symbol='btc', txn_limit=None, api_key=None,
before_bh=None, after_bh=None, unspent_only=False, show_confidence=False,
confirmations=0, include_script=False):
'''
Batch version of get_address_details method
'''
for address in address_list:
assert is_valid_address_for_coinsymbol(
b58_address=address,
coin_symbol=coin_symbol), address
assert isinstance(show_confidence, bool), show_confidence
kwargs = dict(addrs=';'.join([str(addr) for addr in address_list]))
url = make_url(coin_symbol, **kwargs)
params = {}
if txn_limit:
params['limit'] = txn_limit
if api_key:
params['token'] = api_key
if before_bh:
params['before'] = before_bh
if after_bh:
params['after'] = after_bh
if confirmations:
params['confirmations'] = confirmations
if unspent_only:
params['unspentOnly'] = 'true'
if show_confidence:
params['includeConfidence'] = 'true'
if include_script:
params['includeScript'] = 'true'
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
r = get_valid_json(r)
return [_clean_tx(response_dict=d) for d in r] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_wallet_transactions(wallet_name, api_key, coin_symbol='btc',
before_bh=None, after_bh=None, txn_limit=None, omit_addresses=False,
unspent_only=False, show_confidence=False, confirmations=0):
'''
Takes a wallet, api_key, coin_symbol and returns the wallet's details
Optional:
- txn_limit: # transactions to include
- before_bh: filters response to only include transactions below before
height in the blockchain.
- after_bh: filters response to only include transactions above after
height in the blockchain.
- confirmations: returns the balance and TXRefs that have this number
of confirmations
- unspent_only: filters response to only include unspent TXRefs.
- show_confidence: adds confidence information to unconfirmed TXRefs.
'''
assert len(wallet_name) <= 25, wallet_name
assert api_key
assert is_valid_coin_symbol(coin_symbol=coin_symbol)
assert isinstance(show_confidence, bool), show_confidence
assert isinstance(omit_addresses, bool), omit_addresses
url = make_url(coin_symbol, **dict(addrs=wallet_name))
params = {}
if txn_limit:
params['limit'] = txn_limit
if api_key:
params['token'] = api_key
if before_bh:
params['before'] = before_bh
if after_bh:
params['after'] = after_bh
if confirmations:
params['confirmations'] = confirmations
if unspent_only:
params['unspentOnly'] = 'true'
if show_confidence:
params['includeConfidence'] = 'true'
if omit_addresses:
params['omitWalletAddresses'] = 'true'
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
return _clean_tx(get_valid_json(r)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_address_overview(address, coin_symbol='btc', api_key=None):
'''
Takes an address and coin_symbol and return the address details
'''
assert is_valid_address_for_coinsymbol(b58_address=address,
coin_symbol=coin_symbol)
url = make_url(coin_symbol, 'addrs', **{address: 'balance'})
params = {}
if api_key:
params['token'] = api_key
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
return get_valid_json(r) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def generate_new_address(coin_symbol='btc', api_key=None):
'''
Takes a coin_symbol and returns a new address with it's public and private keys.
This method will create the address server side, which is inherently insecure and should only be used for testing.
If you want to create a secure address client-side using python, please check out bitmerchant:
from bitmerchant.wallet import Wallet
Wallet.new_random_wallet()
https://github.com/sbuss/bitmerchant
'''
assert api_key, 'api_key required'
assert is_valid_coin_symbol(coin_symbol)
if coin_symbol not in ('btc-testnet', 'bcy'):
WARNING_MSG = [
'Generating private key details server-side.',
'You really should do this client-side.',
'See https://github.com/sbuss/bitmerchant for an example.',
]
print(' '.join(WARNING_MSG))
url = make_url(coin_symbol, 'addrs')
params = {'token': api_key}
r = requests.post(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
return get_valid_json(r) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_transaction_details(tx_hash, coin_symbol='btc', limit=None, tx_input_offset=None, tx_output_offset=None, include_hex=False, show_confidence=False, confidence_only=False, api_key=None):
""" Takes a tx_hash, coin_symbol, and limit and returns the transaction details Optional: - limit: # inputs/ouputs to include (applies to both) - tx_input_offset: input offset - tx_output_offset: output offset - include_hex: include the raw TX hex - show_confidence: adds confidence information to unconfirmed TXRefs. - confidence_only: show only the confidence statistics and don't return the rest of the endpoint details (faster) """ |
assert is_valid_hash(tx_hash), tx_hash
assert is_valid_coin_symbol(coin_symbol), coin_symbol
added = 'txs/{}{}'.format(tx_hash, '/confidence' if confidence_only else '')
url = make_url(coin_symbol, added)
params = {}
if api_key:
params['token'] = api_key
if limit:
params['limit'] = limit
if tx_input_offset:
params['inStart'] = tx_input_offset
if tx_output_offset:
params['outStart'] = tx_output_offset
if include_hex:
params['includeHex'] = 'true'
if show_confidence and not confidence_only:
params['includeConfidence'] = 'true'
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
response_dict = get_valid_json(r)
if 'error' not in response_dict and not confidence_only:
if response_dict['block_height'] > 0:
response_dict['confirmed'] = parser.parse(response_dict['confirmed'])
else:
response_dict['block_height'] = None
# Blockcypher reports fake times if it's not in a block
response_dict['confirmed'] = None
# format this string as a datetime object
response_dict['received'] = parser.parse(response_dict['received'])
return response_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_transactions_details(tx_hash_list, coin_symbol='btc', limit=None, api_key=None):
""" Takes a list of tx_hashes, coin_symbol, and limit and returns the transaction details Limit applies to both num inputs and num outputs. TODO: add offsetting once supported """ |
for tx_hash in tx_hash_list:
assert is_valid_hash(tx_hash)
assert is_valid_coin_symbol(coin_symbol)
if len(tx_hash_list) == 0:
return []
elif len(tx_hash_list) == 1:
return [get_transaction_details(tx_hash=tx_hash_list[0],
coin_symbol=coin_symbol,
limit=limit,
api_key=api_key
)]
url = make_url(coin_symbol, **dict(txs=';'.join(tx_hash_list)))
params = {}
if api_key:
params['token'] = api_key
if limit:
params['limit'] = limit
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
response_dict_list = get_valid_json(r)
cleaned_dict_list = []
for response_dict in response_dict_list:
if 'error' not in response_dict:
if response_dict['block_height'] > 0:
response_dict['confirmed'] = parser.parse(response_dict['confirmed'])
else:
# Blockcypher reports fake times if it's not in a block
response_dict['confirmed'] = None
response_dict['block_height'] = None
# format this string as a datetime object
response_dict['received'] = parser.parse(response_dict['received'])
cleaned_dict_list.append(response_dict)
return cleaned_dict_list |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_num_confirmations(tx_hash, coin_symbol='btc', api_key=None):
'''
Given a tx_hash, return the number of confirmations that transactions has.
Answer is going to be from 0 - current_block_height.
'''
return get_transaction_details(tx_hash=tx_hash, coin_symbol=coin_symbol,
limit=1, api_key=api_key).get('confirmations') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_broadcast_transactions(coin_symbol='btc', limit=10, api_key=None):
""" Get a list of broadcast but unconfirmed transactions Similar to bitcoind's getrawmempool method """ |
url = make_url(coin_symbol, 'txs')
params = {}
if api_key:
params['token'] = api_key
if limit:
params['limit'] = limit
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
response_dict = get_valid_json(r)
unconfirmed_txs = []
for unconfirmed_tx in response_dict:
unconfirmed_tx['received'] = parser.parse(unconfirmed_tx['received'])
unconfirmed_txs.append(unconfirmed_tx)
return unconfirmed_txs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_block_overview(block_representation, coin_symbol='btc', txn_limit=None, txn_offset=None, api_key=None):
""" Takes a block_representation, coin_symbol and txn_limit and gets an overview of that block, including up to X transaction ids. Note that block_representation may be the block number or block hash """ |
assert is_valid_coin_symbol(coin_symbol)
assert is_valid_block_representation(
block_representation=block_representation,
coin_symbol=coin_symbol)
url = make_url(coin_symbol, **dict(blocks=block_representation))
params = {}
if api_key:
params['token'] = api_key
if txn_limit:
params['limit'] = txn_limit
if txn_offset:
params['txstart'] = txn_offset
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
response_dict = get_valid_json(r)
if 'error' in response_dict:
return response_dict
return _clean_block(response_dict=response_dict) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_blocks_overview(block_representation_list, coin_symbol='btc', txn_limit=None, api_key=None):
'''
Batch request version of get_blocks_overview
'''
for block_representation in block_representation_list:
assert is_valid_block_representation(
block_representation=block_representation,
coin_symbol=coin_symbol)
assert is_valid_coin_symbol(coin_symbol)
blocks = ';'.join([str(x) for x in block_representation_list])
url = make_url(coin_symbol, **dict(blocks=blocks))
logger.info(url)
params = {}
if api_key:
params['token'] = api_key
if txn_limit:
params['limit'] = txn_limit
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
r = get_valid_json(r)
return [_clean_tx(response_dict=d) for d in r] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_merkle_root(block_representation, coin_symbol='btc', api_key=None):
'''
Takes a block_representation and returns the merkle root
'''
return get_block_overview(block_representation=block_representation,
coin_symbol=coin_symbol, txn_limit=1, api_key=api_key)['mrkl_root'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_bits(block_representation, coin_symbol='btc', api_key=None):
'''
Takes a block_representation and returns the number of bits
'''
return get_block_overview(block_representation=block_representation,
coin_symbol=coin_symbol, txn_limit=1, api_key=api_key)['bits'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_nonce(block_representation, coin_symbol='btc', api_key=None):
'''
Takes a block_representation and returns the nonce
'''
return get_block_overview(block_representation=block_representation,
coin_symbol=coin_symbol, txn_limit=1, api_key=api_key)['bits'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_prev_block_hash(block_representation, coin_symbol='btc', api_key=None):
'''
Takes a block_representation and returns the previous block hash
'''
return get_block_overview(block_representation=block_representation,
coin_symbol=coin_symbol, txn_limit=1, api_key=api_key)['prev_block'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_block_hash(block_height, coin_symbol='btc', api_key=None):
'''
Takes a block_height and returns the block_hash
'''
return get_block_overview(block_representation=block_height,
coin_symbol=coin_symbol, txn_limit=1, api_key=api_key)['hash'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_block_height(block_hash, coin_symbol='btc', api_key=None):
'''
Takes a block_hash and returns the block_height
'''
return get_block_overview(block_representation=block_hash,
coin_symbol=coin_symbol, txn_limit=1, api_key=api_key)['height'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_block_details(block_representation, coin_symbol='btc', txn_limit=None, txn_offset=None, in_out_limit=None, api_key=None):
""" Takes a block_representation, coin_symbol and txn_limit and 1) Gets the block overview 2) Makes a separate API call to get specific data on txn_limit transactions Note: block_representation may be the block number or block hash WARNING: using a high txn_limit will make this *extremely* slow. """ |
assert is_valid_coin_symbol(coin_symbol)
block_overview = get_block_overview(
block_representation=block_representation,
coin_symbol=coin_symbol,
txn_limit=txn_limit,
txn_offset=txn_offset,
api_key=api_key,
)
if 'error' in block_overview:
return block_overview
txids_to_lookup = block_overview['txids']
txs_details = get_transactions_details(
tx_hash_list=txids_to_lookup,
coin_symbol=coin_symbol,
limit=in_out_limit,
api_key=api_key,
)
if 'error' in txs_details:
return txs_details
# build comparator dict to use for fast sorting of batched results later
txids_comparator_dict = {}
for cnt, tx_id in enumerate(txids_to_lookup):
txids_comparator_dict[tx_id] = cnt
# sort results using comparator dict
block_overview['txids'] = sorted(
txs_details,
key=lambda k: txids_comparator_dict.get(k.get('hash'), 9999), # anything that fails goes last
)
return block_overview |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.