Description
stringlengths 18
161k
⌀ | Code
stringlengths 15
300k
|
---|---|
implements a markov chain chains are described using a dictionary mychain a a 0 6 e 0 4 e a 0 7 e 0 3 choose the next state randomly given a markovchain randomly chooses the next state given the current state yield a sequence of states given a markov chain and the initial state choose the next state randomly given a markov chain randomly chooses the next state given the current state yield a sequence of states given a markov chain and the initial state | import random
def __choose_state(state_map):
choice = random.random()
probability_reached = 0
for state, probability in state_map.items():
probability_reached += probability
if probability_reached > choice:
return state
return None
def next_state(chain, current_state):
next_state_map = chain.get(current_state)
return __choose_state(next_state_map)
def iterating_markov_chain(chain, state):
while True:
state = next_state(chain, state)
yield state |
given the capacity source and sink of a graph computes the maximum flow from source to sink input capacity source sink output maximum flow from source to sink capacity is a twodimensional array that is vv capacityij implies the capacity of the edge from i to j if there is no edge from i to j capacityij should be zero pylint disabletoomanyarguments depth first search implementation for fordfulkerson algorithm dfs function for fordfulkerson algorithm computes maximum flow from source to sink using dfs time complexity oef e is the number of edges and f is the maximum flow in the graph computes maximum flow from source to sink using bfs time complexity ove2 v is the number of vertices and e is the number of edges finds new flow using bfs update flow array following parent starting from sink bfs function for dinic algorithm check whether sink is reachable only using edges that is not full dfs function for dinic algorithm finds new flow using edges that is not full computes maximum flow from source to sink using dinic algorithm time complexity ov2e v is the number of vertices and e is the number of edges pylint disable too many arguments depth first search implementation for ford fulkerson algorithm dfs function for ford_fulkerson algorithm computes maximum flow from source to sink using dfs time complexity o ef e is the number of edges and f is the maximum flow in the graph computes maximum flow from source to sink using bfs time complexity o v e 2 v is the number of vertices and e is the number of edges finds new flow using bfs update flow array following parent starting from sink bfs function for dinic algorithm check whether sink is reachable only using edges that is not full dfs function for dinic algorithm finds new flow using edges that is not full computes maximum flow from source to sink using dinic algorithm time complexity o v 2 e v is the number of vertices and e is the number of edges | from queue import Queue
def dfs(capacity, flow, visit, vertices, idx, sink, current_flow = 1 << 63):
if idx == sink:
return current_flow
visit[idx] = True
for nxt in range(vertices):
if not visit[nxt] and flow[idx][nxt] < capacity[idx][nxt]:
available_flow = min(current_flow, capacity[idx][nxt]-flow[idx][nxt])
tmp = dfs(capacity, flow, visit, vertices, nxt, sink, available_flow)
if tmp:
flow[idx][nxt] += tmp
flow[nxt][idx] -= tmp
return tmp
return 0
def ford_fulkerson(capacity, source, sink):
vertices = len(capacity)
ret = 0
flow = [[0]*vertices for _ in range(vertices)]
while True:
visit = [False for _ in range(vertices)]
tmp = dfs(capacity, flow, visit, vertices, source, sink)
if tmp:
ret += tmp
else:
break
return ret
def edmonds_karp(capacity, source, sink):
vertices = len(capacity)
ret = 0
flow = [[0]*vertices for _ in range(vertices)]
while True:
tmp = 0
queue = Queue()
visit = [False for _ in range(vertices)]
par = [-1 for _ in range(vertices)]
visit[source] = True
queue.put((source, 1 << 63))
while queue.qsize():
front = queue.get()
idx, current_flow = front
if idx == sink:
tmp = current_flow
break
for nxt in range(vertices):
if not visit[nxt] and flow[idx][nxt] < capacity[idx][nxt]:
visit[nxt] = True
par[nxt] = idx
queue.put((nxt, min(current_flow, capacity[idx][nxt]-flow[idx][nxt])))
if par[sink] == -1:
break
ret += tmp
parent = par[sink]
idx = sink
while parent != -1:
flow[parent][idx] += tmp
flow[idx][parent] -= tmp
idx = parent
parent = par[parent]
return ret
def dinic_bfs(capacity, flow, level, source, sink):
vertices = len(capacity)
queue = Queue()
queue.put(source)
level[source] = 0
while queue.qsize():
front = queue.get()
for nxt in range(vertices):
if level[nxt] == -1 and flow[front][nxt] < capacity[front][nxt]:
level[nxt] = level[front] + 1
queue.put(nxt)
return level[sink] != -1
def dinic_dfs(capacity, flow, level, idx, sink, work, current_flow = 1 << 63):
if idx == sink:
return current_flow
vertices = len(capacity)
while work[idx] < vertices:
nxt = work[idx]
if level[nxt] == level[idx] + 1 and flow[idx][nxt] < capacity[idx][nxt]:
available_flow = min(current_flow, capacity[idx][nxt] - flow[idx][nxt])
tmp = dinic_dfs(capacity, flow, level, nxt, sink, work, available_flow)
if tmp > 0:
flow[idx][nxt] += tmp
flow[nxt][idx] -= tmp
return tmp
work[idx] += 1
return 0
def dinic(capacity, source, sink):
vertices = len(capacity)
flow = [[0]*vertices for i in range(vertices)]
ret = 0
while True:
level = [-1 for i in range(vertices)]
work = [0 for i in range(vertices)]
if not dinic_bfs(capacity, flow, level, source, sink):
break
while True:
tmp = dinic_dfs(capacity, flow, level, source, sink, work)
if tmp > 0:
ret += tmp
else:
break
return ret |
given a nn adjacency array it will give you a maximum flow this version use bfs to search path assume the first is the source and the last is the sink time complexity oef example graph 0 16 13 0 0 0 0 0 10 12 0 0 0 4 0 0 14 0 0 0 9 0 0 20 0 0 0 7 0 4 0 0 0 0 0 0 answer should be 23 get the maximum flow through a graph using a breadth first search initial setting setting min to maxvalue save visited nodes save parent nodes initialize queue for bfs initial setting bfs to find path pop from queue checking capacity and visit if not put into queue and chage to visit and save path if there is no path from src to sink initial setting get minimum flow find minimum flow initial setting reduce capacity get the maximum flow through a graph using a breadth first search initial setting setting min to max_value save visited nodes save parent nodes initialize queue for bfs initial setting bfs to find path pop from queue checking capacity and visit if not put into queue and chage to visit and save path if there is no path from src to sink initial setting get minimum flow find minimum flow initial setting reduce capacity | import copy
import queue
import math
def maximum_flow_bfs(adjacency_matrix):
new_array = copy.deepcopy(adjacency_matrix)
total = 0
while True:
min_flow = math.inf
visited = [0]*len(new_array)
path = [0]*len(new_array)
bfs = queue.Queue()
visited[0] = 1
bfs.put(0)
while bfs.qsize() > 0:
src = bfs.get()
for k in range(len(new_array)):
if(new_array[src][k] > 0 and visited[k] == 0 ):
visited[k] = 1
bfs.put(k)
path[k] = src
if visited[len(new_array) - 1] == 0:
break
tmp = len(new_array) - 1
while tmp != 0:
if min_flow > new_array[path[tmp]][tmp]:
min_flow = new_array[path[tmp]][tmp]
tmp = path[tmp]
tmp = len(new_array) - 1
while tmp != 0:
new_array[path[tmp]][tmp] = new_array[path[tmp]][tmp] - min_flow
tmp = path[tmp]
total = total + min_flow
return total |
given a nn adjacency array it will give you a maximum flow this version use dfs to search path assume the first is the source and the last is the sink time complexity oef example graph 0 16 13 0 0 0 0 0 10 12 0 0 0 4 0 0 14 0 0 0 9 0 0 20 0 0 0 7 0 4 0 0 0 0 0 0 answer should be 23 get the maximum flow through a graph using a depth first search initial setting setting min to maxvalue save visited nodes save parent nodes initialize stack for dfs initial setting dfs to find path pop from queue checking capacity and visit if not put into queue and chage to visit and save path if there is no path from src to sink initial setting get minimum flow find minimum flow initial setting reduce capacity get the maximum flow through a graph using a depth first search initial setting setting min to max_value save visited nodes save parent nodes initialize stack for dfs initial setting dfs to find path pop from queue checking capacity and visit if not put into queue and chage to visit and save path if there is no path from src to sink initial setting get minimum flow find minimum flow initial setting reduce capacity | import copy
import math
def maximum_flow_dfs(adjacency_matrix):
new_array = copy.deepcopy(adjacency_matrix)
total = 0
while True:
min = math.inf
visited = [0]*len(new_array)
path = [0]*len(new_array)
stack = []
visited[0] = 1
stack.append(0)
while len(stack) > 0:
src = stack.pop()
for k in range(len(new_array)):
if new_array[src][k] > 0 and visited[k] == 0:
visited[k] = 1
stack.append(k)
path[k] = src
if visited[len(new_array) - 1] == 0:
break
tmp = len(new_array) - 1
while tmp != 0:
if min > new_array[path[tmp]][tmp]:
min = new_array[path[tmp]][tmp]
tmp = path[tmp]
tmp = len(new_array) - 1
while tmp != 0:
new_array[path[tmp]][tmp] = new_array[path[tmp]][tmp] - min
tmp = path[tmp]
total = total + min
return total |
minimum spanning tree mst is going to use an undirected graph pylint disabletoofewpublicmethods an edge of an undirected graph the disjoint set is represented with an list n of integers where ni is the parent of the node at position i if ni i i it s a root or a head of a set args n int number of vertices in the graph args node1 node2 int indexes of nodes whose sets will be merged get the set of nodes at position a and b if a and b are the roots this will be constant o1 join the shortest node to the longest minimizing tree size faster find get the root element of the set containing a very important memoize result of the recursion in the list to optimize next calls and make this operation practically constant o1 node a it s the set root so we can return that index args vertexcount int number of vertices in the graph edges list of edge edges of the graph forest disjointset disjointset of the vertices returns int sum of weights of the minnimum spanning tree kruskal algorithm this algorithm will find the optimal graph with less edges and less total weight to connect all vertices mst the mst will always contain n1 edges because it s the minimum required to connect n vertices procedure sort the edges criteria less weight only take edges of nodes in different sets if we take a edge we need to merge the sets to discard these after repeat this until select n1 edges we will have the complete mst if we have selected n1 edges all the other edges will be discarted so we can stop here test how input works input consists of different weighted connected undirected graphs line 1 integers n m lines 2 m2 edge with the format node index u node index v integer weight samples of input 5 6 1 2 3 1 3 8 2 4 5 3 4 2 3 5 4 4 5 6 3 3 2 1 20 3 1 20 2 3 100 sum of weights of the optimal paths 14 40 read m edges from input after finish input and graph creation use kruskal algorithm for mst pylint disable too few public methods an edge of an undirected graph the disjoint set is represented with an list n of integers where n i is the parent of the node at position i if n i i i it s a root or a head of a set args n int number of vertices in the graph contains wich node is the parent of the node at poisition i contains size of node at index i used to optimize merge make all nodes his own parent creating n sets args node1 node2 int indexes of nodes whose sets will be merged get the set of nodes at position a and b if a and b are the roots this will be constant o 1 join the shortest node to the longest minimizing tree size faster find merge set a and set b add size of old set a to set b merge set b and set a add size of old set b to set a get the root element of the set containing a very important memoize result of the recursion in the list to optimize next calls and make this operation practically constant o 1 node a it s the set root so we can return that index args vertex_count int number of vertices in the graph edges list of edge edges of the graph forest disjointset disjointset of the vertices returns int sum of weights of the minnimum spanning tree kruskal algorithm this algorithm will find the optimal graph with less edges and less total weight to connect all vertices mst the mst will always contain n 1 edges because it s the minimum required to connect n vertices procedure sort the edges criteria less weight only take edges of nodes in different sets if we take a edge we need to merge the sets to discard these after repeat this until select n 1 edges we will have the complete mst list of edges taken minimum spanning tree set of the node u set of the node v if we have selected n 1 edges all the other edges will be discarted so we can stop here test how input works input consists of different weighted connected undirected graphs line 1 integers n m lines 2 m 2 edge with the format node index u node index v integer weight samples of input 5 6 1 2 3 1 3 8 2 4 5 3 4 2 3 5 4 4 5 6 3 3 2 1 20 3 1 20 2 3 100 sum of weights of the optimal paths 14 40 create list of size m read m edges from input convert from 1 indexed to 0 indexed convert from 1 indexed to 0 indexed after finish input and graph creation use kruskal algorithm for mst | import sys
class Edge:
def __init__(self, source, target, weight):
self.source = source
self.target = target
self.weight = weight
class DisjointSet:
def __init__(self, size):
self.parent = [None] * size
self.size = [1] * size
for i in range(size):
self.parent[i] = i
def merge_set(self, node1, node2):
node1 = self.find_set(node1)
node2 = self.find_set(node2)
if self.size[node1] < self.size[node2]:
self.parent[node1] = node2
self.size[node2] += self.size[node1]
else:
self.parent[node2] = node1
self.size[node1] += self.size[node2]
def find_set(self, node):
if self.parent[node] != node:
self.parent[node] = self.find_set(self.parent[node])
return self.parent[node]
def kruskal(vertex_count, edges, forest):
edges.sort(key=lambda edge: edge.weight)
mst = []
for edge in edges:
set_u = forest.find_set(edge.u)
set_v = forest.find_set(edge.v)
if set_u != set_v:
forest.merge_set(set_u, set_v)
mst.append(edge)
if len(mst) == vertex_count-1:
break
return sum([edge.weight for edge in mst])
def main():
for size in sys.stdin:
vertex_count, edge_count = map(int, size.split())
forest = DisjointSet(edge_count)
edges = [None] * edge_count
for i in range(edge_count):
source, target, weight = map(int, input().split())
source -= 1
target -= 1
edges[i] = Edge(source, target, weight)
print("MST weights sum:", kruskal(vertex_count, edges, forest))
if __name__ == "__main__":
main() |
determine if there is a path between nodes in a graph a directed graph add a new directed edge to the graph determine if there is a path from source to target using a depth first search determine if there is a path from source to target using a depth first search param visited should be an array of booleans determining if the corresponding vertex has been visited already determine if there is a path from source to target a directed graph add a new directed edge to the graph determine if there is a path from source to target using a depth first search determine if there is a path from source to target using a depth first search param visited should be an array of booleans determining if the corresponding vertex has been visited already determine if there is a path from source to target | from collections import defaultdict
class Graph:
def __init__(self,vertex_count):
self.vertex_count = vertex_count
self.graph = defaultdict(list)
self.has_path = False
def add_edge(self,source,target):
self.graph[source].append(target)
def dfs(self,source,target):
visited = [False] * self.vertex_count
self.dfsutil(visited,source,target,)
def dfsutil(self,visited,source,target):
visited[source] = True
for i in self.graph[source]:
if target in self.graph[source]:
self.has_path = True
return
if not visited[i]:
self.dfsutil(visited,source,i)
def is_reachable(self,source,target):
self.has_path = False
self.dfs(source,target)
return self.has_path |
this prim s algorithm code is for finding weight of minimum spanning tree of a connected graph for argument graph it should be a dictionary type such as graph a 3 b 8 c b 3 a 5 d c 8 a 2 d 4 e d 5 b 2 c 6 e e 4 c 6 d where a b c d e are nodes these can be 1 2 3 4 5 as well prim s algorithm to find weight of minimum spanning tree for priority queue prim s algorithm to find weight of minimum spanning tree | import heapq
def prims_minimum_spanning(graph_used):
vis=[]
heap=[[0,1]]
prim = set()
mincost=0
while len(heap) > 0:
cost, node = heapq.heappop(heap)
if node in vis:
continue
mincost += cost
prim.add(node)
vis.append(node)
for distance, adjacent in graph_used[node]:
if adjacent not in vis:
heapq.heappush(heap, [distance, adjacent])
return mincost |
given a formula in conjunctive normal form 2cnf finds a way to assign truefalse values to all variables to satisfy all clauses or reports there is no solution https en wikipedia orgwiki2satisfiability format each clause is a pair of literals each literal in the form name isneg where name is an arbitrary identifier and isneg is true if the literal is negated perform a depth first search traversal of the graph starting at the given vertex stores the order in which nodes were visited to the list in transposed order perform a depth first search traversal of the graph starting at the given vertex records all visited nodes as being of a certain strongly connected component add a directed edge to the graph computes the strongly connected components of a graph order visited vertex false for vertex in graph graphtransposed vertex for vertex in graph for source neighbours in graph iteritems for target in neighbours addedgegraphtransposed target source for vertex in graph if not visitedvertex dfstransposedvertex graphtransposed order visited visited vertex false for vertex in graph vertexscc currentcomp 0 for vertex in reversedorder if not visitedvertex each dfs will visit exactly one component dfsvertex currentcomp vertexscc graph visited currentcomp 1 return vertexscc def buildgraphformula solves the 2sat problem entry point for testing perform a depth first search traversal of the graph starting at the given vertex stores the order in which nodes were visited to the list in transposed order perform a depth first search traversal of the graph starting at the given vertex records all visited nodes as being of a certain strongly connected component add a directed edge to the graph computes the strongly connected components of a graph each dfs will visit exactly one component builds the implication graph from the formula solves the 2 sat problem the formula is contradictory an arbitrary representant from each component true false value for each strongly connected component entry point for testing | def dfs_transposed(vertex, graph, order, visited):
visited[vertex] = True
for adjacent in graph[vertex]:
if not visited[adjacent]:
dfs_transposed(adjacent, graph, order, visited)
order.append(vertex)
def dfs(vertex, current_comp, vertex_scc, graph, visited):
visited[vertex] = True
vertex_scc[vertex] = current_comp
for adjacent in graph[vertex]:
if not visited[adjacent]:
dfs(adjacent, current_comp, vertex_scc, graph, visited)
def add_edge(graph, vertex_from, vertex_to):
if vertex_from not in graph:
graph[vertex_from] = []
graph[vertex_from].append(vertex_to)
def scc(graph):
order = []
visited = {vertex: False for vertex in graph}
graph_transposed = {vertex: [] for vertex in graph}
for (source, neighbours) in graph.iteritems():
for target in neighbours:
add_edge(graph_transposed, target, source)
for vertex in graph:
if not visited[vertex]:
dfs_transposed(vertex, graph_transposed, order, visited)
visited = {vertex: False for vertex in graph}
vertex_scc = {}
current_comp = 0
for vertex in reversed(order):
if not visited[vertex]:
dfs(vertex, current_comp, vertex_scc, graph, visited)
current_comp += 1
return vertex_scc
def build_graph(formula):
graph = {}
for clause in formula:
for (lit, _) in clause:
for neg in [False, True]:
graph[(lit, neg)] = []
for ((a_lit, a_neg), (b_lit, b_neg)) in formula:
add_edge(graph, (a_lit, a_neg), (b_lit, not b_neg))
add_edge(graph, (b_lit, b_neg), (a_lit, not a_neg))
return graph
def solve_sat(formula):
graph = build_graph(formula)
vertex_scc = scc(graph)
for (var, _) in graph:
if vertex_scc[(var, False)] == vertex_scc[(var, True)]:
return None
comp_repr = {}
for vertex in graph:
if not vertex_scc[vertex] in comp_repr:
comp_repr[vertex_scc[vertex]] = vertex
comp_value = {}
components = sorted(vertex_scc.values())
for comp in components:
if comp not in comp_value:
comp_value[comp] = False
(lit, neg) = comp_repr[comp]
comp_value[vertex_scc[(lit, not neg)]] = True
value = {var: comp_value[vertex_scc[(var, False)]] for (var, _) in graph}
return value
def main():
formula = [(('x', False), ('y', False)),
(('y', True), ('y', True)),
(('a', False), ('b', False)),
(('a', True), ('c', True)),
(('c', False), ('b', True))]
result = solve_sat(formula)
for (variable, assign) in result.items():
print(f"{variable}:{assign}")
if __name__ == '__main__':
main() |
implements tarjan s algorithm for finding strongly connected components in a graph https en wikipedia orgwikitarjan27sstronglyconnectedcomponentsalgorithm pylint disabletoofewpublicmethods a directed graph used for finding strongly connected components runs tarjan set all node index to none given a vertex adds all successors of the given vertex to the same connected component set the depth index for v to the smallest unused index consider successors of v successor w has not yet been visited recurse on it successor w is in stack s and hence in the current scc if w is not on stack then v w is a crossedge in the dfs tree and must be ignored note the next line may look odd but is correct it says w index not w lowlink that is deliberate and from the original paper if v is a root node pop the stack and generate an scc start a new strongly connected component pylint disable too few public methods a directed graph used for finding strongly connected components runs tarjan set all node index to none given a vertex adds all successors of the given vertex to the same connected component set the depth index for v to the smallest unused index consider successors of v successor w has not yet been visited recurse on it successor w is in stack s and hence in the current scc if w is not on stack then v w is a cross edge in the dfs tree and must be ignored note the next line may look odd but is correct it says w index not w lowlink that is deliberate and from the original paper if v is a root node pop the stack and generate an scc start a new strongly connected component | from algorithms.graph.graph import DirectedGraph
class Tarjan:
def __init__(self, dict_graph):
self.graph = DirectedGraph(dict_graph)
self.index = 0
self.stack = []
for vertex in self.graph.nodes:
vertex.index = None
self.sccs = []
for vertex in self.graph.nodes:
if vertex.index is None:
self.strongconnect(vertex, self.sccs)
def strongconnect(self, vertex, sccs):
vertex.index = self.index
vertex.lowlink = self.index
self.index += 1
self.stack.append(vertex)
vertex.on_stack = True
for adjacent in self.graph.adjacency_list[vertex]:
if adjacent.index is None:
self.strongconnect(adjacent, sccs)
vertex.lowlink = min(vertex.lowlink, adjacent.lowlink)
elif adjacent.on_stack:
vertex.lowlink = min(vertex.lowlink, adjacent.index)
if vertex.lowlink == vertex.index:
scc = []
while True:
adjacent = self.stack.pop()
adjacent.on_stack = False
scc.append(adjacent)
if adjacent == vertex:
break
scc.sort()
sccs.append(scc) |
finds the transitive closure of a graph reference https en wikipedia orgwikitransitiveclosureingraphtheory this class represents a directed graph using adjacency lists no of vertices default dictionary to store graph to store transitive closure adds a directed edge to the graph a recursive dfs traversal function that finds all reachable vertices for source mark reachability from source to target as true find all the vertices reachable through target the function to find transitive closure it uses recursive dfsutil call the recursive helper function to print dfs traversal starting from all vertices one by one this class represents a directed graph using adjacency lists no of vertices default dictionary to store graph to store transitive closure adds a directed edge to the graph a recursive dfs traversal function that finds all reachable vertices for source mark reachability from source to target as true find all the vertices reachable through target the function to find transitive closure it uses recursive dfs_util call the recursive helper function to print dfs traversal starting from all vertices one by one | class Graph:
def __init__(self, vertices):
self.vertex_count = vertices
self.graph = {}
self.closure = [[0 for j in range(vertices)] for i in range(vertices)]
def add_edge(self, source, target):
if source in self.graph:
self.graph[source].append(target)
else:
self.graph[source] = [target]
def dfs_util(self, source, target):
self.closure[source][target] = 1
for adjacent in self.graph[target]:
if self.closure[source][adjacent] == 0:
self.dfs_util(source, adjacent)
def transitive_closure(self):
for i in range(self.vertex_count):
self.dfs_util(i, i)
return self.closure |
different ways to traverse a graph dfs and bfs are the ultimately same except that they are visiting nodes in different order to simulate this ordering we would use stack for dfs and queue for bfs traversal by depth first search traversal by breadth first search traversal by recursive depth first search dfs and bfs are the ultimately same except that they are visiting nodes in different order to simulate this ordering we would use stack for dfs and queue for bfs traversal by depth first search traversal by breadth first search traversal by recursive depth first search | def dfs_traverse(graph, start):
visited, stack = set(), [start]
while stack:
node = stack.pop()
if node not in visited:
visited.add(node)
for next_node in graph[node]:
if next_node not in visited:
stack.append(next_node)
return visited
def bfs_traverse(graph, start):
visited, queue = set(), [start]
while queue:
node = queue.pop(0)
if node not in visited:
visited.add(node)
for next_node in graph[node]:
if next_node not in visited:
queue.append(next_node)
return visited
def dfs_traverse_recursive(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
for next_node in graph[start]:
if next_node not in visited:
dfs_traverse_recursive(graph, next_node, visited)
return visited |
algorithm used kadane s algorithm kadane s algorithm is used for finding the maximum sum of contiguous subsequence in a sequence it is considered a greedydp algorithm but i think they more greedy than dp here are some of the examples to understand the use case more clearly example1 2 3 8 1 4 result 3 8 1 4 14 example2 1 1 0 result 1 1 example3 1 3 4 result 1 example1 2 3 8 12 8 4 result 8 4 12 basic algorithm idea if the sum of the current contiguous subsequence after adding the value at the current position is less than the value at the current position then we know that it will be better if we start the current contiguous subsequence from this position else we add the value at the current position to the current contiguous subsequence note in the implementation the contiguous subsequence has at least one element if it can have 0 elements then the result will be maxmaxtillnow 0 | def max_contiguous_subsequence_sum(arr) -> int:
arr_size = len(arr)
if arr_size == 0:
return 0
max_till_now = arr[0]
curr_sub_sum = 0
for i in range(0, arr_size):
if curr_sub_sum + arr[i] < arr[i]:
curr_sub_sum = arr[i]
else:
curr_sub_sum += arr[i]
max_till_now = max(max_till_now, curr_sub_sum)
return max_till_now |
given a list of points find the k closest to the origin idea maintain a max heap of k elements we can iterate through all points if a point p has a smaller distance to the origin than the top element of a heap we add point p to the heap and remove the top element after iterating through all points our heap contains the k closest points to the origin time oknklogk space ok initialize max heap with first k points python does not support a max heap thus we can use the default min heap where the keys distance are negated for every point p in pointsk check if p is smaller than the root of the max heap if it is add p to heap and remove root reheapify same as if d heap00 heappushheap d p heappopheap note heappushpop is more efficient than separate push and pop calls each heappushpop call takes ologk time calculates the distance for a point from origo return point0 origin02 point1 origin12 time o k n k logk space o k initialize max heap with first k points python does not support a max heap thus we can use the default min heap where the keys distance are negated for every point p in points k check if p is smaller than the root of the max heap if it is add p to heap and remove root reheapify heappushpop does conditional check same as if d heap 0 0 heappush heap d p heappop heap note heappushpop is more efficient than separate push and pop calls each heappushpop call takes o logk time return points in heap calculates the distance for a point from origo | from heapq import heapify, heappushpop
def k_closest(points, k, origin=(0, 0)):
heap = [(-distance(p, origin), p) for p in points[:k]]
heapify(heap)
for point in points[k:]:
dist = distance(point, origin)
heappushpop(heap, (-dist, point))
return [point for nd, point in heap]
def distance(point, origin=(0, 0)):
return (point[0] - origin[0])**2 + (point[1] - origin[1])**2 |
merge k sorted linked lists and return it as one sorted list analyze and describe its complexity definition for singlylinked list listnode class def initself val self val val self next none def mergeklistslists merge list dummy listnodenone curr dummy q priorityqueue for node in lists if node q putnode val node while not q empty curr next q get1 these two lines seem to curr curr next be equivalent to curr q get1 if curr next q putcurr next val curr next return dummy next definition for singly linked list listnode class merge lists only change heap size when necessary merge list these two lines seem to be equivalent to curr q get 1 i think my code s complexity is also o nlogk and not using heap or priority queue n means the total elements and k means the size of list the mergetwolists function in my code comes from the problem merge two sorted lists whose complexity obviously is o n n is the sum of length of l1 and l2 to put it simpler assume the k is 2 x so the progress of combination is like a full binary tree from bottom to top so on every level of tree the combination complexity is n because every level have all n numbers without repetition the level of tree is x ie log k so the complexity is o n log k for example 8 listnode and the length of every listnode is x1 x2 x3 x4 x5 x6 x7 x8 total is n on level 3 x1 x2 x3 x4 x5 x6 x7 x8 sum n on level 2 x1 x2 x3 x4 x5 x6 x7 x8 sum n on level 1 x1 x2 x3 x4 x5 x6 x7 x8 sum n | from heapq import heappop, heapreplace, heapify
from queue import PriorityQueue
class ListNode(object):
def __init__(self, val):
self.val = val
self.next = None
def merge_k_lists(lists):
dummy = node = ListNode(0)
list_h = [(n.val, n) for n in lists if n]
heapify(list_h)
while list_h:
_, n_val = list_h[0]
if n_val.next is None:
heappop(list_h)
else:
heapreplace(list_h, (n_val.next.val, n_val.next))
node.next = n_val
node = node.next
return dummy.next
def merge_k_lists(lists):
dummy = ListNode(None)
curr = dummy
q = PriorityQueue()
for node in lists:
if node:
q.put((node.val, node))
while not q.empty():
curr.next = q.get()[1]
curr = curr.next
if curr.next:
q.put((curr.next.val, curr.next))
return dummy.next |
coding utf8 a city s skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance now suppose you are given the locations and height of all the buildings as shown on a cityscape photo figure a write a program to output the skyline formed by these buildings collectively figure b the geometric information of each building is represented by a triplet of integers li ri hi where li and ri are the x coordinates of the left and right edge of the ith building respectively and hi is its height it is guaranteed that 0 li ri intmax 0 hi intmax and ri li 0 you may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0 for instance the dimensions of all buildings in figure a are recorded as 2 9 10 3 7 15 5 12 12 15 20 10 19 24 8 the output is a list of key points red dots in figure b in the format of x1 y1 x2 y2 x3 y3 that uniquely defines a skyline a key point is the left endpoint of a horizontal line segment note that the last key point where the rightmost building ends is merely used to mark the termination of the skyline and always has zero height also the ground in between any two adjacent buildings should be considered part of the skyline contour for instance the skyline in figure b should be represented as 2 10 3 15 7 12 12 0 15 10 20 8 24 0 notes the number of buildings in any input list is guaranteed to be in the range 0 10000 the input list is already sorted in ascending order by the left x position li the output list must be sorted by the x position there must be no consecutive horizontal lines of equal height in the output skyline for instance 2 3 4 5 7 5 11 5 12 7 is not acceptable the three lines of height 5 should be merged into one in the final output as such 2 3 4 5 12 7 wortst time complexity onlogn type buildings listlistint rtype listlistint coding utf 8 a city s skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance now suppose you are given the locations and height of all the buildings as shown on a cityscape photo figure a write a program to output the skyline formed by these buildings collectively figure b the geometric information of each building is represented by a triplet of integers li ri hi where li and ri are the x coordinates of the left and right edge of the ith building respectively and hi is its height it is guaranteed that 0 li ri int_max 0 hi int_max and ri li 0 you may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0 for instance the dimensions of all buildings in figure a are recorded as 2 9 10 3 7 15 5 12 12 15 20 10 19 24 8 the output is a list of key points red dots in figure b in the format of x1 y1 x2 y2 x3 y3 that uniquely defines a skyline a key point is the left endpoint of a horizontal line segment note that the last key point where the rightmost building ends is merely used to mark the termination of the skyline and always has zero height also the ground in between any two adjacent buildings should be considered part of the skyline contour for instance the skyline in figure b should be represented as 2 10 3 15 7 12 12 0 15 10 20 8 24 0 notes the number of buildings in any input list is guaranteed to be in the range 0 10000 the input list is already sorted in ascending order by the left x position li the output list must be sorted by the x position there must be no consecutive horizontal lines of equal height in the output skyline for instance 2 3 4 5 7 5 11 5 12 7 is not acceptable the three lines of height 5 should be merged into one in the final output as such 2 3 4 5 12 7 wortst time complexity o nlogn type buildings list list int rtype list list int | import heapq
def get_skyline(lrh):
skyline, live = [], []
i, n = 0, len(lrh)
while i < n or live:
if not live or i < n and lrh[i][0] <= -live[0][1]:
x = lrh[i][0]
while i < n and lrh[i][0] == x:
heapq.heappush(live, (-lrh[i][2], -lrh[i][1]))
i += 1
else:
x = -live[0][1]
while live and -live[0][1] <= x:
heapq.heappop(live)
height = len(live) and -live[0][0]
if not skyline or height != skyline[-1][1]:
skyline += [x, height],
return skyline |
given an array nums there is a sliding window of size k which is moving from the very left of the array to the very right you can only see the k numbers in the window each time the sliding window moves right by one position for example given nums 1 3 1 3 5 3 6 7 and k 3 window position max 1 3 1 3 5 3 6 7 3 1 3 1 3 5 3 6 7 3 1 3 1 3 5 3 6 7 5 1 3 1 3 5 3 6 7 5 1 3 1 3 5 3 6 7 6 1 3 1 3 5 3 6 7 7 therefore return the max sliding window as 3 3 5 5 6 7 type nums listint type k int rtype listint type nums list int type k int rtype list int | import collections
def max_sliding_window(nums, k):
if not nums:
return nums
queue = collections.deque()
res = []
for num in nums:
if len(queue) < k:
queue.append(num)
else:
res.append(max(queue))
queue.popleft()
queue.append(num)
res.append(max(queue))
return res |
you are given two nonempty linked lists representing two nonnegative integers the digits are stored in reverse order and each of their nodes contain a single digit add the two numbers and return it as a linked list you may assume the two numbers do not contain any leading zero except the number 0 itself input 2 4 3 5 6 4 output 7 0 8 converts a positive integer into a reversed linked list for example give 112 result 2 1 1 converts the nonnegative number list into a string testsuite for the linked list structure and the adding function above 1 test case 2 test case 3 test case 4 test case converts a positive integer into a reversed linked list for example give 112 result 2 1 1 converts the non negative number list into a string testsuite for the linked list structure and the adding function above 1 test case 2 test case 3 test case 4 test case | import unittest
class Node:
def __init__(self, x):
self.val = x
self.next = None
def add_two_numbers(left: Node, right: Node) -> Node:
head = Node(0)
current = head
sum = 0
while left or right:
print("adding: ", left.val, right.val)
sum //= 10
if left:
sum += left.val
left = left.next
if right:
sum += right.val
right = right.next
current.next = Node(sum % 10)
current = current.next
if sum // 10 == 1:
current.next = Node(1)
return head.next
def convert_to_list(number: int) -> Node:
if number >= 0:
head = Node(0)
current = head
remainder = number % 10
quotient = number // 10
while quotient != 0:
current.next = Node(remainder)
current = current.next
remainder = quotient % 10
quotient //= 10
current.next = Node(remainder)
return head.next
else:
print("number must be positive!")
def convert_to_str(l: Node) -> str:
result = ""
while l:
result += str(l.val)
l = l.next
return result
class TestSuite(unittest.TestCase):
def test_convert_to_str(self):
number1 = Node(2)
number1.next = Node(4)
number1.next.next = Node(3)
self.assertEqual("243", convert_to_str(number1))
def test_add_two_numbers(self):
number1 = Node(2)
number1.next = Node(4)
number1.next.next = Node(3)
number2 = Node(5)
number2.next = Node(6)
number2.next.next = Node(4)
result = convert_to_str(add_two_numbers(number1, number2))
self.assertEqual("708", result)
number3 = Node(1)
number3.next = Node(1)
number3.next.next = Node(9)
number4 = Node(1)
number4.next = Node(0)
number4.next.next = Node(1)
result = convert_to_str(add_two_numbers(number3, number4))
self.assertEqual("2101", result)
number5 = Node(1)
number6 = Node(0)
result = convert_to_str(add_two_numbers(number5, number6))
self.assertEqual("1", result)
number7 = Node(9)
number7.next = Node(1)
number7.next.next = Node(1)
number8 = Node(1)
number8.next = Node(0)
number8.next.next = Node(1)
result = convert_to_str(add_two_numbers(number7, number8))
self.assertEqual("022", result)
def test_convert_to_list(self):
result = convert_to_str(convert_to_list(112))
self.assertEqual("211", result)
if __name__ == "__main__":
unittest.main() |
a linked list is given such that each node contains an additional random pointer which could point to any node in the list or null return a deep copy of the list type head randomlistnode rtype randomlistnode on type head randomlistnode rtype randomlistnode type head randomlistnode rtype randomlistnode o n type head randomlistnode rtype randomlistnode | from collections import defaultdict
class RandomListNode(object):
def __init__(self, label):
self.label = label
self.next = None
self.random = None
def copy_random_pointer_v1(head):
dic = dict()
m = n = head
while m:
dic[m] = RandomListNode(m.label)
m = m.next
while n:
dic[n].next = dic.get(n.next)
dic[n].random = dic.get(n.random)
n = n.next
return dic.get(head)
def copy_random_pointer_v2(head):
copy = defaultdict(lambda: RandomListNode(0))
copy[None] = None
node = head
while node:
copy[node].label = node.label
copy[node].next = copy[node.next]
copy[node].random = copy[node.random]
node = node.next
return copy[head] |
write a function to delete a node except the tail in a singly linked list given only access to that node supposed the linked list is 1 2 3 4 and you are given the third node with value 3 the linked list should become 1 2 4 after calling your function make linkedlist 1 2 3 4 node3 3 after deletenode 1 2 4 make linkedlist 1 2 3 4 node3 3 after delete_node 1 2 4 | import unittest
class Node:
def __init__(self, x):
self.val = x
self.next = None
def delete_node(node):
if node is None or node.next is None:
raise ValueError
node.val = node.next.val
node.next = node.next.next
class TestSuite(unittest.TestCase):
def test_delete_node(self):
head = Node(1)
curr = head
for i in range(2, 6):
curr.next = Node(i)
curr = curr.next
node3 = head.next.next
delete_node(node3)
curr = head
self.assertEqual(1, curr.val)
curr = curr.next
self.assertEqual(2, curr.val)
curr = curr.next
self.assertEqual(4, curr.val)
curr = curr.next
self.assertEqual(5, curr.val)
tail = curr
self.assertIsNone(tail.next)
self.assertRaises(ValueError, delete_node, tail)
self.assertRaises(ValueError, delete_node, tail.next)
if __name__ == '__main__':
unittest.main() |
given a linked list find the first node of a cycle in it 1 2 3 4 5 1 1 a b c d e c c note the solution is a direct implementation floyd s cyclefinding algorithm floyd s tortoise and hare type head node rtype node create linked list a b c d e c type head node rtype node create linked list a b c d e c | import unittest
class Node:
def __init__(self, x):
self.val = x
self.next = None
def first_cyclic_node(head):
runner = walker = head
while runner and runner.next:
runner = runner.next.next
walker = walker.next
if runner is walker:
break
if runner is None or runner.next is None:
return None
walker = head
while runner is not walker:
runner, walker = runner.next, walker.next
return runner
class TestSuite(unittest.TestCase):
def test_first_cyclic_node(self):
head = Node('A')
head.next = Node('B')
curr = head.next
cyclic_node = Node('C')
curr.next = cyclic_node
curr = curr.next
curr.next = Node('D')
curr = curr.next
curr.next = Node('E')
curr = curr.next
curr.next = cyclic_node
self.assertEqual('C', first_cyclic_node(head).val)
if __name__ == '__main__':
unittest.main() |
this function takes two lists and returns the node they have in common if any in this example 1 3 5 7 9 11 2 4 6 we would return 7 note that the node itself is the unique identifier not the value of the node we hit the end of one of the lists set a flag for this force the longer of the two lists to catch up the nodes match return the node create linked list as 1 3 5 7 9 11 2 4 6 we hit the end of one of the lists set a flag for this mark the length of the longer of the two lists force the longer of the two lists to catch up the nodes match return the node create linked list as 1 3 5 7 9 11 2 4 6 | import unittest
class Node(object):
def __init__(self, val=None):
self.val = val
self.next = None
def intersection(h1, h2):
count = 0
flag = None
h1_orig = h1
h2_orig = h2
while h1 or h2:
count += 1
if not flag and (h1.next is None or h2.next is None):
flag = (count, h1.next, h2.next)
if h1:
h1 = h1.next
if h2:
h2 = h2.next
long_len = count
short_len = flag[0]
if flag[1] is None:
shorter = h1_orig
longer = h2_orig
elif flag[2] is None:
shorter = h2_orig
longer = h1_orig
while longer and shorter:
while long_len > short_len:
longer = longer.next
long_len -= 1
if longer == shorter:
return longer
else:
longer = longer.next
shorter = shorter.next
return None
class TestSuite(unittest.TestCase):
def test_intersection(self):
a1 = Node(1)
b1 = Node(3)
c1 = Node(5)
d = Node(7)
a2 = Node(2)
b2 = Node(4)
c2 = Node(6)
e = Node(9)
f = Node(11)
a1.next = b1
b1.next = c1
c1.next = d
a2.next = b2
b2.next = c2
c2.next = d
d.next = e
e.next = f
self.assertEqual(7, intersection(a1, a2).val)
if __name__ == '__main__':
unittest.main() |
given a linked list determine if it has a cycle in it follow up can you solve it without using extra space type head node rtype bool type head node rtype bool | class Node:
def __init__(self, x):
self.val = x
self.next = None
def is_cyclic(head):
if not head:
return False
runner = head
walker = head
while runner.next and runner.next.next:
runner = runner.next.next
walker = walker.next
if runner == walker:
return True
return False |
split the list to two parts reverse the second part compare two parts second part has the same or one less node 1 get the midpoint slow 2 push the second half into the stack 3 comparison this function builds up a dictionary where the keys are the values of the list and the values are the positions at which these values occur in the list we then iterate over the dict and if there is more than one key with an odd number of occurrences bail out and return false otherwise we want to ensure that the positions of occurrence sum to the value of the length of the list 1 working from the outside of the list inward for example input 1 1 2 3 2 1 1 d 1 0 1 5 6 2 2 4 3 3 3 is the middle outlier 246 066 and 516 so we have a palindrome split the list to two parts don t forget here but forget still works reverse the second part compare two parts second part has the same or one less node 1 get the midpoint slow 2 push the second half into the stack 3 comparison this function builds up a dictionary where the keys are the values of the list and the values are the positions at which these values occur in the list we then iterate over the dict and if there is more than one key with an odd number of occurrences bail out and return false otherwise we want to ensure that the positions of occurrence sum to the value of the length of the list 1 working from the outside of the list inward for example input 1 1 2 3 2 1 1 d 1 0 1 5 6 2 2 4 3 3 3 is the middle outlier 2 4 6 0 6 6 and 5 1 6 so we have a palindrome | def is_palindrome(head):
if not head:
return True
fast, slow = head.next, head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
second = slow.next
slow.next = None
node = None
while second:
nxt = second.next
second.next = node
node = second
second = nxt
while node:
if node.val != head.val:
return False
node = node.next
head = head.next
return True
def is_palindrome_stack(head):
if not head or not head.next:
return True
slow = fast = cur = head
while fast and fast.next:
fast, slow = fast.next.next, slow.next
stack = [slow.val]
while slow.next:
slow = slow.next
stack.append(slow.val)
while stack:
if stack.pop() != cur.val:
return False
cur = cur.next
return True
def is_palindrome_dict(head):
if not head or not head.next:
return True
d = {}
pos = 0
while head:
if head.val in d.keys():
d[head.val].append(pos)
else:
d[head.val] = [pos]
head = head.next
pos += 1
checksum = pos - 1
middle = 0
for v in d.values():
if len(v) % 2 != 0:
middle += 1
else:
step = 0
for i in range(0, len(v)):
if v[i] + v[len(v) - 1 - step] != checksum:
return False
step += 1
if middle > 1:
return False
return True |
given a linked list issort function returns true if the list is in sorted increasing order and return false otherwise an empty list is considered to be sorted for example null list is sorted 1 2 3 4 list is sorted 1 2 1 3 list is not sorted | def is_sorted(head):
if not head:
return True
current = head
while current.next:
if current.val > current.next.val:
return False
current = current.next
return True |
this is a suboptimal hacky method using eval which is not safe for user input we guard against danger by ensuring k in an int this is a brute force method where we keep a dict the size of the list then we check it for the value we need if the key is not in the dict our and statement will short circuit and return false this is an optimal method using iteration we move p1 k steps ahead into the list then we move p1 and p2 together until p1 hits the end went too far k is not valid def maketestli a a b c d c f g test kthtolasteval test kthtolastdict test kthtolast this is a suboptimal hacky method using eval which is not safe for user input we guard against danger by ensuring k in an int this is a brute force method where we keep a dict the size of the list then we check it for the value we need if the key is not in the dict our and statement will short circuit and return false this is an optimal method using iteration we move p1 k steps ahead into the list then we move p1 and p2 together until p1 hits the end went too far k is not valid def make_test_li a a b c d c f g test kth_to_last_eval test kth_to_last_dict test kth_to_last | class Node():
def __init__(self, val=None):
self.val = val
self.next = None
def kth_to_last_eval(head, k):
if not isinstance(k, int) or not head.val:
return False
nexts = '.'.join(['next' for n in range(1, k+1)])
seeker = str('.'.join(['head', nexts]))
while head:
if eval(seeker) is None:
return head
else:
head = head.next
return False
def kth_to_last_dict(head, k):
if not (head and k > -1):
return False
d = dict()
count = 0
while head:
d[count] = head
head = head.next
count += 1
return len(d)-k in d and d[len(d)-k]
def kth_to_last(head, k):
if not (head or k > -1):
return False
p1 = head
p2 = head
for i in range(1, k+1):
if p1 is None:
raise IndexError
p1 = p1.next
while p1:
p1 = p1.next
p2 = p2.next
return p2
def print_linked_list(head):
string = ""
while head.next:
string += head.val + " -> "
head = head.next
string += head.val
print(string)
def test():
a1 = Node("A")
a2 = Node("A")
b = Node("B")
c1 = Node("C")
d = Node("D")
c2 = Node("C")
f = Node("F")
g = Node("G")
a1.next = a2
a2.next = b
b.next = c1
c1.next = d
d.next = c2
c2.next = f
f.next = g
print_linked_list(a1)
kth = kth_to_last_eval(a1, 4)
try:
assert kth.val == "D"
except AssertionError as e:
e.args += ("Expecting D, got %s" % kth.val,)
raise
kth = kth_to_last_dict(a1, 4)
try:
assert kth.val == "D"
except AssertionError as e:
e.args += ("Expecting D, got %s" % kth.val,)
raise
kth = kth_to_last(a1, 4)
try:
assert kth.val == "D"
except AssertionError as e:
e.args += ("Expecting D, got %s" % kth.val,)
raise
print("all passed.")
if __name__ == '__main__':
test() |
pros linked lists have constanttime insertions and deletions in any position in comparison arrays require on time to do the same thing linked lists can continue to expand without having to specify their size ahead of time remember our lectures on array sizing from the array sequence section of the course cons to access an element in a linked list you need to take ok time to go from the head of the list to the kth element in contrast arrays have constant time operations to access elements in an array pros linked lists have constant time insertions and deletions in any position in comparison arrays require o n time to do the same thing linked lists can continue to expand without having to specify their size ahead of time remember our lectures on array sizing from the array sequence section of the course cons to access an element in a linked list you need to take o k time to go from the head of the list to the kth element in contrast arrays have constant time operations to access elements in an array | class DoublyLinkedListNode(object):
def __init__(self, value):
self.value = value
self.next = None
self.prev = None
class SinglyLinkedListNode(object):
def __init__(self, value):
self.value = value
self.next = None |
merge two sorted linked lists and return it as a new list the new list should be made by splicing together the nodes of the first two lists for example input 124 134 output 112344 recursively recursively | class Node:
def __init__(self, x):
self.val = x
self.next = None
def merge_two_list(l1, l2):
ret = cur = Node(0)
while l1 and l2:
if l1.val < l2.val:
cur.next = l1
l1 = l1.next
else:
cur.next = l2
l2 = l2.next
cur = cur.next
cur.next = l1 or l2
return ret.next
def merge_two_list_recur(l1, l2):
if not l1 or not l2:
return l1 or l2
if l1.val < l2.val:
l1.next = merge_two_list_recur(l1.next, l2)
return l1
else:
l2.next = merge_two_list_recur(l1, l2.next)
return l2 |
write code to partition a linked list around a value x such that all nodes less than x come before all nodes greater than or equal to x if x is contained within the list the values of x only need to be after the elements less than x the partition element x can appear anywhere in the right partition it does not need to appear between the left and right partitions 3 5 8 5 10 2 1 partition5 3 1 2 10 5 5 8 we assume the values of all linked list nodes are int and that x in an int cache previous value in case it needs to be pointed elsewhere cache previous value in case it needs to be pointed elsewhere | class Node():
def __init__(self, val=None):
self.val = int(val)
self.next = None
def print_linked_list(head):
string = ""
while head.next:
string += str(head.val) + " -> "
head = head.next
string += str(head.val)
print(string)
def partition(head, x):
left = None
right = None
prev = None
current = head
while current:
if int(current.val) >= x:
if not right:
right = current
else:
if not left:
left = current
else:
prev.next = current.next
left.next = current
left = current
left.next = right
if prev and prev.next is None:
break
prev = current
current = current.next
def test():
a = Node("3")
b = Node("5")
c = Node("8")
d = Node("5")
e = Node("10")
f = Node("2")
g = Node("1")
a.next = b
b.next = c
c.next = d
d.next = e
e.next = f
f.next = g
print_linked_list(a)
partition(a, 5)
print_linked_list(a)
if __name__ == '__main__':
test() |
time complexity on space complexity on time complexity on2 space complexity o1 a a b c d c f g time complexity o n space complexity o n time complexity o n 2 space complexity o 1 a a b c d c f g | class Node():
def __init__(self, val = None):
self.val = val
self.next = None
def remove_dups(head):
hashset = set()
prev = Node()
while head:
if head.val in hashset:
prev.next = head.next
else:
hashset.add(head.val)
prev = head
head = head.next
def remove_dups_wothout_set(head):
current = head
while current:
runner = current
while runner.next:
if runner.next.val == current.val:
runner.next = runner.next.next
else:
runner = runner.next
current = current.next
def print_linked_list(head):
string = ""
while head.next:
string += head.val + " -> "
head = head.next
string += head.val
print(string)
a1 = Node("A")
a2 = Node("A")
b = Node("B")
c1 = Node("C")
d = Node("D")
c2 = Node("C")
f = Node("F")
g = Node("G")
a1.next = a2
a2.next = b
b.next = c1
c1.next = d
d.next = c2
c2.next = f
f.next = g
remove_dups(a1)
print_linked_list(a1)
remove_dups_wothout_set(a1)
print_linked_list(a1) |
given a linked list removerange function accepts a starting and ending index as parameters and removes the elements at those indexes inclusive from the list for example list 8 13 17 4 9 12 98 41 7 23 0 92 removerangelist 3 8 list becomes 8 13 17 23 0 92 legal range of the list 0 start index end index size of list case remove node at head move pointer to start position remove data until the end case remove node at head move pointer to start position remove data until the end | def remove_range(head, start, end):
assert(start <= end)
if start == 0:
for i in range(0, end+1):
if head != None:
head = head.next
else:
current = head
for i in range(0,start-1):
current = current.next
for i in range(0, end-start + 1):
if current != None and current.next != None:
current.next = current.next.next
return head |
reverse a singly linked list for example 1 2 3 4 after reverse 4 3 2 1 iterative solution tn on type head listnode rtype listnode recursive solution tn on type head listnode rtype listnode iterative solution t n o n type head listnode rtype listnode recursive solution t n o n type head listnode rtype listnode | def reverse_list(head):
if not head or not head.next:
return head
prev = None
while head:
current = head
head = head.next
current.next = prev
prev = current
return prev
def reverse_list_recursive(head):
if head is None or head.next is None:
return head
p = head.next
head.next = None
revrest = reverse_list_recursive(p)
p.next = head
return revrest |
given a list rotate the list to the right by k places where k is nonnegative for example given 12345null and k 2 return 45123null definition for singlylinked list class listnodeobject def initself x self val x self next none type head listnode type k int rtype listnode count length of the list make it circular rotate until lengthk definition for singly linked list class listnode object def __init__ self x self val x self next none type head listnode type k int rtype listnode count length of the list make it circular rotate until length k | def rotate_right(head, k):
if not head or not head.next:
return head
current = head
length = 1
while current.next:
current = current.next
length += 1
current.next = head
k = k % length
for i in range(length-k):
current = current.next
head = current.next
current.next = None
return head |
given a linked list swap every two adjacent nodes and return its head for example given 1234 you should return the list as 2143 your algorithm should use only constant space you may not modify the values in the list only nodes itself can be changed | class Node(object):
def __init__(self, x):
self.val = x
self.next = None
def swap_pairs(head):
if not head:
return head
start = Node(0)
start.next = head
current = start
while current.next and current.next.next:
first = current.next
second = current.next.next
first.next = second.next
current.next = second
current.next.next = first
current = current.next.next
return start.next |
hashmap data type hashmap create a new empty map it returns an empty map collection putkey val add a new keyvalue pair to the map if the key is already in the map then replace the old value with the new value getkey given a key return the value stored in the map or none otherwise delkey or del mapkey delete the keyvalue pair from the map using a statement of the form del mapkey len return the number of keyvalue pairs stored in the map in return true for a statement of the form key in map if the given key is in the map false otherwise can assign to hash index key already exists here assign over table is full that key was never assigned key found table is full and wrapped around that key was never assigned key found assign with deleted sentinel table is full and wrapped around linear probing increase size of dict 2 if filled 23 size like python dict hashmap data type hashmap create a new empty map it returns an empty map collection put key val add a new key value pair to the map if the key is already in the map then replace the old value with the new value get key given a key return the value stored in the map or none otherwise del_ key or del map key delete the key value pair from the map using a statement of the form del map key len return the number of key value pairs stored in the map in return true for a statement of the form key in map if the given key is in the map false otherwise keys values can assign to hash_ index key already exists here assign over table is full that key was never assigned key found table is full and wrapped around that key was never assigned key found assign with deleted sentinel table is full and wrapped around linear probing increase size of dict 2 if filled 2 3 size like python dict this will be the new size | class HashTable(object):
_empty = object()
_deleted = object()
def __init__(self, size=11):
self.size = size
self._len = 0
self._keys = [self._empty] * size
self._values = [self._empty] * size
def put(self, key, value):
initial_hash = hash_ = self.hash(key)
while True:
if self._keys[hash_] is self._empty or self._keys[hash_] is self._deleted:
self._keys[hash_] = key
self._values[hash_] = value
self._len += 1
return
elif self._keys[hash_] == key:
self._keys[hash_] = key
self._values[hash_] = value
return
hash_ = self._rehash(hash_)
if initial_hash == hash_:
raise ValueError("Table is full")
def get(self, key):
initial_hash = hash_ = self.hash(key)
while True:
if self._keys[hash_] is self._empty:
return None
elif self._keys[hash_] == key:
return self._values[hash_]
hash_ = self._rehash(hash_)
if initial_hash == hash_:
return None
def del_(self, key):
initial_hash = hash_ = self.hash(key)
while True:
if self._keys[hash_] is self._empty:
return None
elif self._keys[hash_] == key:
self._keys[hash_] = self._deleted
self._values[hash_] = self._deleted
self._len -= 1
return
hash_ = self._rehash(hash_)
if initial_hash == hash_:
return None
def hash(self, key):
return key % self.size
def _rehash(self, old_hash):
return (old_hash + 1) % self.size
def __getitem__(self, key):
return self.get(key)
def __delitem__(self, key):
return self.del_(key)
def __setitem__(self, key, value):
self.put(key, value)
def __len__(self):
return self._len
class ResizableHashTable(HashTable):
MIN_SIZE = 8
def __init__(self):
super().__init__(self.MIN_SIZE)
def put(self, key, value):
rv = super().put(key, value)
if len(self) >= (self.size * 2) / 3:
self.__resize()
def __resize(self):
keys, values = self._keys, self._values
self.size *= 2
self._len = 0
self._keys = [self._empty] * self.size
self._values = [self._empty] * self.size
for key, value in zip(keys, values):
if key is not self._empty and key is not self._deleted:
self.put(key, value) |
given two strings s and t write a function to determine if t is an anagram of s example 1 input s anagram t nagaram output true example 2 input s rat t car output false note you may assume the string contains only lowercase alphabets reference https leetcode comproblemsvalidanagramdescription type s str type t str rtype bool type s str type t str rtype bool | def is_anagram(s, t):
maps = {}
mapt = {}
for i in s:
maps[i] = maps.get(i, 0) + 1
for i in t:
mapt[i] = mapt.get(i, 0) + 1
return maps == mapt |
given two strings s and t determine if they are isomorphic two strings are isomorphic if the characters in s can be replaced to get t all occurrences of a character must be replaced with another character while preserving the order of characters no two characters may map to the same character but a character may map to itself example 1 input s egg t add output true example 2 input s foo t bar output false example 3 input s paper t title output true reference https leetcode comproblemsisomorphicstringsdescription type s str type t str rtype bool type s str type t str rtype bool | def is_isomorphic(s, t):
if len(s) != len(t):
return False
dict = {}
set_value = set()
for i in range(len(s)):
if s[i] not in dict:
if t[i] in set_value:
return False
dict[s[i]] = t[i]
set_value.add(t[i])
else:
if dict[s[i]] != t[i]:
return False
return True |
given string a and b with b containing all distinct characters find the longest common sub sequence s length expected complexity on logn assuming s2 has all unique chars assuming s2 has all unique chars | def max_common_sub_string(s1, s2):
s2dic = {s2[i]: i for i in range(len(s2))}
maxr = 0
subs = ''
i = 0
while i < len(s1):
if s1[i] in s2dic:
j = s2dic[s1[i]]
k = i
while j < len(s2) and k < len(s1) and s1[k] == s2[j]:
k += 1
j += 1
if k - i > maxr:
maxr = k-i
subs = s1[i:k]
i = k
else:
i += 1
return subs |
from icecream import ic ics logestsubstr 申请长度为n的列表 并初始化 同上 当 j 时 第 i 个子串为回文子串 判断长度 当j i 1时 判断s i 是否等于s j 并判断当j 1时 第i 1个子串是否为回文子串 当 j 时 第 i 个子串为回文子串 覆盖旧的列表 新的列表清空 from icecream import ic ic s logestsubstr logestsubstr | def longest_palindromic_subsequence(s):
k = len(s)
olist = [0] * k
nList = [0] * k
logestSubStr = ""
logestLen = 0
for j in range(0, k):
for i in range(0, j + 1):
if j - i <= 1:
if s[i] == s[j]:
nList[i] = 1
len_t = j - i + 1
if logestLen < len_t:
logestSubStr = s[i:j + 1]
logestLen = len_t
else:
if s[i] == s[j] and olist[i+1]:
nList[i] = 1
len_t = j - i + 1
if logestLen < len_t:
logestSubStr = s[i:j + 1]
logestLen = len_t
olist = nList
nList = [0] * k
return logestLen |
design a data structure that supports all following operations in average o1 time insertval inserts an item val to the set if not already present removeval removes an item val from the set if present getrandom returns a random element from current set of elements each element must have the same probability of being returned | import random
class RandomizedSet:
def __init__(self):
self.nums = []
self.idxs = {}
def insert(self, val):
if val not in self.idxs:
self.nums.append(val)
self.idxs[val] = len(self.nums)-1
return True
return False
def remove(self, val):
if val in self.idxs:
idx, last = self.idxs[val], self.nums[-1]
self.nums[idx], self.idxs[last] = last, idx
self.nums.pop()
self.idxs.pop(val, 0)
return True
return False
def get_random(self):
idx = random.randint(0, len(self.nums)-1)
return self.nums[idx]
if __name__ == "__main__":
rs = RandomizedSet()
print("insert 1: ", rs.insert(1))
print("insert 2: ", rs.insert(2))
print("insert 3: ", rs.insert(3))
print("insert 4: ", rs.insert(4))
print("remove 3: ", rs.remove(3))
print("remove 3: ", rs.remove(3))
print("remove 1: ", rs.remove(1))
print("random: ", rs.get_random())
print("random: ", rs.get_random())
print("random: ", rs.get_random())
print("random: ", rs.get_random()) |
hashtable data type by having each bucket contain a linked list of elements that are hashed to that bucket usage table separatechaininghashtable create a new empty map table put hello world add a new keyvalue pair lentable return the number of keyvalue pairs stored in the map 1 table get hello get value by key world del table hello equivalent to table del hello deleting keyvalue pair table get hello is none return none if a key doesn t exist true hashtable data type by having each bucket contain a linked list of elements that are hashed to that bucket usage table separatechaininghashtable create a new empty map table put hello world add a new key value pair len table return the number of key value pairs stored in the map 1 table get hello get value by key world del table hello equivalent to table del_ hello deleting key value pair table get hello is none return none if a key doesn t exist true | import unittest
class Node(object):
def __init__(self, key=None, value=None, next=None):
self.key = key
self.value = value
self.next = next
class SeparateChainingHashTable(object):
_empty = None
def __init__(self, size=11):
self.size = size
self._len = 0
self._table = [self._empty] * size
def put(self, key, value):
hash_ = self.hash(key)
node_ = self._table[hash_]
if node_ is self._empty:
self._table[hash_] = Node(key, value)
else:
while node_.next is not None:
if node_.key == key:
node_.value = value
return
node_ = node_.next
node_.next = Node(key, value)
self._len += 1
def get(self, key):
hash_ = self.hash(key)
node_ = self._table[hash_]
while node_ is not self._empty:
if node_.key == key:
return node_.value
node_ = node_.next
return None
def del_(self, key):
hash_ = self.hash(key)
node_ = self._table[hash_]
pre_node = None
while node_ is not None:
if node_.key == key:
if pre_node is None:
self._table[hash_] = node_.next
else:
pre_node.next = node_.next
self._len -= 1
pre_node = node_
node_ = node_.next
def hash(self, key):
return hash(key) % self.size
def __len__(self):
return self._len
def __getitem__(self, key):
return self.get(key)
def __delitem__(self, key):
return self.del_(key)
def __setitem__(self, key, value):
self.put(key, value) |
determine if a sudoku is valid according to sudoku puzzles the rules the sudoku board could be partially filled where empty cells are filled with the character | def is_valid_sudoku(self, board):
seen = []
for i, row in enumerate(board):
for j, c in enumerate(row):
if c != '.':
seen += [(c,j),(i,c),(i/3,j/3,c)]
return len(seen) == len(set(seen)) |
given a pattern and a string str find if str follows the same pattern here follow means a full match such that there is a bijection between a letter in pattern and a nonempty word in str example 1 input pattern abba str dog cat cat dog output true example 2 input pattern abba str dog cat cat fish output false example 3 input pattern aaaa str dog cat cat dog output false example 4 input pattern abba str dog dog dog dog output false notes you may assume pattern contains only lowercase letters and str contains lowercase letters separated by a single space reference https leetcode comproblemswordpatterndescription | def word_pattern(pattern, str):
dict = {}
set_value = set()
list_str = str.split()
if len(list_str) != len(pattern):
return False
for i in range(len(pattern)):
if pattern[i] not in dict:
if list_str[i] in set_value:
return False
dict[pattern[i]] = list_str[i]
set_value.add(list_str[i])
else:
if dict[pattern[i]] != list_str[i]:
return False
return True |
collection of mathematical algorithms and functions | from .base_conversion import *
from .decimal_to_binary_ip import *
from .euler_totient import *
from .extended_gcd import *
from .factorial import *
from .gcd import *
from .generate_strobogrammtic import *
from .is_strobogrammatic import *
from .modular_exponential import *
from .next_perfect_square import *
from .prime_check import *
from .primes_sieve_of_eratosthenes import *
from .pythagoras import *
from .rabin_miller import *
from .rsa import *
from .combination import *
from .cosine_similarity import *
from .find_order_simple import *
from .find_primitive_root_simple import *
from .diffie_hellman_key_exchange import *
from .num_digits import *
from .power import *
from .magic_number import *
from .krishnamurthy_number import *
from .num_perfect_squares import * |
integer base conversion algorithm inttobase5 2 return 101 basetoint f 16 return 15 type num int type base int rtype str note you can use int builtin function instead of this type strtoconvert str type base int rtype int type num int type base int rtype str note you can use int built in function instead of this type str_to_convert str type base int rtype int | import string
def int_to_base(num, base):
is_negative = False
if num == 0:
return '0'
if num < 0:
is_negative = True
num *= -1
digit = string.digits + string.ascii_uppercase
res = ''
while num > 0:
res += digit[num % base]
num //= base
if is_negative:
return '-' + res[::-1]
return res[::-1]
def base_to_int(str_to_convert, base):
digit = {}
for ind, char in enumerate(string.digits + string.ascii_uppercase):
digit[char] = ind
multiplier = 1
res = 0
for char in str_to_convert[::-1]:
res += digit[char] * multiplier
multiplier *= base
return res |
solves system of equations using the chinese remainder theorem if possible computes the smallest x that satisfies the chinese remainder theorem for a system of equations the system of equations has the form x nums0 rems0 x nums1 rems1 x numsk 1 remsk 1 where k is the number of elements in nums and rems k 0 all numbers in nums needs to be pariwise coprime otherwise an exception is raised returns x the smallest value for x that satisfies the system of equations computes the smallest x that satisfies the chinese remainder theorem for a system of equations the system of equations has the form x nums 0 rems 0 x nums 1 rems 1 x nums k 1 rems k 1 where k is the number of elements in nums and rems k 0 all numbers in nums needs to be pariwise coprime otherwise an exception is raised returns x the smallest value for x that satisfies the system of equations | from typing import List
from algorithms.maths.gcd import gcd
def solve_chinese_remainder(nums : List[int], rems : List[int]):
if not len(nums) == len(rems):
raise Exception("nums and rems should have equal length")
if not len(nums) > 0:
raise Exception("Lists nums and rems need to contain at least one element")
for num in nums:
if not num > 1:
raise Exception("All numbers in nums needs to be > 1")
if not _check_coprime(nums):
raise Exception("All pairs of numbers in nums are not coprime")
k = len(nums)
x = 1
while True:
i = 0
while i < k:
if x % nums[i] != rems[i]:
break
i += 1
if i == k:
return x
x += 1
def _check_coprime(list_to_check : List[int]):
for ind, num in enumerate(list_to_check):
for num2 in list_to_check[ind + 1:]:
if gcd(num, num2) != 1:
return False
return True |
functions to calculate ncr ie how many ways to choose r items from n items this function calculates ncr if n r or r 0 return 1 return combinationn1 r1 combinationn1 r def combinationmemon r this function calculates ncr this function calculates ncr using memoization method | def combination(n, r):
if n == r or r == 0:
return 1
return combination(n-1, r-1) + combination(n-1, r)
def combination_memo(n, r):
memo = {}
def recur(n, r):
if n == r or r == 0:
return 1
if (n, r) not in memo:
memo[(n, r)] = recur(n - 1, r - 1) + recur(n - 1, r)
return memo[(n, r)]
return recur(n, r) |
calculate cosine similarity between given two 1d list two list must have the same length example cosinesimilarity1 1 1 1 2 1 output 0 47140452079103173 calculate l2 distance from two given vectors calculate cosine similarity between given two vectors type vec1 list type vec2 list calculate the dot product of two vectors calculate l2 distance from two given vectors calculate cosine similarity between given two vectors type vec1 list type vec2 list calculate the dot product of two vectors | import math
def _l2_distance(vec):
norm = 0.
for element in vec:
norm += element * element
norm = math.sqrt(norm)
return norm
def cosine_similarity(vec1, vec2):
if len(vec1) != len(vec2):
raise ValueError("The two vectors must be the same length. Got shape " + str(len(vec1))
+ " and " + str(len(vec2)))
norm_a = _l2_distance(vec1)
norm_b = _l2_distance(vec2)
similarity = 0.
for vec1_element, vec2_element in zip(vec1, vec2):
similarity += vec1_element * vec2_element
similarity /= (norm_a * norm_b)
return similarity |
given an ip address in dotteddecimal representation determine the binary representation for example decimaltobinary255 0 0 5 returns 11111111 00000000 00000000 00000101 accepts string returns string convert 8bit decimal number to binary representation type val str rtype str convert dotteddecimal ip address to binary representation with help of decimaltobinaryutil convert 8 bit decimal number to binary representation type val str rtype str convert dotted decimal ip address to binary representation with help of decimal_to_binary_util | def decimal_to_binary_util(val):
bits = [128, 64, 32, 16, 8, 4, 2, 1]
val = int(val)
binary_rep = ''
for bit in bits:
if val >= bit:
binary_rep += str(1)
val -= bit
else:
binary_rep += str(0)
return binary_rep
def decimal_to_binary_ip(ip):
values = ip.split('.')
binary_list = []
for val in values:
binary_list.append(decimal_to_binary_util(val))
return '.'.join(binary_list) |
algorithms for performing diffiehellman key exchange code from algorithmsmathsprimecheck py written by goswamirahul and hai honag dang return true if num is a prime number else return false for positive integer n and given integer a that satisfies gcda n 1 the order of a modulo n is the smallest positive integer k that satisfies pow a k n 1 in other words ak 1 mod n order of certain number may or may not exist if not return 1 exception handeling 1 is the order of of 1 euler s totient function also known as phifunction n counts the number of integers between 1 and n inclusive which are coprime to n two numbers are coprime if their greatest common divisor gcd equals 1 code from algorithmsmathseulertotient py written by goswamirahul euler s totient function or phi function time complexity osqrtn result n for i in range2 intn 0 5 1 if n i 0 while n i 0 n i result result i if n 1 result result n return result def findprimitiverootn exception handeling 0 is the only primitive root of 1 to have order a and n must be relative prime with each other diffiehellman key exchange is the method that enables two entities in here alice and bob not knowing each other to share common secret key through notencrypted communication network this method use the property of oneway function discrete logarithm for example given a b and n it is easy to calculate x that satisfies ab x mod n however it is very hard to calculate x that satisfies ax b mod n for using this method large prime number p and its primitive root a must be given alice determine her private key in the range of 1 p1 this must be kept in secret return randint1 p1 def alicepublickeyaprk a p bob determine his private key in the range of 1 p1 this must be kept in secret return randint1 p1 def bobpublickeybprk a p alice calculate secret key shared with bob with her private key and bob s public key this must be kept in secret return powbpuk aprk p def bobsharedkeyapuk bprk p perform diffiehelmman key exchange if option is not none print explanation of process when option parameter is given option 1 if primecheckp is false printfp is not a prime number p must be large prime number return false try prootlist findprimitiverootp prootlist indexa except valueerror printfa is not a primitive root of p a must be primitive root of p return false aprk aliceprivatekeyp apuk alicepublickeyaprk a p bprk bobprivatekeyp bpuk bobpublickeybprk a p if option 1 printfalice s private key aprk printfalice s public key apuk printfbob s private key bprk printfbob s public key bpuk in here alice send her public key to bob and bob also send his public key to alice ashk alicesharedkeybpuk aprk p bshk bobsharedkeyapuk bprk p print fshared key calculated by alice ashk print fshared key calculated by bob bshk return ashk bshk code from algorithms maths prime_check py written by goswami rahul and hai honag dang return true if num is a prime number else return false for positive integer n and given integer a that satisfies gcd a n 1 the order of a modulo n is the smallest positive integer k that satisfies pow a k n 1 in other words a k 1 mod n order of certain number may or may not exist if not return 1 exception handeling 1 is the order of of 1 euler s totient function also known as phi function ϕ n counts the number of integers between 1 and n inclusive which are coprime to n two numbers are coprime if their greatest common divisor gcd equals 1 code from algorithms maths euler_totient py written by goswami rahul euler s totient function or phi function time complexity o sqrt n for positive integer n and given integer a that satisfies gcd a n 1 a is the primitive root of n if a s order k for n satisfies k ϕ n primitive roots of certain number may or may not be exist if so return empty list returns all primitive roots of n exception handeling 0 is the only primitive root of 1 to have order a and n must be relative prime with each other diffie hellman key exchange is the method that enables two entities in here alice and bob not knowing each other to share common secret key through not encrypted communication network this method use the property of one way function discrete logarithm for example given a b and n it is easy to calculate x that satisfies a b x mod n however it is very hard to calculate x that satisfies a x b mod n for using this method large prime number p and its primitive root a must be given alice determine her private key in the range of 1 p 1 this must be kept in secret alice calculate her public key with her private key this is open to public bob determine his private key in the range of 1 p 1 this must be kept in secret bob calculate his public key with his private key this is open to public alice calculate secret key shared with bob with her private key and bob s public key this must be kept in secret bob calculate secret key shared with alice with his private key and alice s public key this must be kept in secret perform diffie helmman key exchange print explanation of process when option parameter is given p must be large prime number a must be primitive root of p in here alice send her public key to bob and bob also send his public key to alice | import math
from random import randint
def prime_check(num):
if num <= 1:
return False
if num == 2 or num == 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
j = 5
while j * j <= num:
if num % j == 0 or num % (j + 2) == 0:
return False
j += 6
return True
def find_order(a, n):
if (a == 1) & (n == 1):
return 1
if math.gcd(a, n) != 1:
print ("a and n should be relative prime!")
return -1
for i in range(1, n):
if pow(a, i) % n == 1:
return i
return -1
def euler_totient(n):
result = n
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
while n % i == 0:
n //= i
result -= result // i
if n > 1:
result -= result // n
return result
def find_primitive_root(n):
if n == 1:
return [0]
phi = euler_totient(n)
p_root_list = []
for i in range (1, n):
if math.gcd(i, n) != 1:
continue
order = find_order(i, n)
if order == phi:
p_root_list.append(i)
return p_root_list
def alice_private_key(p):
return randint(1, p-1)
def alice_public_key(a_pr_k, a, p):
return pow(a, a_pr_k) % p
def bob_private_key(p):
return randint(1, p-1)
def bob_public_key(b_pr_k, a, p):
return pow(a, b_pr_k) % p
def alice_shared_key(b_pu_k, a_pr_k, p):
return pow(b_pu_k, a_pr_k) % p
def bob_shared_key(a_pu_k, b_pr_k, p):
return pow(a_pu_k, b_pr_k) % p
def diffie_hellman_key_exchange(a, p, option = None):
if option is not None:
option = 1
if prime_check(p) is False:
print(f"{p} is not a prime number")
return False
try:
p_root_list = find_primitive_root(p)
p_root_list.index(a)
except ValueError:
print(f"{a} is not a primitive root of {p}")
return False
a_pr_k = alice_private_key(p)
a_pu_k = alice_public_key(a_pr_k, a, p)
b_pr_k = bob_private_key(p)
b_pu_k = bob_public_key(b_pr_k, a, p)
if option == 1:
print(f"Alice's private key: {a_pr_k}")
print(f"Alice's public key: {a_pu_k}")
print(f"Bob's private key: {b_pr_k}")
print(f"Bob's public key: {b_pu_k}")
a_sh_k = alice_shared_key(b_pu_k, a_pr_k, p)
b_sh_k = bob_shared_key(a_pu_k, b_pr_k, p)
print (f"Shared key calculated by Alice = {a_sh_k}")
print (f"Shared key calculated by Bob = {b_sh_k}")
return a_sh_k == b_sh_k |
euler s totient function also known as phifunction n counts the number of integers between 1 and n inclusive which are coprime to n two numbers are coprime if their greatest common divisor gcd equals 1 euler s totient function or phi function time complexity osqrtn result n for i in range2 intn 0 5 1 if n i 0 while n i 0 n i result result i if n 1 result result n return result euler s totient function or phi function time complexity o sqrt n | def euler_totient(n):
result = n
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
while n % i == 0:
n //= i
result -= result // i
if n > 1:
result -= result // n
return result |
provides extended gcd functionality for finding coprime numbers s and t such that num1 s num2 t gcdnum1 num2 ie the coefficients of bzout s identity extended gcd algorithm return s t g such that num1 s num2 t gcdnum1 num2 and s and t are coprime extended gcd algorithm return s t g such that num1 s num2 t gcd num1 num2 and s and t are co prime | def extended_gcd(num1, num2):
old_s, s = 1, 0
old_t, t = 0, 1
old_r, r = num1, num2
while r != 0:
quotient = old_r / r
old_r, r = r, old_r - quotient * r
old_s, s = s, old_s - quotient * s
old_t, t = t, old_t - quotient * t
return old_s, old_t, old_r |
calculates the factorial with the added functionality of calculating it modulo mod calculates factorial iteratively if mod is not none then return n mod time complexity on if not isinstancen int and n 0 raise valueerror n must be a nonnegative integer if mod is not none and not isinstancemod int and mod 0 raise valueerror mod must be a positive integer result 1 if n 0 return 1 for i in range2 n1 result i if mod result mod return result def factorialrecurn modnone calculates factorial iteratively if mod is not none then return n mod time complexity o n calculates factorial recursively if mod is not none then return n mod time complexity o n | def factorial(n, mod=None):
if not (isinstance(n, int) and n >= 0):
raise ValueError("'n' must be a non-negative integer.")
if mod is not None and not (isinstance(mod, int) and mod > 0):
raise ValueError("'mod' must be a positive integer")
result = 1
if n == 0:
return 1
for i in range(2, n+1):
result *= i
if mod:
result %= mod
return result
def factorial_recur(n, mod=None):
if not (isinstance(n, int) and n >= 0):
raise ValueError("'n' must be a non-negative integer.")
if mod is not None and not (isinstance(mod, int) and mod > 0):
raise ValueError("'mod' must be a positive integer")
if n == 0:
return 1
result = n * factorial(n - 1, mod)
if mod:
result %= mod
return result |
implementation of the cooleytukey which is the most common fft algorithm input an array of complex values which has a size of n where n is an integer power of 2 output an array of complex values which is the discrete fourier transform of the input example 1 input 2 02j 1 03j 3 01j 2 02j output 88j 2j 22j 20j pseudocode https en wikipedia orgwikicooleye28093tukeyfftalgorithm recursive implementation of the cooleytukey n lenx if n 1 return x get the elements at evenodd indices even fftx0 2 odd fftx1 2 y 0 for i in rangen for k in rangen2 q exp2jpiknoddk yk evenk q yk n2 evenk q return y recursive implementation of the cooley tukey get the elements at even odd indices | from cmath import exp, pi
def fft(x):
N = len(x)
if N == 1:
return x
even = fft(x[0::2])
odd = fft(x[1::2])
y = [0 for i in range(N)]
for k in range(N//2):
q = exp(-2j*pi*k/N)*odd[k]
y[k] = even[k] + q
y[k + N//2] = even[k] - q
return y |
for positive integer n and given integer a that satisfies gcda n 1 the order of a modulo n is the smallest positive integer k that satisfies pow a k n 1 in other words ak 1 mod n order of a certain number may or may not be exist if not return 1 total time complexity onlogn on for iteration loop ologn for builtin power function find order for positive integer n and given integer a that satisfies gcda n 1 exception handeling 1 is the order of of 1 find order for positive integer n and given integer a that satisfies gcd a n 1 exception handeling 1 is the order of of 1 | import math
def find_order(a, n):
if (a == 1) & (n == 1):
return 1
if math.gcd(a, n) != 1:
print ("a and n should be relative prime!")
return -1
for i in range(1, n):
if pow(a, i) % n == 1:
return i
return -1 |
function to find the primitive root of a number for positive integer n and given integer a that satisfies gcda n 1 the order of a modulo n is the smallest positive integer k that satisfies pow a k n 1 in other words ak 1 mod n order of certain number may or may not be exist if so return 1 find order for positive integer n and given integer a that satisfies gcda n 1 time complexity onlogn exception handeling 1 is the order of of 1 euler s totient function also known as phifunction n counts the number of integers between 1 and n inclusive which are coprime to n two numbers are coprime if their greatest common divisor gcd equals 1 code from algorithmsmathseulertotient py written by goswamirahul euler s totient function or phi function time complexity osqrtn result n for i in range2 intn 0 5 1 if n i 0 while n i 0 n i result result i if n 1 result result n return result def findprimitiverootn if n 1 exception handeling 0 is the only primitive root of 1 return 0 phi eulertotientn prootlist to have order a and n must be relative prime with each other for positive integer n and given integer a that satisfies gcd a n 1 the order of a modulo n is the smallest positive integer k that satisfies pow a k n 1 in other words a k 1 mod n order of certain number may or may not be exist if so return 1 find order for positive integer n and given integer a that satisfies gcd a n 1 time complexity o nlog n exception handeling 1 is the order of of 1 euler s totient function also known as phi function ϕ n counts the number of integers between 1 and n inclusive which are coprime to n two numbers are coprime if their greatest common divisor gcd equals 1 code from algorithms maths euler_totient py written by goswami rahul euler s totient function or phi function time complexity o sqrt n for positive integer n and given integer a that satisfies gcd a n 1 a is the primitive root of n if a s order k for n satisfies k ϕ n primitive roots of certain number may or may not exist if so return empty list exception handeling 0 is the only primitive root of 1 it will return every primitive roots of n to have order a and n must be relative prime with each other | import math
def find_order(a, n):
if (a == 1) & (n == 1):
return 1
if math.gcd(a, n) != 1:
print ("a and n should be relative prime!")
return -1
for i in range(1, n):
if pow(a, i) % n == 1:
return i
return -1
def euler_totient(n):
result = n
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
while n % i == 0:
n //= i
result -= result // i
if n > 1:
result -= result // n
return result
def find_primitive_root(n):
if n == 1:
return [0]
phi = euler_totient(n)
p_root_list = []
for i in range (1, n):
if math.gcd(i, n) == 1:
order = find_order(i, n)
if order == phi:
p_root_list.append(i)
return p_root_list |
functions for calculating the greatest common divisor of two integers or their least common multiple computes the greatest common divisor of integers a and b using euclid s algorithm gcd gcd gcd gcd see proof https proofwiki orgwikigcdfornegativeintegers computes the lowest common multiple of integers a and b return absa absb gcda b def trailingzerox count 0 while x and not x 1 count 1 x 1 return count def gcdbita b computes the greatest common divisor of integers a and b using euclid s algorithm gcd 𝑎 𝑏 gcd 𝑎 𝑏 gcd 𝑎 𝑏 gcd 𝑎 𝑏 see proof https proofwiki org wiki gcd_for_negative_integers computes the lowest common multiple of integers a and b given a positive integer x computes the number of trailing zero of x example input 34 100010 output 1 input 40 101000 output 3 given two non negative integer a and b computes the greatest common divisor of a and b using bitwise operator similar to gcd but uses bitwise operators and less error handling | def gcd(a, b):
a_int = isinstance(a, int)
b_int = isinstance(b, int)
a = abs(a)
b = abs(b)
if not(a_int or b_int):
raise ValueError("Input arguments are not integers")
if (a == 0) or (b == 0) :
raise ValueError("One or more input arguments equals zero")
while b != 0:
a, b = b, a % b
return a
def lcm(a, b):
return abs(a) * abs(b) / gcd(a, b)
def trailing_zero(x):
count = 0
while x and not x & 1:
count += 1
x >>= 1
return count
def gcd_bit(a, b):
tza = trailing_zero(a)
tzb = trailing_zero(b)
a >>= tza
b >>= tzb
while b:
if a < b:
a, b = b, a
a -= b
a >>= trailing_zero(a)
return a << min(tza, tzb) |
a strobogrammatic number is a number that looks the same when rotated 180 degrees looked at upside down find all strobogrammatic numbers that are of length n for example given n 2 return 11 69 88 96 given n generate all strobogrammatic numbers of length n type n int rtype liststr type low str type high str rtype int given n generate all strobogrammatic numbers of length n type n int rtype list str type low str type high str rtype int | def gen_strobogrammatic(n):
return helper(n, n)
def helper(n, length):
if n == 0:
return [""]
if n == 1:
return ["1", "0", "8"]
middles = helper(n-2, length)
result = []
for middle in middles:
if n != length:
result.append("0" + middle + "0")
result.append("8" + middle + "8")
result.append("1" + middle + "1")
result.append("9" + middle + "6")
result.append("6" + middle + "9")
return result
def strobogrammatic_in_range(low, high):
res = []
count = 0
low_len = len(low)
high_len = len(high)
for i in range(low_len, high_len + 1):
res.extend(helper2(i, i))
for perm in res:
if len(perm) == low_len and int(perm) < int(low):
continue
if len(perm) == high_len and int(perm) > int(high):
continue
count += 1
return count
def helper2(n, length):
if n == 0:
return [""]
if n == 1:
return ["0", "8", "1"]
mids = helper(n-2, length)
res = []
for mid in mids:
if n != length:
res.append("0"+mid+"0")
res.append("1"+mid+"1")
res.append("6"+mid+"9")
res.append("9"+mid+"6")
res.append("8"+mid+"8")
return res |
implementation of hailstone function which generates a sequence for some n by following these rules n 1 done n is even the next n n2 n is odd the next n 3n 1 return the hailstone sequence from n to 1 n the starting point of the hailstone sequence return the hailstone sequence from n to 1 n the starting point of the hailstone sequence | def hailstone(n):
sequence = [n]
while n > 1:
if n%2 != 0:
n = 3*n + 1
else:
n = int(n/2)
sequence.append(n)
return sequence |
a krishnamurthy number is a number whose sum total of the factorials of each digit is equal to the number itself the following are some examples of krishnamurthy numbers 145 is a krishnamurthy number because 1 4 5 1 24 120 145 40585 is also a krishnamurthy number 4 0 5 8 5 40585 357 or 25965 is not a krishnamurthy number 3 5 7 6 120 5040 357 the following function will check if a number is a krishnamurthy number or not and return a boolean value calculates the factorial of a given number n fact 1 while n 0 fact n n 1 return fact def krishnamurthynumbern if n 0 return false sumofdigits 0 will hold sum of factorial of digits temp n while temp 0 get the factorial of of the last digit of n and add it to sumofdigits sumofdigits findfactorialtemp 10 replace value of temp by temp10 i e will remove the last digit from temp temp 10 returns true if number is krishnamurthy return sumofdigits n calculates the factorial of a given number n will hold sum of factorial of digits get the factorial of of the last digit of n and add it to sum_of_digits replace value of temp by temp 10 i e will remove the last digit from temp returns true if number is krishnamurthy | def find_factorial(n):
fact = 1
while n != 0:
fact *= n
n -= 1
return fact
def krishnamurthy_number(n):
if n == 0:
return False
sum_of_digits = 0
temp = n
while temp != 0:
sum_of_digits += find_factorial(temp % 10)
temp //= 10
return sum_of_digits == n |
magic number a number is said to be a magic number if summing the digits of the number and then recursively repeating this process for the given sum untill the number becomes a single digit number equal to 1 example number 50113 5011310 101 this is a magic number number 1234 123410 101 this is a magic number number 199 19919 1910 101 this is a magic number number 111 1113 this is not a magic number the following function checks for magic numbers and returns a boolean accordingly checks if n is a magic number totalsum 0 will end when n becomes 0 and sum becomes single digit while n 0 or totalsum 9 when n becomes 0 but we have a totalsum we update the value of n with the value of the sum digits if n 0 n totalsum only when sum of digits isn t single digit totalsum 0 totalsum n 10 n 10 return true if sum becomes 1 return totalsum 1 checks if n is a magic number will end when n becomes 0 and sum becomes single digit when n becomes 0 but we have a total_sum we update the value of n with the value of the sum digits only when sum of digits isn t single digit return true if sum becomes 1 | def magic_number(n):
total_sum = 0
while n > 0 or total_sum > 9:
if n == 0:
n = total_sum
total_sum = 0
total_sum += n % 10
n //= 10
return total_sum == 1 |
computes base exponent mod time complexity olog n use similar to python inbuilt function pow if exponent 0 raise valueerrorexponent must be positive base mod result 1 while exponent 0 if the last bit is 1 add 2k if exponent 1 result result base mod exponent exponent 1 utilize modular multiplication properties to combine the computed mod c values base base base mod return result computes base exponent mod time complexity o log n use similar to python in built function pow if the last bit is 1 add 2 k utilize modular multiplication properties to combine the computed mod c values | def modular_exponential(base, exponent, mod):
if exponent < 0:
raise ValueError("Exponent must be positive.")
base %= mod
result = 1
while exponent > 0:
if exponent & 1:
result = (result * base) % mod
exponent = exponent >> 1
base = (base * base) % mod
return result |
extendedgcda b modified from https github comkeonalgorithmsblobmasteralgorithmsmathsextendedgcd py extended gcd algorithm return s t g such that a s b t gcda b and s and t are coprime returns x such that a x 1 mod m a and m must be coprime extended_gcd a b modified from https github com keon algorithms blob master algorithms maths extended_gcd py extended gcd algorithm return s t g such that a s b t gcd a b and s and t are co prime returns x such that a x 1 mod m a and m must be coprime | def extended_gcd(a: int, b: int) -> [int, int, int]:
old_s, s = 1, 0
old_t, t = 0, 1
old_r, r = a, b
while r != 0:
quotient = old_r // r
old_r, r = r, old_r - quotient * r
old_s, s = s, old_s - quotient * s
old_t, t = t, old_t - quotient * t
return old_s, old_t, old_r
def modular_inverse(a: int, m: int) -> int:
s, _, g = extended_gcd(a, m)
if g != 1:
raise ValueError("a and m must be coprime")
return s % m |
i just bombed an interview and made pretty much zero progress on my interview question given a number find the next higher number which has the exact same set of digits as the original number for example given 38276 return 38627 given 99999 return 1 no such number exists condensed mathematical description find largest index i such that arrayi 1 arrayi if no such i exists then this is already the last permutation find largest index j such that j i and arrayj arrayi 1 swap arrayj and arrayi 1 reverse the suffix starting at arrayi no such number exists prefer slicing instead of reversed digits idx | import unittest
def next_bigger(num):
digits = [int(i) for i in str(num)]
idx = len(digits) - 1
while idx >= 1 and digits[idx-1] >= digits[idx]:
idx -= 1
if idx == 0:
return -1
pivot = digits[idx-1]
swap_idx = len(digits) - 1
while pivot >= digits[swap_idx]:
swap_idx -= 1
digits[swap_idx], digits[idx-1] = digits[idx-1], digits[swap_idx]
digits[idx:] = digits[:idx-1:-1]
return int(''.join(str(x) for x in digits))
class TestSuite(unittest.TestCase):
def test_next_bigger(self):
self.assertEqual(next_bigger(38276), 38627)
self.assertEqual(next_bigger(12345), 12354)
self.assertEqual(next_bigger(1528452), 1528524)
self.assertEqual(next_bigger(138654), 143568)
self.assertEqual(next_bigger(54321), -1)
self.assertEqual(next_bigger(999), -1)
self.assertEqual(next_bigger(5), -1)
if __name__ == '__main__':
unittest.main() |
this program will look for the next perfect square check the argument to see if it is a perfect square itself if it is not then return 1 otherwise look for the next perfect square for instance if you pass 121 then the script should return the next perfect square which is 144 alternative method works by evaluating anything nonzero as true 0 000001 true root sq0 5 return 1 if root 1 else root12 alternative method works by evaluating anything non zero as true 0 000001 true | def find_next_square(sq):
root = sq ** 0.5
if root.is_integer():
return (root + 1)**2
return -1
def find_next_square2(sq):
root = sq**0.5
return -1 if root % 1 else (root+1)**2 |
find the nth digit of given number 1 find the length of the number where the nth digit is from 2 find the actual number where the nth digit is from 3 find the nth digit and return find the nth digit of given number 1 find the length of the number where the nth digit is from 2 find the actual number where the nth digit is from 3 find the nth digit and return | def find_nth_digit(n):
length = 1
count = 9
start = 1
while n > length * count:
n -= length * count
length += 1
count *= 10
start *= 10
start += (n-1) / length
s = str(start)
return int(s[(n-1) % length]) |
numdigits method will return the number of digits of a number in o1 time using math log10 method | import math
def num_digits(n):
n=abs(n)
if n==0:
return 1
return int(math.log10(n))+1 |
given an integer numperfectsquares will return the minimum amount of perfect squares are required to sum to the specified number lagrange s foursquare theorem gives us that the answer will always be between 1 and 4 https en wikipedia orgwikilagrange27sfoursquaretheorem some examples number perfect squares representation answer 9 32 1 10 32 12 2 12 22 22 22 3 31 52 22 12 12 4 returns the smallest number of perfect squares that sum to the specified number return int between 1 4 if the number is a perfect square then we only need 1 number we check if https en wikipedia orgwikilegendre27sthreesquaretheorem holds and divide the number accordingly ie if the number can be written as a sum of 3 squares where the 02 is allowed which is possible for all numbers except those of the form 4a8b 7 if the number is of the form 4a8b 7 it can t be expressed as a sum of three or less excluding the 02 perfect squares if the number was of that form the previous while loop divided away the 4a so by now it would be of the form 8b 7 so check if this is the case and return 4 since it neccessarily must be a sum of 4 perfect squares in accordance with https en wikipedia orgwikilagrange27sfoursquaretheorem by now we know that the number wasn t of the form 4a8b 7 so it can be expressed as a sum of 3 or less perfect squares try first to express it as a sum of 2 perfect squares and if that fails we know finally that it can be expressed as a sum of 3 perfect squares returns the smallest number of perfect squares that sum to the specified number return int between 1 4 if the number is a perfect square then we only need 1 number we check if https en wikipedia org wiki legendre 27s_three square_theorem holds and divide the number accordingly ie if the number can be written as a sum of 3 squares where the 0 2 is allowed which is possible for all numbers except those of the form 4 a 8b 7 if the number is of the form 4 a 8b 7 it can t be expressed as a sum of three or less excluding the 0 2 perfect squares if the number was of that form the previous while loop divided away the 4 a so by now it would be of the form 8b 7 so check if this is the case and return 4 since it neccessarily must be a sum of 4 perfect squares in accordance with https en wikipedia org wiki lagrange 27s_four square_theorem by now we know that the number wasn t of the form 4 a 8b 7 so it can be expressed as a sum of 3 or less perfect squares try first to express it as a sum of 2 perfect squares and if that fails we know finally that it can be expressed as a sum of 3 perfect squares | import math
def num_perfect_squares(number):
if int(math.sqrt(number))**2 == number:
return 1
while number > 0 and number % 4 == 0:
number /= 4
if number % 8 == 7:
return 4
for i in range(1, int(math.sqrt(number)) + 1):
if int(math.sqrt(number - i**2))**2 == number - i**2:
return 2
return 3 |
from future import annotations a simple monomial class to record the details of all variables that a typical monomial is composed of create a monomial in the given variables examples monomial1 1 a11 monomial 1 3 2 2 4 1 5 0 12 12a13a22a4 monomial 0 monomial2 3 3 1 1 5 32a23a31 a helper for converting numbers to fraction only when possible def equaluptoscalarself other monomial bool return true if other is a monomial and is equivalent to self up to a scalar multiple def addself other unionint float fraction monomial define the addition of two monomials or the addition of a monomial with an int float or a fraction if they don t share same variables then by the definition if they are added the result becomes a polynomial and not a monomial thus raise valueerror in that case def eqself other monomial bool return true if two monomials are equal upto a scalar multiple def mulself other unionint float fraction monomial monomial multiply two monomials and merge the variables in both of them examples monomial1 1 monomial1 3 2 1 a12a2 monomial3 2 2 5 52a32 def inverseself monomial compute the inverse of a monomial examples monomial1 1 2 1 3 2 2 5 inverse monomial1 1 2 1 3 2 25 def truedivself other unionint float fraction monomial monomial compute the division between two monomials or a monomial and some other datatype like intfloatfraction def floordivself other unionint float fraction monomial monomial for monomials floor div is the same as true div def cloneself monomial clone the monomial def cleanself monomial clean the monomial by dropping any variables that have power 0 def subself other unionint float fraction monomial monomial compute the subtraction of a monomial and a datatype such as int float fraction or monomial define the hash of a monomial by the underlying variables if hashing is implemented in ovlogv where v represents the number of variables in the monomial then search queries for the purposes of simplification of a polynomial can be performed in ovlogv as well much better than the length of the polynomial get the set of all variables present in the monomial substitute the variables in the monomial for values defined by the substitutions dictionary get a string representation of the monomial a simple implementation of a polynomial class that records the details about two polynomials that are potentially comprised of multiple variables create a polynomial in the given variables examples polynomial monomial1 1 2 monomial2 3 1 1 1 math pi fraction1 2 a12 1a23a11 2 6415926536 polynomial 0 a helper for converting numbers to fraction only when possible def addself other unionint float fraction monomial polynomial polynomial add a given poylnomial to a copy of self def subself other unionint float fraction monomial polynomial polynomial subtract the given polynomial from a copy of self def mulself other unionint float fraction monomial polynomial polynomial multiply a given polynomial to a copy of self def floordivself other unionint float fraction monomial polynomial polynomial for polynomials floordiv is the same as truediv def truedivself other unionint float fraction monomial polynomial polynomial for polynomials only division by a monomial is defined todo implement polynomial polynomial def cloneself polynomial clone the polynomial get all the variables present in this polynomials res sort get the monomials of this polynomial return true if the other polynomial is the same as this get the value after substituting certain values for the variables defined in substitutions get a string representation of the polynomial from __future__ import annotations a simple monomial class to record the details of all variables that a typical monomial is composed of create a monomial in the given variables examples monomial 1 1 a_1 1 monomial 1 3 2 2 4 1 5 0 12 12 a_1 3 a_2 2 a_4 monomial 0 monomial 2 3 3 1 1 5 3 2 a_2 3 a_3 1 a helper for converting numbers to fraction only when possible def equal_upto_scalar self other monomial bool return true if other is a monomial and is equivalent to self up to a scalar multiple def __add__ self other union int float fraction monomial define the addition of two monomials or the addition of a monomial with an int float or a fraction if they don t share same variables then by the definition if they are added the result becomes a polynomial and not a monomial thus raise valueerror in that case def __eq__ self other monomial bool return true if two monomials are equal upto a scalar multiple def __mul__ self other union int float fraction monomial monomial multiply two monomials and merge the variables in both of them examples monomial 1 1 monomial 1 3 2 1 a_1 2 a_2 monomial 3 2 2 5 5 2 a_3 2 def inverse self monomial compute the inverse of a monomial examples monomial 1 1 2 1 3 2 2 5 inverse monomial 1 1 2 1 3 2 2 5 def __truediv__ self other union int float fraction monomial monomial compute the division between two monomials or a monomial and some other datatype like int float fraction def __floordiv__ self other union int float fraction monomial monomial for monomials floor div is the same as true div def clone self monomial clone the monomial def clean self monomial clean the monomial by dropping any variables that have power 0 def __sub__ self other union int float fraction monomial monomial compute the subtraction of a monomial and a datatype such as int float fraction or monomial define the hash of a monomial by the underlying variables if hashing is implemented in o v log v where v represents the number of variables in the monomial then search queries for the purposes of simplification of a polynomial can be performed in o v log v as well much better than the length of the polynomial get the set of all variables present in the monomial substitute the variables in the monomial for values defined by the substitutions dictionary get a string representation of the monomial a simple implementation of a polynomial class that records the details about two polynomials that are potentially comprised of multiple variables create a polynomial in the given variables examples polynomial monomial 1 1 2 monomial 2 3 1 1 1 math pi fraction 1 2 a_1 2 1 a_2 3 a_1 1 2 6415926536 polynomial 0 a helper for converting numbers to fraction only when possible def __add__ self other union int float fraction monomial polynomial polynomial add a given poylnomial to a copy of self def __sub__ self other union int float fraction monomial polynomial polynomial subtract the given polynomial from a copy of self def __mul__ self other union int float fraction monomial polynomial polynomial multiply a given polynomial to a copy of self def __floordiv__ self other union int float fraction monomial polynomial polynomial for polynomials floordiv is the same as truediv def __truediv__ self other union int float fraction monomial polynomial polynomial for polynomials only division by a monomial is defined todo implement polynomial polynomial def clone self polynomial clone the polynomial get all the variables present in this polynomials res sort get the monomials of this polynomial return true if the other polynomial is the same as this get the value after substituting certain values for the variables defined in substitutions get a string representation of the polynomial | from fractions import Fraction
from typing import Dict, Union, Set, Iterable
from numbers import Rational
from functools import reduce
class Monomial:
def __init__(self, variables: Dict[int, int], coeff: Union[int, float, Fraction, None]= None) -> None:
self.variables = dict()
if coeff is None:
if len(variables) == 0:
coeff = Fraction(0, 1)
else:
coeff = Fraction(1, 1)
elif coeff == 0:
self.coeff = Fraction(0, 1)
return
if len(variables) == 0:
self.coeff = Monomial._rationalize_if_possible(coeff)
return
for i in variables:
if variables[i] != 0:
self.variables[i] = variables[i]
self.coeff = Monomial._rationalize_if_possible(coeff)
@staticmethod
def _rationalize_if_possible(num):
if isinstance(num, Rational):
res = Fraction(num, 1)
return Fraction(res.numerator, res.denominator)
else:
return num
def equal_upto_scalar(self, other) -> bool:
if not isinstance(other, Monomial):
raise ValueError('Can only compare monomials.')
return other.variables == self.variables
def __add__(self, other: Union[int, float, Fraction]):
if isinstance(other, int) or isinstance(other, float) or isinstance(other, Fraction):
return self.__add__(Monomial({}, Monomial._rationalize_if_possible(other)))
if not isinstance(other, Monomial):
raise ValueError('Can only add monomials, ints, floats, or Fractions.')
if self.variables == other.variables:
mono = {i: self.variables[i] for i in self.variables}
return Monomial(mono, Monomial._rationalize_if_possible(self.coeff + other.coeff)).clean()
raise ValueError(f'Cannot add {str(other)} to {self.__str__()} because they don\'t have same variables.')
def __eq__(self, other) -> bool:
return self.equal_upto_scalar(other) and self.coeff == other.coeff
def __mul__(self, other: Union[int, float, Fraction]):
if isinstance(other, float) or isinstance(other, int) or isinstance(other, Fraction):
mono = {i: self.variables[i] for i in self.variables}
return Monomial(mono, Monomial._rationalize_if_possible(self.coeff * other)).clean()
if not isinstance(other, Monomial):
raise ValueError('Can only multiply monomials, ints, floats, or Fractions.')
else:
mono = {i: self.variables[i] for i in self.variables}
for i in other.variables:
if i in mono:
mono[i] += other.variables[i]
else:
mono[i] = other.variables[i]
temp = dict()
for k in mono:
if mono[k] != 0:
temp[k] = mono[k]
return Monomial(temp, Monomial._rationalize_if_possible(self.coeff * other.coeff)).clean()
def inverse(self):
mono = {i: self.variables[i] for i in self.variables if self.variables[i] != 0}
for i in mono:
mono[i] *= -1
if self.coeff == 0:
raise ValueError("Coefficient must not be 0.")
return Monomial(mono, Monomial._rationalize_if_possible(1/self.coeff)).clean()
def __truediv__(self, other: Union[int, float, Fraction]):
if isinstance(other, int) or isinstance(other, float) or isinstance(other, Fraction):
mono = {i: self.variables[i] for i in self.variables}
if other == 0:
raise ValueError('Cannot divide by 0.')
return Monomial(mono, Monomial._rationalize_if_possible(self.coeff / other)).clean()
o = other.inverse()
return self.__mul__(o)
def __floordiv__(self, other: Union[int, float, Fraction]):
return self.__truediv__(other)
def clone(self):
temp_variables = {i: self.variables[i] for i in self.variables}
return Monomial(temp_variables, Monomial._rationalize_if_possible(self.coeff)).clean()
def clean(self):
temp_variables = {i: self.variables[i] for i in self.variables if self.variables[i] != 0}
return Monomial(temp_variables, Monomial._rationalize_if_possible(self.coeff))
def __sub__(self, other: Union[int, float, Fraction]):
if isinstance(other, int) or isinstance(other, float) or isinstance(other, Fraction):
mono = {i: self.variables[i] for i in self.variables if self.variables[i] != 0}
if len(mono) != 0:
raise ValueError('Can only subtract like monomials.')
other_term = Monomial(mono, Monomial._rationalize_if_possible(other))
return self.__sub__(other_term)
if not isinstance(other, Monomial):
raise ValueError('Can only subtract monomials')
return self.__add__(other.__mul__(Fraction(-1, 1)))
def __hash__(self) -> int:
arr = []
for i in sorted(self.variables):
if self.variables[i] > 0:
for _ in range(self.variables[i]):
arr.append(i)
return hash(tuple(arr))
def all_variables(self) -> Set:
return set(sorted(self.variables.keys()))
def substitute(self, substitutions: Union[int, float, Fraction, Dict[int, Union[int, float, Fraction]]]) -> Fraction:
if isinstance(substitutions, int) or isinstance(substitutions, float) or isinstance(substitutions, Fraction):
substitutions = {v: Monomial._rationalize_if_possible(substitutions) for v in self.all_variables()}
else:
if not self.all_variables().issubset(set(substitutions.keys())):
raise ValueError('Some variables didn\'t receive their values.')
if self.coeff == 0:
return Fraction(0, 1)
ans = Monomial._rationalize_if_possible(self.coeff)
for k in self.variables:
ans *= Monomial._rationalize_if_possible(substitutions[k]**self.variables[k])
return Monomial._rationalize_if_possible(ans)
def __str__(self) -> str:
if len(self.variables) == 0:
return str(self.coeff)
result = str(self.coeff)
result += '('
for i in self.variables:
temp = 'a_{}'.format(str(i))
if self.variables[i] > 1:
temp = '(' + temp + ')**{}'.format(self.variables[i])
elif self.variables[i] < 0:
temp = '(' + temp + ')**(-{})'.format(-self.variables[i])
elif self.variables[i] == 0:
continue
else:
temp = '(' + temp + ')'
result += temp
return result + ')'
class Polynomial:
def __init__(self, monomials: Iterable[Union[int, float, Fraction, Monomial]]) -> None:
self.monomials = set()
for m in monomials:
if any(map(lambda x: isinstance(m, x), [int, float, Fraction])):
self.monomials |= {Monomial({}, m)}
elif isinstance(m, Monomial):
self.monomials |= {m}
else:
raise ValueError('Iterable should have monomials, int, float, or Fraction.')
self.monomials -= {Monomial({}, 0)}
@staticmethod
def _rationalize_if_possible(num):
if isinstance(num, Rational):
res = Fraction(num, 1)
return Fraction(res.numerator, res.denominator)
else:
return num
def __add__(self, other: Union[int, float, Fraction, Monomial]):
if isinstance(other, int) or isinstance(other, float) or isinstance(other, Fraction):
return self.__add__(Monomial({}, Polynomial._rationalize_if_possible(other)))
elif isinstance(other, Monomial):
monos = {m.clone() for m in self.monomials}
for _own_monos in monos:
if _own_monos.equal_upto_scalar(other):
scalar = _own_monos.coeff
monos -= {_own_monos}
temp_variables = {i: other.variables[i] for i in other.variables}
monos |= {Monomial(temp_variables, Polynomial._rationalize_if_possible(scalar + other.coeff))}
return Polynomial([z for z in monos])
monos |= {other.clone()}
return Polynomial([z for z in monos])
elif isinstance(other, Polynomial):
temp = list(z for z in {m.clone() for m in self.all_monomials()})
p = Polynomial(temp)
for o in other.all_monomials():
p = p.__add__(o.clone())
return p
else:
raise ValueError('Can only add int, float, Fraction, Monomials, or Polynomials to Polynomials.')
def __sub__(self, other: Union[int, float, Fraction, Monomial]):
if isinstance(other, int) or isinstance(other, float) or isinstance(other, Fraction):
return self.__sub__(Monomial({}, Polynomial._rationalize_if_possible(other)))
elif isinstance(other, Monomial):
monos = {m.clone() for m in self.all_monomials()}
for _own_monos in monos:
if _own_monos.equal_upto_scalar(other):
scalar = _own_monos.coeff
monos -= {_own_monos}
temp_variables = {i: other.variables[i] for i in other.variables}
monos |= {Monomial(temp_variables, Polynomial._rationalize_if_possible(scalar - other.coeff))}
return Polynomial([z for z in monos])
to_insert = other.clone()
to_insert.coeff *= -1
monos |= {to_insert}
return Polynomial([z for z in monos])
elif isinstance(other, Polynomial):
p = Polynomial(list(z for z in {m.clone() for m in self.all_monomials()}))
for o in other.all_monomials():
p = p.__sub__(o.clone())
return p
else:
raise ValueError('Can only subtract int, float, Fraction, Monomials, or Polynomials from Polynomials.')
return
def __mul__(self, other: Union[int, float, Fraction, Monomial]):
if isinstance(other, int) or isinstance(other, float) or isinstance(other, Fraction):
result = Polynomial([])
monos = {m.clone() for m in self.all_monomials()}
for m in monos:
result = result.__add__(m.clone()*other)
return result
elif isinstance(other, Monomial):
result = Polynomial([])
monos = {m.clone() for m in self.all_monomials()}
for m in monos:
result = result.__add__(m.clone() * other)
return result
elif isinstance(other, Polynomial):
temp_self = {m.clone() for m in self.all_monomials()}
temp_other = {m.clone() for m in other.all_monomials()}
result = Polynomial([])
for i in temp_self:
for j in temp_other:
result = result.__add__(i * j)
return result
else:
raise ValueError('Can only multiple int, float, Fraction, Monomials, or Polynomials with Polynomials.')
def __floordiv__(self, other: Union[int, float, Fraction, Monomial]):
return self.__truediv__(other)
def __truediv__(self, other: Union[int, float, Fraction, Monomial]):
if isinstance(other, int) or isinstance(other, float) or isinstance(other, Fraction):
return self.__truediv__( Monomial({}, other) )
elif isinstance(other, Monomial):
poly_temp = reduce(lambda acc, val: acc + val, map(lambda x: x / other, [z for z in self.all_monomials()]), Polynomial([Monomial({}, 0)]))
return poly_temp
elif isinstance(other, Polynomial):
if Monomial({}, 0) in other.all_monomials():
if len(other.all_monomials()) == 2:
temp_set = {x for x in other.all_monomials() if x != Monomial({}, 0)}
only = temp_set.pop()
return self.__truediv__(only)
elif len(other.all_monomials()) == 1:
temp_set = {x for x in other.all_monomials()}
only = temp_set.pop()
return self.__truediv__(only)
raise ValueError('Can only divide a polynomial by an int, float, Fraction, or a Monomial.')
return
def clone(self):
return Polynomial(list({m.clone() for m in self.all_monomials()}))
def variables(self) -> Set:
res = set()
for i in self.all_monomials():
res |= {j for j in i.variables}
res = list(res)
return set(res)
def all_monomials(self) -> Iterable[Monomial]:
return {m for m in self.monomials if m != Monomial({}, 0)}
def __eq__(self, other) -> bool:
if isinstance(other, int) or isinstance(other, float) or isinstance(other, Fraction):
other_poly = Polynomial([Monomial({}, other)])
return self.__eq__(other_poly)
elif isinstance(other, Monomial):
return self.__eq__(Polynomial([other]))
elif isinstance(other, Polynomial):
return self.all_monomials() == other.all_monomials()
else:
raise ValueError('Can only compare a polynomial with an int, float, Fraction, Monomial, or another Polynomial.')
def subs(self, substitutions: Union[int, float, Fraction, Dict[int, Union[int, float, Fraction]]]) -> Union[int, float, Fraction]:
if isinstance(substitutions, int) or isinstance(substitutions, float) or isinstance(substitutions, Fraction):
substitutions = {i: Polynomial._rationalize_if_possible(substitutions) for i in set(self.variables())}
return self.subs(substitutions)
elif not isinstance(substitutions, dict):
raise ValueError('The substitutions should be a dictionary.')
if not self.variables().issubset(set(substitutions.keys())):
raise ValueError('Some variables didn\'t receive their values.')
ans = 0
for m in self.all_monomials():
ans += Polynomial._rationalize_if_possible(m.substitute(substitutions))
return Polynomial._rationalize_if_possible(ans)
def __str__(self) -> str:
return ' + '.join(str(m) for m in self.all_monomials() if m.coeff != Fraction(0, 1)) |
performs exponentiation similarly to the builtin pow or functions allows also for calculating the exponentiation modulo iterative version of binary exponentiation calculate a n if mod is specified return the result modulo mod time complexity ologn space complexity o1 recursive version of binary exponentiation calculate a n if mod is specified return the result modulo mod time complexity ologn space complexity ologn iterative version of binary exponentiation calculate a n if mod is specified return the result modulo mod time complexity o log n space complexity o 1 recursive version of binary exponentiation calculate a n if mod is specified return the result modulo mod time complexity o log n space complexity o log n | def power(a: int, n: int, mod: int = None):
ans = 1
while n:
if n & 1:
ans = ans * a
a = a * a
if mod:
ans %= mod
a %= mod
n >>= 1
return ans
def power_recur(a: int, n: int, mod: int = None):
if n == 0:
ans = 1
elif n == 1:
ans = a
else:
ans = power_recur(a, n // 2, mod)
ans = ans * ans
if n % 2:
ans = ans * a
if mod:
ans %= mod
return ans |
return true if n is a prime number else return false return true if n is a prime number else return false | def prime_check(n):
if n <= 1:
return False
if n == 2 or n == 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
j = 5
while j * j <= n:
if n % j == 0 or n % (j + 2) == 0:
return False
j += 6
return True |
return list of all primes less than n using sieve of eratosthenes modification we don t need to check all even numbers we can make the sieve excluding even numbers and adding 2 to the primes list by default we are going to make an array of x 2 1 if number is even else x 2 the 1 with even number it s to exclude the number itself because we just need numbers from 3 x if x is odd we can get value represented at index i with i2 3 for example for x 10 we start with an array of x 2 1 4 1 1 1 1 3 5 7 9 for x 11 1 1 1 1 1 3 5 7 9 11 11 is odd it s included in the list with this we have reduced the array size to a half and complexity it s also a half now return list of all primes less than n using sieve of eratosthenes if x is even exclude x from list 1 return list of all primes less than n using sieve of eratosthenes if x is even exclude x from list 1 sieve list of primes 2 is prime by default | def get_primes(n):
if n <= 0:
raise ValueError("'n' must be a positive integer.")
sieve_size = (n // 2 - 1) if n % 2 == 0 else (n // 2)
sieve = [True for _ in range(sieve_size)]
primes = []
if n >= 2:
primes.append(2)
for i in range(sieve_size):
if sieve[i]:
value_at_i = i*2 + 3
primes.append(value_at_i)
for j in range(i, sieve_size, value_at_i):
sieve[j] = False
return primes |
given the lengths of two of the three sides of a right angled triangle this function returns the length of the third side returns length of a third side of a right angled triangle passing will indicate the unknown side returns length of a third side of a right angled triangle passing will indicate the unknown side | def pythagoras(opposite, adjacent, hypotenuse):
try:
if opposite == str("?"):
return ("Opposite = " + str(((hypotenuse**2) - (adjacent**2))**0.5))
if adjacent == str("?"):
return ("Adjacent = " + str(((hypotenuse**2) - (opposite**2))**0.5))
if hypotenuse == str("?"):
return ("Hypotenuse = " + str(((opposite**2) + (adjacent**2))**0.5))
return "You already know the answer!"
except:
raise ValueError("invalid argument(s) were given.") |
rabinmiller primality test returning false implies that n is guaranteed composite returning true means that n is probably prime with a 4 k chance of being wrong factor n into a power of 2 times an odd number power 0 while num 2 0 num 2 power 1 return power num def validwitnessa x powinta intd intn if x 1 or x n 1 return false for in ranger 1 x powintx int2 intn if x 1 return true if x n 1 return false return true precondition n 5 if n 5 return n 2 or n 3 true for prime r d pow2factorn 1 for in rangek if validwitnessrandom randrange2 n 2 return false return true factor n into a power of 2 times an odd number returns true if a is a valid witness for n a valid witness increases chances of n being prime an invalid witness guarantees n is composite precondition n 5 true for prime | import random
def is_prime(n, k):
def pow2_factor(num):
power = 0
while num % 2 == 0:
num /= 2
power += 1
return power, num
def valid_witness(a):
x = pow(int(a), int(d), int(n))
if x == 1 or x == n - 1:
return False
for _ in range(r - 1):
x = pow(int(x), int(2), int(n))
if x == 1:
return True
if x == n - 1:
return False
return True
if n < 5:
return n == 2 or n == 3
r, d = pow2_factor(n - 1)
for _ in range(k):
if valid_witness(random.randrange(2, n - 2)):
return False
return True |
calculates the binomial coefficient cn k with nk using recursion time complexity is ok so can calculate fairly quickly for large values of k recursivebinomialcoefficient5 0 1 recursivebinomialcoefficient8 2 28 recursivebinomialcoefficient500 300 5054949849935535817667719165973249533761635252733275327088189563256013971725761702359997954491403585396607971745777019273390505201262259748208640 function is only defined for nk cn 0 cn n 1 so this is our base case cn k cn nk so if n2 is sufficiently small we can reduce the problem size else we know cn k nkcn1 k1 so we can use this to reduce our problem size calculates the binomial coefficient c n k with n k using recursion time complexity is o k so can calculate fairly quickly for large values of k recursive_binomial_coefficient 5 0 1 recursive_binomial_coefficient 8 2 28 recursive_binomial_coefficient 500 300 5054949849935535817667719165973249533761635252733275327088189563256013971725761702359997954491403585396607971745777019273390505201262259748208640 function is only defined for n k c n 0 c n n 1 so this is our base case c n k c n n k so if n 2 is sufficiently small we can reduce the problem size else we know c n k n k c n 1 k 1 so we can use this to reduce our problem size | def recursive_binomial_coefficient(n,k):
if k>n:
raise ValueError('Invalid Inputs, ensure that n >= k')
if k == 0 or n == k:
return 1
if k > n/2:
return recursive_binomial_coefficient(n,n-k)
return int((n/k)*recursive_binomial_coefficient(n-1,k-1)) |
rsa encryption algorithm a method for encrypting a number that uses seperate encryption and decryption keys this file only implements the key generation algorithm there are three important numbers in rsa called n e and d e is called the encryption exponent d is called the decryption exponent n is called the modulus these three numbers satisfy x e d n x n to use this system for encryption n and e are made publicly available and d is kept secret a number x can be encrypted by computing x e n the original number can then be recovered by computing e d n where e is the encrypted number fortunately python provides a three argument version of pow that can compute powers modulo a number very quickly a b c powa b c sample usage n e d generatekey16 data 20 encrypted powdata e n decrypted powencrypted d n assert decrypted data the rsa key generating algorithm k is the number of bits in n calculate the inverse of a mod m that is find b such that a b m 1 b 1 while not a b m 1 b 1 return b def genprimek seednone size in bits of p and q need to add up to the size of n sample usage n e d generate_key 16 data 20 encrypted pow data e n decrypted pow encrypted d n assert decrypted data the rsa key generating algorithm k is the number of bits in n calculate the inverse of a mod m that is find b such that a b m 1 generate a prime with k bits size in bits of p and q need to add up to the size of n in many cases e is also chosen to be a small constant calculate totient function | import random
def generate_key(k, seed=None):
def modinv(a, m):
b = 1
while not (a * b) % m == 1:
b += 1
return b
def gen_prime(k, seed=None):
def is_prime(num):
if num == 2:
return True
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
random.seed(seed)
while True:
key = random.randrange(int(2 ** (k - 1)), int(2 ** k))
if is_prime(key):
return key
p_size = k / 2
q_size = k - p_size
e = gen_prime(k, seed)
while True:
p = gen_prime(p_size, seed)
if p % e != 1:
break
while True:
q = gen_prime(q_size, seed)
if q % e != 1:
break
n = p * q
l = (p - 1) * (q - 1)
d = modinv(e, l)
return int(n), int(e), int(d)
def encrypt(data, e, n):
return pow(int(data), int(e), int(n))
def decrypt(data, d, n):
return pow(int(data), int(d), int(n)) |
given a positive integer n and a precision factor p it produces an output with a maximum error p from the actual square root of n example given n 5 and p 0 001 can produce output x such that 2 235 x 2 237 actual square root of 5 being 2 236 return square root of n with maximum absolute error epsilon guess n 2 while absguess guess n epsilon guess guess n guess 2 return guess return square root of n with maximum absolute error epsilon | def square_root(n, epsilon=0.001):
guess = n / 2
while abs(guess * guess - n) > epsilon:
guess = (guess + (n / guess)) / 2
return guess |
recently i encountered an interview question whose description was as below the number 89 is the first integer with more than one digit whose digits when raised up to consecutive powers give the same number for example 89 81 92 gives the number 89 the next number after 89 with this property is 135 11 32 53 135 write a function that returns a list of numbers with the above property the function will receive range as parameter some test cases set to 1 set to 1 parse the string into individual digits some test cases | def sum_dig_pow(low, high):
result = []
for number in range(low, high + 1):
exponent = 1
summation = 0
number_as_string = str(number)
tokens = list(map(int, number_as_string))
for k in tokens:
summation = summation + (k ** exponent)
exponent += 1
if summation == number:
result.append(number)
return result
assert sum_dig_pow(1, 10) == [1, 2, 3, 4, 5, 6, 7, 8, 9]
assert sum_dig_pow(1, 100) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 89] |
the significance of the cycle index polynomial of symmetry group is deeply rooted in counting the number of configurations of an object excluding those that are symmetric in terms of permutations for example the following problem can be solved as a direct application of the cycle index polynomial of the symmetry group note i came across this problem as a google s foo bar challenge at level 5 and solved it using a purely group theoretic approach problem given positive integers w h and s compute the number of distinct 2d grids of dimensions w x h that contain entries from 0 1 s1 note that two grids are defined to be equivalent if one can be obtained from the other by switching rows and columns some number of times approach compute the cycle index polynomials of sw and sh i e the symmetry group on w and h symbols respectively compute the product of the two cycle indices while combining two monomials in such a way that for any pair of cycles c1 and c2 in the elements of sw x sh the resultant monomial contains terms of the form xlcmc1 c2gcdc1 c2 return the specialization of the product of cycle indices at xi s for all the valid i code def solvew h s s1 getcycleindexsymw s2 getcycleindexsymh result cycleproductfortwopolynomialss1 s2 s return strresult given two monomials from the cycle index of a symmetry group compute the resultant monomial in the cartesian product corresponding to their merging compute the product of given cycle indices p1 and p2 and evaluate it at q a helper for the dpstyle evaluation of the cycle index the recurrence is given in https en wikipedia orgwikicycleindexsymmetricgroupsn compute the cycle index of sn i e the symmetry group of n symbols given two monomials from the cycle index of a symmetry group compute the resultant monomial in the cartesian product corresponding to their merging compute the product of given cycle indices p1 and p2 and evaluate it at q a helper for the dp style evaluation of the cycle index the recurrence is given in https en wikipedia org wiki cycle_index symmetric_group_sn compute the cycle index of s_n i e the symmetry group of n symbols | from fractions import Fraction
from typing import Dict, Union
from polynomial import ( Monomial, Polynomial )
from gcd import lcm
def cycle_product(m1: Monomial, m2: Monomial) -> Monomial:
assert isinstance(m1, Monomial) and isinstance(m2, Monomial)
A = m1.variables
B = m2.variables
result_variables = dict()
for i in A:
for j in B:
k = lcm(i, j)
g = (i * j) // k
if k in result_variables:
result_variables[k] += A[i] * B[j] * g
else:
result_variables[k] = A[i] * B[j] * g
return Monomial(result_variables, Fraction(m1.coeff * m2.coeff, 1))
def cycle_product_for_two_polynomials(p1: Polynomial, p2: Polynomial, q: Union[float, int, Fraction]) -> Union[float, int, Fraction]:
ans = Fraction(0, 1)
for m1 in p1.monomials:
for m2 in p2.monomials:
ans += cycle_product(m1, m2).substitute(q)
return ans
def cycle_index_sym_helper(n: int, memo: Dict[int, Polynomial]) -> Polynomial:
if n in memo:
return memo[n]
ans = Polynomial([Monomial({}, Fraction(0, 1))])
for t in range(1, n+1):
ans = ans.__add__(Polynomial([Monomial({t: 1}, Fraction(1, 1))]) * cycle_index_sym_helper(n-t, memo))
ans *= Fraction(1, n)
memo[n] = ans
return memo[n]
def get_cycle_index_sym(n: int) -> Polynomial:
if n < 0:
raise ValueError('n should be a non-negative integer.')
memo = {
0: Polynomial([
Monomial({}, Fraction(1, 1))
]),
1: Polynomial([
Monomial({1: 1}, Fraction(1, 1))
]),
2: Polynomial([
Monomial({1: 2}, Fraction(1, 2)),
Monomial({2: 1}, Fraction(1, 2))
]),
3: Polynomial([
Monomial({1: 3}, Fraction(1, 6)),
Monomial({1: 1, 2: 1}, Fraction(1, 2)),
Monomial({3: 1}, Fraction(1, 3))
]),
4: Polynomial([
Monomial({1: 4}, Fraction(1, 24)),
Monomial({2: 1, 1: 2}, Fraction(1, 4)),
Monomial({3: 1, 1: 1}, Fraction(1, 3)),
Monomial({2: 2}, Fraction(1, 8)),
Monomial({4: 1}, Fraction(1, 4)),
])
}
result = cycle_index_sym_helper(n, memo)
return result |
given a 2d grid each cell is either a wall w an enemy e or empty 0 the number zero return the maximum enemies you can kill using one bomb the bomb kills all the enemies in the same row and column from the planted point until it hits the wall since the wall is too strong to be destroyed note that you can only put the bomb at an empty cell example for the given grid 0 e 0 0 e 0 w e 0 e 0 0 return 3 placing a bomb at 1 1 kills 3 enemies iterates over all cells in the grid makes sure we are next to a wall makes sure we are next to a wall makes sure the cell contains a 0 updates the variable calculate killed enemies for row i from column j calculate killed enemies for column j from row i tests testsuite for the project iterates over all cells in the grid makes sure we are next to a wall makes sure we are next to a wall makes sure the cell contains a 0 updates the variable calculate killed enemies for row i from column j calculate killed enemies for column j from row i tests testsuite for the project | def max_killed_enemies(grid):
if not grid:
return 0
m, n = len(grid), len(grid[0])
max_killed = 0
row_e, col_e = 0, [0] * n
for i in range(m):
for j in range(n):
if j == 0 or grid[i][j-1] == 'W':
row_e = row_kills(grid, i, j)
if i == 0 or grid[i-1][j] == 'W':
col_e[j] = col_kills(grid, i, j)
if grid[i][j] == '0':
max_killed = max(max_killed, row_e + col_e[j])
return max_killed
def row_kills(grid, i, j):
num = 0
len_row = len(grid[0])
while j < len_row and grid[i][j] != 'W':
if grid[i][j] == 'E':
num += 1
j += 1
return num
def col_kills(grid, i, j):
num = 0
len_col = len(grid)
while i < len_col and grid[i][j] != 'W':
if grid[i][j] == 'E':
num += 1
i += 1
return num
import unittest
class TestBombEnemy(unittest.TestCase):
def test_3x4(self):
grid1 = [["0", "E", "0", "0"],
["E", "0", "W", "E"],
["0", "E", "0", "0"]]
self.assertEqual(3, max_killed_enemies(grid1))
def test_4x4(self):
grid1 = [
["0", "E", "0", "E"],
["E", "E", "E", "0"],
["E", "0", "W", "E"],
["0", "E", "0", "0"]]
grid2 = [
["0", "0", "0", "E"],
["E", "0", "0", "0"],
["E", "0", "W", "E"],
["0", "E", "0", "0"]]
self.assertEqual(5, max_killed_enemies(grid1))
self.assertEqual(3, max_killed_enemies(grid2))
if __name__ == "__main__":
unittest.main() |
cholesky matrix decomposition is used to find the decomposition of a hermitian positivedefinite matrix a into matrix v so that v v a where v denotes the conjugate transpose of l the dimensions of the matrix a must match this method is mainly used for numeric solution of linear equations ax b example input matrix a 4 12 16 12 37 43 16 43 98 result 2 0 0 0 0 0 6 0 1 0 0 0 8 0 5 0 3 0 time complexity of this algorithm is on3 specifically about n33 param a hermitian positivedefinite matrix of type listlistfloat return matrix of type listlistfloat if a can be decomposed otherwise none param a hermitian positive definite matrix of type list list float return matrix of type list list float if a can be decomposed otherwise none | import math
def cholesky_decomposition(A):
n = len(A)
for ai in A:
if len(ai) != n:
return None
V = [[0.0] * n for _ in range(n)]
for j in range(n):
sum_diagonal_element = 0
for k in range(j):
sum_diagonal_element = sum_diagonal_element + math.pow(V[j][k], 2)
sum_diagonal_element = A[j][j] - sum_diagonal_element
if sum_diagonal_element <= 0:
return None
V[j][j] = math.pow(sum_diagonal_element, 0.5)
for i in range(j+1, n):
sum_other_element = 0
for k in range(j):
sum_other_element += V[i][k]*V[j][k]
V[i][j] = (A[i][j] - sum_other_element)/V[j][j]
return V |
count the number of unique paths from a00 to am1n1 we are allowed to move either right or down from a cell in the matrix approaches i recursion recurse starting from am1n1 upwards and leftwards add the path count of both recursions and return count ii dynamic programming start from a00 store the count in a count matrix return countm1n1 tn omn sn omn taking care of the edge cases matrix of size 1xn or mx1 number of ways to reach aij number of ways to reach ai1j aij1 count the number of unique paths from a 0 0 to a m 1 n 1 we are allowed to move either right or down from a cell in the matrix approaches i recursion recurse starting from a m 1 n 1 upwards and leftwards add the path count of both recursions and return count ii dynamic programming start from a 0 0 store the count in a count matrix return count m 1 n 1 t n o mn s n o mn taking care of the edge cases matrix of size 1xn or mx1 number of ways to reach a i j number of ways to reach a i 1 j a i j 1 | def count_paths(m, n):
if m < 1 or n < 1:
return -1
count = [[None for j in range(n)] for i in range(m)]
for i in range(n):
count[0][i] = 1
for j in range(m):
count[j][0] = 1
for i in range(1, m):
for j in range(1, n):
count[i][j] = count[i - 1][j] + count[i][j - 1]
print(count[m - 1][n - 1])
def main():
m, n = map(int, input('Enter two positive integers: ').split())
count_paths(m, n)
if __name__ == '__main__':
main() |
crout matrix decomposition is used to find two matrices that when multiplied give our input matrix so l u a l stands for lower and l has nonzero elements only on diagonal and below u stands for upper and u has nonzero elements only on diagonal and above this can for example be used to solve systems of linear equations the last if is used if to avoid dividing by zero example we input the a matrix 1 2 3 3 4 5 6 7 8 we get l 1 0 0 0 0 0 3 0 2 0 0 0 6 0 5 0 0 0 u 1 0 2 0 3 0 0 0 1 0 2 0 0 0 0 0 1 0 we can check that l u a i think the complexity should be on3 | def crout_matrix_decomposition(A):
n = len(A)
L = [[0.0] * n for i in range(n)]
U = [[0.0] * n for i in range(n)]
for j in range(n):
U[j][j] = 1.0
for i in range(j, n):
alpha = float(A[i][j])
for k in range(j):
alpha -= L[i][k]*U[k][j]
L[i][j] = float(alpha)
for i in range(j+1, n):
tempU = float(A[j][i])
for k in range(j):
tempU -= float(L[j][k]*U[k][i])
if int(L[j][j]) == 0:
L[j][j] = float(0.1**40)
U[j][i] = float(tempU/L[j][j])
return (L, U) |
multiplies two square matrices mata and matb of size n x n time complexity on3 returns the identity matrix of size n x n time complexity on2 calculates matn by repeated squaring time complexity od3 logn d dimension of the square matrix mat n power the matrix is raised to multiplies two square matrices mata and matb of size n x n time complexity o n 3 returns the identity matrix of size n x n time complexity o n 2 calculates mat n by repeated squaring time complexity o d 3 log n d dimension of the square matrix mat n power the matrix is raised to | def multiply(matA: list, matB: list) -> list:
n = len(matA)
matC = [[0 for i in range(n)] for j in range(n)]
for i in range(n):
for j in range(n):
for k in range(n):
matC[i][j] += matA[i][k] * matB[k][j]
return matC
def identity(n: int) -> list:
I = [[0 for i in range(n)] for j in range(n)]
for i in range(n):
I[i][i] = 1
return I
def matrix_exponentiation(mat: list, n: int) -> list:
if n == 0:
return identity(len(mat))
elif n % 2 == 1:
return multiply(matrix_exponentiation(mat, n - 1), mat)
else:
tmp = matrix_exponentiation(mat, n // 2)
return multiply(tmp, tmp) |
inverts an invertible n x n matrix i e given an n x n matrix a returns an n x n matrix b such that ab ba in the n x n identity matrix for a 2 x 2 matrix inversion is simple using the cofactor equation for larger matrices this is a four step process 1 calculate the matrix of minors create an n x n matrix by considering each position in the original matrix in turn exclude the current row and column and calculate the determinant of the remaining matrix then place that value in the current position s equivalent in the matrix of minors 2 create the matrix of cofactors take the matrix of minors and multiply alternate values by 1 in a checkerboard pattern 3 adjugate hold the top left to bottom right diagonal constant but swap all other values over it 4 multiply the adjugated matrix by 1 the determinant of the original matrix this code combines steps 1 and 2 into one method to reduce traversals of the matrix possible edge cases will not work for 0x0 or 1x1 matrix though these are trivial to calculate without use of this file invert an n x n matrix error conditions if not arrayismatrixm printinvalid matrix array is not a matrix return 1 elif lenm lenm0 printinvalid matrix matrix is not square return 2 elif lenm 2 printinvalid matrix matrix is too small return 3 elif getdeterminantm 0 printinvalid matrix matrix is square but singular determinant 0 return 4 calculation elif lenm 2 simple case multiplier 1 getdeterminantm inverted multiplier lenm for n in rangelenm inverted01 inverted01 1 m01 inverted10 inverted10 1 m10 inverted00 multiplier m11 inverted11 multiplier m00 return inverted else get matrix of minors w checkerboard signs calculate determinant we need to know 1det adjugate swap on diagonals and multiply by 1det recursively calculate the determinant of an n x n matrix n 2 if lenm 2 trivial case return m00 m11 m01 m10 else sign 1 det 0 for i in rangelenm det sign m0i getdeterminantgetminorm 0 i sign 1 return det def getmatrixofminorsm get the minor of the matrix position mrowcol all values mrc where r row and c col swap values along diagonal optionally adding multiplier for row in rangelenm for col in rangerow 1 temp mrowcol multiplier mrowcol mcolrow multiplier mcolrow temp return m def arrayismatrixm if lenm 0 return false firstcol lenm0 for row in m if lenrow firstcol return false return true invert an n x n matrix error conditions calculation simple case some steps combined in helpers to reduce traversals get matrix of minors w checkerboard signs calculate determinant we need to know 1 det adjugate swap on diagonals and multiply by 1 det recursively calculate the determinant of an n x n matrix n 2 trivial case get the matrix of minors and alternate signs get the minor of the matrix position m row col all values m r c where r row and c col swap values along diagonal optionally adding multiplier | import fractions
def invert_matrix(m):
if not array_is_matrix(m):
print("Invalid matrix: array is not a matrix")
return [[-1]]
elif len(m) != len(m[0]):
print("Invalid matrix: matrix is not square")
return [[-2]]
elif len(m) < 2:
print("Invalid matrix: matrix is too small")
return [[-3]]
elif get_determinant(m) == 0:
print("Invalid matrix: matrix is square, but singular (determinant = 0)")
return [[-4]]
elif len(m) == 2:
multiplier = 1 / get_determinant(m)
inverted = [[multiplier] * len(m) for n in range(len(m))]
inverted[0][1] = inverted[0][1] * -1 * m[0][1]
inverted[1][0] = inverted[1][0] * -1 * m[1][0]
inverted[0][0] = multiplier * m[1][1]
inverted[1][1] = multiplier * m[0][0]
return inverted
else:
m_of_minors = get_matrix_of_minors(m)
multiplier = fractions.Fraction(1, get_determinant(m))
inverted = transpose_and_multiply(m_of_minors, multiplier)
return inverted
def get_determinant(m):
if len(m) == 2:
return (m[0][0] * m[1][1]) - (m[0][1] * m[1][0])
else:
sign = 1
det = 0
for i in range(len(m)):
det += sign * m[0][i] * get_determinant(get_minor(m, 0, i))
sign *= -1
return det
def get_matrix_of_minors(m):
matrix_of_minors = [[0 for i in range(len(m))] for j in range(len(m))]
for row in range(len(m)):
for col in range(len(m[0])):
if (row + col) % 2 == 0:
sign = 1
else:
sign = -1
matrix_of_minors[row][col] = sign * get_determinant(get_minor(m, row, col))
return matrix_of_minors
def get_minor(m, row, col):
minors = []
for i in range(len(m)):
if i != row:
new_row = m[i][:col]
new_row.extend(m[i][col + 1:])
minors.append(new_row)
return minors
def transpose_and_multiply(m, multiplier=1):
for row in range(len(m)):
for col in range(row + 1):
temp = m[row][col] * multiplier
m[row][col] = m[col][row] * multiplier
m[col][row] = temp
return m
def array_is_matrix(m):
if len(m) == 0:
return False
first_col = len(m[0])
for row in m:
if len(row) != first_col:
return False
return True |
this algorithm takes two compatible two dimensional matrix and return their product space complexity on2 possible edge case the number of columns of multiplicand not consistent with the number of rows of multiplier will raise exception type a listlistint type b listlistint rtype listlistint create a result matrix type a list list int type b list list int rtype list list int create a result matrix | def multiply(multiplicand: list, multiplier: list) -> list:
multiplicand_row, multiplicand_col = len(
multiplicand), len(multiplicand[0])
multiplier_row, multiplier_col = len(multiplier), len(multiplier[0])
if(multiplicand_col != multiplier_row):
raise Exception(
"Multiplicand matrix not compatible with Multiplier matrix.")
result = [[0] * multiplier_col for i in range(multiplicand_row)]
for i in range(multiplicand_row):
for j in range(multiplier_col):
for k in range(len(multiplier)):
result[i][j] += multiplicand[i][k] * multiplier[k][j]
return result |
you are given an n x n 2d mat representing an image rotate the image by 90 degrees clockwise follow up could you do this inplace clockwise rotate first reverse up to down then swap the symmetry 1 2 3 7 8 9 7 4 1 4 5 6 4 5 6 8 5 2 7 8 9 1 2 3 9 6 3 clockwise rotate first reverse up to down then swap the symmetry 1 2 3 7 8 9 7 4 1 4 5 6 4 5 6 8 5 2 7 8 9 1 2 3 9 6 3 | def rotate(mat):
if not mat:
return mat
mat.reverse()
for i in range(len(mat)):
for j in range(i):
mat[i][j], mat[j][i] = mat[j][i], mat[i][j]
return mat
if __name__ == "__main__":
mat = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
print(mat)
rotate(mat)
print(mat) |
search a key in a row wise and column wise sorted nondecreasing matrix m number of rows in the matrix n number of columns in the matrix tn omn search a key in a row wise and column wise sorted non decreasing matrix m number of rows in the matrix n number of columns in the matrix t n o m n | def search_in_a_sorted_matrix(mat, m, n, key):
i, j = m-1, 0
while i >= 0 and j < n:
if key == mat[i][j]:
print('Key %s found at row- %s column- %s' % (key, i+1, j+1))
return
if key < mat[i][j]:
i -= 1
else:
j += 1
print('Key %s not found' % (key))
def main():
mat = [
[2, 5, 7],
[4, 8, 13],
[9, 11, 15],
[12, 17, 20]
]
key = 13
print(mat)
search_in_a_sorted_matrix(mat, len(mat), len(mat[0]), key)
if __name__ == '__main__':
main() |
given a m n matrix mat of integers sort it diagonally in ascending order from the topleft to the bottomright then return the sorted array mat 3 3 1 1 2 2 1 2 1 1 1 2 should return 1 1 1 1 1 2 2 2 1 2 3 3 if the input is a vector return the vector rows columns 1 the 1 helps you to not repeat a column process the rows initialize heap set row and column traverse diagonally and add the values to the heap sort the diagonal process the columns initialize heap row and column traverse diagonally sort the diagonal return the updated matrix if the input is a vector return the vector rows columns 1 the 1 helps you to not repeat a column process the rows initialize heap set row and column traverse diagonally and add the values to the heap sort the diagonal process the columns initialize heap row and column traverse diagonally sort the diagonal return the updated matrix | from heapq import heappush, heappop
from typing import List
def sort_diagonally(mat: List[List[int]]) -> List[List[int]]:
if len(mat) == 1 or len(mat[0]) == 1:
return mat
for i in range(len(mat)+len(mat[0])-1):
if i+1 < len(mat):
h = []
row = len(mat)-(i+1)
col = 0
while row < len(mat):
heappush(h, (mat[row][col]))
row += 1
col += 1
row = len(mat)-(i+1)
col = 0
while h:
ele = heappop(h)
mat[row][col] = ele
row += 1
col += 1
else:
h = []
row = 0
col = i - (len(mat)-1)
while col < len(mat[0]) and row < len(mat):
heappush(h, (mat[row][col]))
row += 1
col += 1
row = 0
col = i - (len(mat)-1)
while h:
ele = heappop(h)
mat[row][col] = ele
row += 1
col += 1
return mat |
usrbinenv python3 suppose we have very large sparse vectors which contains a lot of zeros and double find a data structure to store them get the dot product of them 10 usr bin env python3 suppose we have very large sparse vectors which contains a lot of zeros and double find a data structure to store them get the dot product of them 10 | def vector_to_index_value_list(vector):
return [(i, v) for i, v in enumerate(vector) if v != 0.0]
def dot_product(iv_list1, iv_list2):
product = 0
p1 = len(iv_list1) - 1
p2 = len(iv_list2) - 1
while p1 >= 0 and p2 >= 0:
i1, v1 = iv_list1[p1]
i2, v2 = iv_list2[p2]
if i1 < i2:
p1 -= 1
elif i2 < i1:
p2 -= 1
else:
product += v1 * v2
p1 -= 1
p2 -= 1
return product
def __test_simple():
print(dot_product(vector_to_index_value_list([1., 2., 3.]),
vector_to_index_value_list([0., 2., 2.])))
def __test_time():
vector_length = 1024
vector_count = 1024
nozero_counut = 10
def random_vector():
import random
vector = [0 for _ in range(vector_length)]
for i in random.sample(range(vector_length), nozero_counut):
vector[i] = random.random()
return vector
vectors = [random_vector() for _ in range(vector_count)]
iv_lists = [vector_to_index_value_list(vector) for vector in vectors]
import time
time_start = time.time()
for i in range(vector_count):
for j in range(i):
dot_product(iv_lists[i], iv_lists[j])
time_end = time.time()
print(time_end - time_start, 'seconds')
if __name__ == '__main__':
__test_simple()
__test_time() |
given two sparse matrices a and b return the result of ab you may assume that a s column number is equal to b s row number example a 1 0 0 1 0 3 b 7 0 0 0 0 0 0 0 1 1 0 0 7 0 0 7 0 0 ab 1 0 3 x 0 0 0 7 0 3 0 0 1 python solution without table 156ms type a listlistint type b listlistint rtype listlistint python solution with only one table for b 196ms type a listlistint type b listlistint rtype listlistint python solution with two tables 196ms type a listlistint type b listlistint rtype listlistint python solution without table 156ms type a list list int type b list list int rtype list list int python solution with only one table for b 196ms type a list list int type b list list int rtype list list int python solution with two tables 196ms type a list list int type b list list int rtype list list int | def multiply(self, a, b):
if a is None or b is None:
return None
m, n, l = len(a), len(b[0]), len(b[0])
if len(b) != n:
raise Exception("A's column number must be equal to B's row number.")
c = [[0 for _ in range(l)] for _ in range(m)]
for i, row in enumerate(a):
for k, eleA in enumerate(row):
if eleA:
for j, eleB in enumerate(b[k]):
if eleB:
c[i][j] += eleA * eleB
return c
def multiply(self, a, b):
if a is None or b is None:
return None
m, n, l = len(a), len(a[0]), len(b[0])
if len(b) != n:
raise Exception("A's column number must be equal to B's row number.")
c = [[0 for _ in range(l)] for _ in range(m)]
table_b = {}
for k, row in enumerate(b):
table_b[k] = {}
for j, eleB in enumerate(row):
if eleB:
table_b[k][j] = eleB
for i, row in enumerate(a):
for k, eleA in enumerate(row):
if eleA:
for j, eleB in table_b[k].iteritems():
c[i][j] += eleA * eleB
return c
def multiply(self, a, b):
if a is None or b is None:
return None
m, n = len(a), len(b[0])
if len(b) != n:
raise Exception("A's column number must be equal to B's row number.")
l = len(b[0])
table_a, table_b = {}, {}
for i, row in enumerate(a):
for j, ele in enumerate(row):
if ele:
if i not in table_a:
table_a[i] = {}
table_a[i][j] = ele
for i, row in enumerate(b):
for j, ele in enumerate(row):
if ele:
if i not in table_b:
table_b[i] = {}
table_b[i][j] = ele
c = [[0 for j in range(l)] for i in range(m)]
for i in table_a:
for k in table_a[i]:
if k not in table_b:
continue
for j in table_b[k]:
c[i][j] += table_a[i][k] * table_b[k][j]
return c |
given a matrix of m x n elements m rows n columns return all elements of the matrix in spiral order for example given the following matrix 1 2 3 4 5 6 7 8 9 you should return 1 2 3 6 9 8 7 4 5 | def spiral_traversal(matrix):
res = []
if len(matrix) == 0:
return res
row_begin = 0
row_end = len(matrix) - 1
col_begin = 0
col_end = len(matrix[0]) - 1
while row_begin <= row_end and col_begin <= col_end:
for i in range(col_begin, col_end+1):
res.append(matrix[row_begin][i])
row_begin += 1
for i in range(row_begin, row_end+1):
res.append(matrix[i][col_end])
col_end -= 1
if row_begin <= row_end:
for i in range(col_end, col_begin-1, -1):
res.append(matrix[row_end][i])
row_end -= 1
if col_begin <= col_end:
for i in range(row_end, row_begin-1, -1):
res.append(matrix[i][col_begin])
col_begin += 1
return res
if __name__ == "__main__":
mat = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
print(spiral_traversal(mat)) |
write a function validsolutionvalidatesolutionvalidsolution that accepts a 2d array representing a sudoku board and returns true if it is a valid solution or false otherwise the cells of the sudoku board may also contain 0 s which will represent empty cells boards containing one or more zeroes are considered to be invalid solutions the board is always 9 cells by 9 cells and every cell only contains integers from 0 to 9 more info at http en wikipedia orgwikisudoku using dicthashtable without hashtabledict check rows check columns check regions if everything correct using set using dict hash table without hash table dict check rows check columns check regions if everything correct using set | from collections import defaultdict
def valid_solution_hashtable(board):
for i in range(len(board)):
dict_row = defaultdict(int)
dict_col = defaultdict(int)
for j in range(len(board[0])):
value_row = board[i][j]
value_col = board[j][i]
if not value_row or value_col == 0:
return False
if value_row in dict_row:
return False
else:
dict_row[value_row] += 1
if value_col in dict_col:
return False
else:
dict_col[value_col] += 1
for i in range(3):
for j in range(3):
grid_add = 0
for k in range(3):
for l in range(3):
grid_add += board[i * 3 + k][j * 3 + l]
if grid_add != 45:
return False
return True
def valid_solution(board):
correct = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for row in board:
if sorted(row) != correct:
return False
for column in zip(*board):
if sorted(column) != correct:
return False
for i in range(3):
for j in range(3):
region = []
for line in board[i*3:(i+1)*3]:
region += line[j*3:(j+1)*3]
if sorted(region) != correct:
return False
return True
def valid_solution_set(board):
valid = set(range(1, 10))
for row in board:
if set(row) != valid:
return False
for col in [[row[i] for row in board] for i in range(9)]:
if set(col) != valid:
return False
for x in range(3):
for y in range(3):
if set(sum([row[x*3:(x+1)*3] for row in board[y*3:(y+1)*3]], [])) != valid:
return False
return True |
function to find sum of all subsquares of size k x k in a given square matrix of size n x n calculate and print sum of current subsquare function to find sum of all sub squares of size k x k in a given square matrix of size n x n calculate and print sum of current sub square | def sum_sub_squares(matrix, k):
n = len(matrix)
result = [[0 for i in range(k)] for j in range(k)]
if k > n:
return
for i in range(n - k + 1):
l = 0
for j in range(n - k + 1):
sum = 0
for p in range(i, k + i):
for q in range(j, k + j):
sum += matrix[p][q]
result[i][l] = sum
l += 1
return result |
summary helperfunction calculates the eulidean distance between vector x and y arguments x tuple vector y tuple vector summary implements the nearest neighbor algorithm arguments x tupel vector tset dict training set returns type result of the andfunction summary helper function calculates the eulidean distance between vector x and y arguments x tuple vector y tuple vector summary implements the nearest neighbor algorithm arguments x tupel vector tset dict training set returns type result of the and function | import math
def distance(x,y):
assert len(x) == len(y), "The vector must have same length"
result = ()
sum = 0
for i in range(len(x)):
result += (x[i] -y[i],)
for component in result:
sum += component**2
return math.sqrt(sum)
def nearest_neighbor(x, tSet):
assert isinstance(x, tuple) and isinstance(tSet, dict)
current_key = ()
min_d = float('inf')
for key in tSet:
d = distance(x, key)
if d < min_d:
min_d = d
current_key = key
return tSet[current_key] |
given an array and a number k find the max elements of each of its subarrays of length k keep indexes of good candidates in deque d the indexes in d are from the current window they re increasing and their corresponding nums are decreasing then the first deque element is the index of the largest window value for each index i 1 pop from the end indexes of smaller elements they ll be useless 2 append the current index 3 pop from the front the index i k if it s still in the deque it falls out of the window 4 if our window has reached size k append the current window maximum to the output queue storing indexes of elements | import collections
def max_sliding_window(arr, k):
qi = collections.deque()
result = []
for i, n in enumerate(arr):
while qi and arr[qi[-1]] < n:
qi.pop()
qi.append(i)
if qi[0] == i - k:
qi.popleft()
if i >= k - 1:
result.append(arr[qi[0]])
return result |
initialize your data structure here type size int type val int rtype float given a stream of integers and a window size calculate the moving average of all integers in the sliding window initialize your data structure here type size int type val int rtype float given a stream of integers and a window size calculate the moving average of all integers in the sliding window | from __future__ import division
from collections import deque
class MovingAverage(object):
def __init__(self, size):
self.queue = deque(maxlen=size)
def next(self, val):
self.queue.append(val)
return sum(self.queue) / len(self.queue)
if __name__ == '__main__':
m = MovingAverage(3)
assert m.next(1) == 1
assert m.next(10) == (1 + 10) / 2
assert m.next(3) == (1 + 10 + 3) / 3
assert m.next(5) == (10 + 3 + 5) / 3 |
implementation of priority queue using linear array insertion on extract minmax node o1 create a priority queue with items list or iterable if items is not passed create empty priority queue self priorityqueuelist if items is none return if priorities is none priorities itertools repeatnone for item priority in zipitems priorities self pushitem prioritypriority def reprself return priorityqueue r formatself priorityqueuelist def sizeself return lenself priorityqueuelist def pushself item prioritynone priority item if priority is none else priority node priorityqueuenodeitem priority for index current in enumerateself priorityqueuelist if current priority node priority self priorityqueuelist insertindex node return when traversed complete queue self priorityqueuelist appendnode def popself remove and return the first node from the queue return self priorityqueuelist pop data create a priority queue with items list or iterable if items is not passed create empty priority queue return size of the priority queue push the item in the priority queue if priority is not given priority is set to the value of item when traversed complete queue remove and return the item with the lowest priority remove and return the first node from the queue | import itertools
class PriorityQueueNode:
def __init__(self, data, priority):
self.data = data
self.priority = priority
def __repr__(self):
return "{}: {}".format(self.data, self.priority)
class PriorityQueue:
def __init__(self, items=None, priorities=None):
self.priority_queue_list = []
if items is None:
return
if priorities is None:
priorities = itertools.repeat(None)
for item, priority in zip(items, priorities):
self.push(item, priority=priority)
def __repr__(self):
return "PriorityQueue({!r})".format(self.priority_queue_list)
def size(self):
return len(self.priority_queue_list)
def push(self, item, priority=None):
priority = item if priority is None else priority
node = PriorityQueueNode(item, priority)
for index, current in enumerate(self.priority_queue_list):
if current.priority < node.priority:
self.priority_queue_list.insert(index, node)
return
self.priority_queue_list.append(node)
def pop(self):
return self.priority_queue_list.pop().data |
queue abstract data type adt queue creates a new queue that is empty it needs no parameters and returns an empty queue enqueueitem adds a new item to the rear of the queue it needs the item and returns nothing dequeue removes the front item from the queue it needs no parameters and returns the item the queue is modified isempty tests to see whether the queue is empty it needs no parameters and returns a boolean value size returns the number of items in the queue it needs no parameters and returns an integer peek returns the front element of the queue initialize python list with capacity of 10 or user given input python list type is a dynamic array so we have to restrict its dynamic nature to make it work like a static array returns the front element of queue if self isempty raise indexerrorqueue is empty return self arrayself front def expandself self array none lenself array class queuenode def initself value self value value self next none class linkedlistqueueabstractqueue def initself super init self front none self rear none def iterself probe self front while true if probe is none return yield probe value probe probe next def enqueueself value node queuenodevalue if self front is none self front node self rear node else self rear next node self rear node self size 1 def dequeueself if self isempty raise indexerrorqueue is empty value self front value if self front is self rear self front none self rear none else self front self front next self size 1 return value def peekself initialize python list with capacity of 10 or user given input python list type is a dynamic array so we have to restrict its dynamic nature to make it work like a static array returns the front element of queue expands size of the array time complexity o n returns the front element of queue | from abc import ABCMeta, abstractmethod
class AbstractQueue(metaclass=ABCMeta):
def __init__(self):
self._size = 0
def __len__(self):
return self._size
def is_empty(self):
return self._size == 0
@abstractmethod
def enqueue(self, value):
pass
@abstractmethod
def dequeue(self):
pass
@abstractmethod
def peek(self):
pass
@abstractmethod
def __iter__(self):
pass
class ArrayQueue(AbstractQueue):
def __init__(self, capacity=10):
super().__init__()
self._array = [None] * capacity
self._front = 0
self._rear = 0
def __iter__(self):
probe = self._front
while True:
if probe == self._rear:
return
yield self._array[probe]
probe += 1
def enqueue(self, value):
if self._rear == len(self._array):
self._expand()
self._array[self._rear] = value
self._rear += 1
self._size += 1
def dequeue(self):
if self.is_empty():
raise IndexError("Queue is empty")
value = self._array[self._front]
self._array[self._front] = None
self._front += 1
self._size -= 1
return value
def peek(self):
if self.is_empty():
raise IndexError("Queue is empty")
return self._array[self._front]
def _expand(self):
self._array += [None] * len(self._array)
class QueueNode:
def __init__(self, value):
self.value = value
self.next = None
class LinkedListQueue(AbstractQueue):
def __init__(self):
super().__init__()
self._front = None
self._rear = None
def __iter__(self):
probe = self._front
while True:
if probe is None:
return
yield probe.value
probe = probe.next
def enqueue(self, value):
node = QueueNode(value)
if self._front is None:
self._front = node
self._rear = node
else:
self._rear.next = node
self._rear = node
self._size += 1
def dequeue(self):
if self.is_empty():
raise IndexError("Queue is empty")
value = self._front.value
if self._front is self._rear:
self._front = None
self._rear = None
else:
self._front = self._front.next
self._size -= 1
return value
def peek(self):
if self.is_empty():
raise IndexError("Queue is empty")
return self._front.value |
suppose you have a random list of people standing in a queue each person is described by a pair of integers h k where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h write an algorithm to reconstruct the queue note the number of people is less than 1 100 example input 7 0 4 4 7 1 5 0 6 1 5 2 output 5 0 7 0 5 2 6 1 4 4 7 1 type people listlistint rtype listlistint suppose you have a random list of people standing in a queue each person is described by a pair of integers h k where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h write an algorithm to reconstruct the queue note the number of people is less than 1 100 example input 7 0 4 4 7 1 5 0 6 1 5 2 output 5 0 7 0 5 2 6 1 4 4 7 1 type people list list int rtype list list int | def reconstruct_queue(people):
queue = []
people.sort(key=lambda x: (-x[0], x[1]))
for h, k in people:
queue.insert(k, [h, k])
return queue |
initialize your data structure here type v1 listint type v2 listint rtype int rtype bool initialize your data structure here type v1 list int type v2 list int rtype int rtype bool | class ZigZagIterator:
def __init__(self, v1, v2):
self.queue = [_ for _ in (v1, v2) if _]
print(self.queue)
def next(self):
v = self.queue.pop(0)
ret = v.pop(0)
if v:
self.queue.append(v)
return ret
def has_next(self):
if self.queue:
return True
return False
l1 = [1, 2]
l2 = [3, 4, 5, 6]
it = ZigZagIterator(l1, l2)
while it.has_next():
print(it.next()) |