Prompt
stringlengths
16
11.5k
Completions
stringlengths
84
25.3k
These are classes to represent a Graph and its elements. It can be shared across graph algorithms. A nodevertex in a graph. Return the name of the node A directed edge in a directed graph. Stores the source and target node of the edge. A directed graph. Stores a set of nodes, edges and adjacency matrix. pylint: disabledangerousdefaultvalue Add a new named node to the graph. Add a new edge to the graph between two nodes.
class Node: """ A node/vertex in a graph. """ def __init__(self, name): self.name = name @staticmethod def get_name(obj): """ Return the name of the node """ if isinstance(obj, Node): return obj.name if isinstance(obj, str): return obj return'' def __eq__(self, obj): return self.name == self.get_name(obj) def __repr__(self): return self.name def __hash__(self): return hash(self.name) def __ne__(self, obj): return self.name != self.get_name(obj) def __lt__(self, obj): return self.name < self.get_name(obj) def __le__(self, obj): return self.name <= self.get_name(obj) def __gt__(self, obj): return self.name > self.get_name(obj) def __ge__(self, obj): return self.name >= self.get_name(obj) def __bool__(self): return self.name class DirectedEdge: """ A directed edge in a directed graph. Stores the source and target node of the edge. """ def __init__(self, node_from, node_to): self.source = node_from self.target = node_to def __eq__(self, obj): if isinstance(obj, DirectedEdge): return obj.source == self.source and obj.target == self.target return False def __repr__(self): return f"({self.source} -> {self.target})" class DirectedGraph: """ A directed graph. Stores a set of nodes, edges and adjacency matrix. """ # pylint: disable=dangerous-default-value def __init__(self, load_dict={}): self.nodes = [] self.edges = [] self.adjacency_list = {} if load_dict and isinstance(load_dict, dict): for vertex in load_dict: node_from = self.add_node(vertex) self.adjacency_list[node_from] = [] for neighbor in load_dict[vertex]: node_to = self.add_node(neighbor) self.adjacency_list[node_from].append(node_to) self.add_edge(vertex, neighbor) def add_node(self, node_name): """ Add a new named node to the graph. """ try: return self.nodes[self.nodes.index(node_name)] except ValueError: node = Node(node_name) self.nodes.append(node) return node def add_edge(self, node_name_from, node_name_to): """ Add a new edge to the graph between two nodes. """ try: node_from = self.nodes[self.nodes.index(node_name_from)] node_to = self.nodes[self.nodes.index(node_name_to)] self.edges.append(DirectedEdge(node_from, node_to)) except ValueError: pass
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
import random def __choose_state(state_map): """ Choose the next state randomly """ 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): """ Given a markov-chain, randomly chooses the next state given the current state. """ next_state_map = chain.get(current_state) return __choose_state(next_state_map) def iterating_markov_chain(chain, state): """ Yield a sequence of states given a markov chain and the initial 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.
from queue import Queue # pylint: disable=too-many-arguments def dfs(capacity, flow, visit, vertices, idx, sink, current_flow = 1 << 63): """ Depth First Search implementation for Ford-Fulkerson algorithm. """ # DFS function for ford_fulkerson algorithm. 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): """ 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. """ 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): """ 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. """ 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)) # Finds new flow using BFS. 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 # Update flow array following parent starting from 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): """ BFS function for Dinic algorithm. Check whether sink is reachable only using edges that is not full. """ 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): """ DFS function for Dinic algorithm. Finds new flow using edges that is not full. """ 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): """ 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. """ 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
import copy import queue import math def maximum_flow_bfs(adjacency_matrix): """ Get the maximum flow through a graph using a breadth first search """ #initial setting new_array = copy.deepcopy(adjacency_matrix) total = 0 while True: #setting min to max_value min_flow = math.inf #save visited nodes visited = [0]*len(new_array) #save parent nodes path = [0]*len(new_array) #initialize queue for BFS bfs = queue.Queue() #initial setting visited[0] = 1 bfs.put(0) #BFS to find path while bfs.qsize() > 0: #pop from queue src = bfs.get() for k in range(len(new_array)): #checking capacity and visit if(new_array[src][k] > 0 and visited[k] == 0 ): #if not, put into queue and chage to visit and save path visited[k] = 1 bfs.put(k) path[k] = src #if there is no path from src to sink if visited[len(new_array) - 1] == 0: break #initial setting tmp = len(new_array) - 1 #Get minimum flow while tmp != 0: #find minimum flow if min_flow > new_array[path[tmp]][tmp]: min_flow = new_array[path[tmp]][tmp] tmp = path[tmp] #initial setting tmp = len(new_array) - 1 #reduce capacity 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
import copy import math def maximum_flow_dfs(adjacency_matrix): """ Get the maximum flow through a graph using a depth first search """ #initial setting new_array = copy.deepcopy(adjacency_matrix) total = 0 while True: #setting min to max_value min = math.inf #save visited nodes visited = [0]*len(new_array) #save parent nodes path = [0]*len(new_array) #initialize stack for DFS stack = [] #initial setting visited[0] = 1 stack.append(0) #DFS to find path while len(stack) > 0: #pop from queue src = stack.pop() for k in range(len(new_array)): #checking capacity and visit if new_array[src][k] > 0 and visited[k] == 0: #if not, put into queue and chage to visit and save path visited[k] = 1 stack.append(k) path[k] = src #if there is no path from src to sink if visited[len(new_array) - 1] == 0: break #initial setting tmp = len(new_array) - 1 #Get minimum flow while tmp != 0: #find minimum flow if min > new_array[path[tmp]][tmp]: min = new_array[path[tmp]][tmp] tmp = path[tmp] #initial setting tmp = len(new_array) - 1 #reduce capacity 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:
import sys # pylint: disable=too-few-public-methods class Edge: """ An edge of an undirected graph """ def __init__(self, source, target, weight): self.source = source self.target = target self.weight = weight class DisjointSet: """ 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 """ def __init__(self, size): """ Args: n (int): Number of vertices in the graph """ self.parent = [None] * size # Contains wich node is the parent of the node at poisition <i> self.size = [1] * size # Contains size of node at index <i>, used to optimize merge for i in range(size): self.parent[i] = i # Make all nodes his own parent, creating n sets. def merge_set(self, node1, node2): """ 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) node1 = self.find_set(node1) node2 = self.find_set(node2) # Join the shortest node to the longest, minimizing tree size (faster find) if self.size[node1] < self.size[node2]: self.parent[node1] = node2 # Merge set(a) and set(b) self.size[node2] += self.size[node1] # Add size of old set(a) to set(b) else: self.parent[node2] = node1 # Merge set(b) and set(a) self.size[node1] += self.size[node2] # Add size of old set(b) to set(a) def find_set(self, node): """ Get the root element of the set containing <a> """ if self.parent[node] != node: # Very important, memoize result of the # recursion in the list to optimize next # calls and make this operation practically constant, O(1) self.parent[node] = self.find_set(self.parent[node]) # node <a> it's the set root, so we can return that index return self.parent[node] def kruskal(vertex_count, edges, forest): """ 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. """ edges.sort(key=lambda edge: edge.weight) mst = [] # List of edges taken, minimum spanning tree for edge in edges: set_u = forest.find_set(edge.u) # Set of the node <u> set_v = forest.find_set(edge.v) # Set of the node <v> if set_u != set_v: forest.merge_set(set_u, set_v) mst.append(edge) if len(mst) == vertex_count-1: # If we have selected n-1 edges, all the other # edges will be discarted, so, we can stop here break return sum([edge.weight for edge in mst]) def main(): """ 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 """ for size in sys.stdin: vertex_count, edge_count = map(int, size.split()) forest = DisjointSet(edge_count) edges = [None] * edge_count # Create list of size <m> # Read <m> edges from input for i in range(edge_count): source, target, weight = map(int, input().split()) source -= 1 # Convert from 1-indexed to 0-indexed target -= 1 # Convert from 1-indexed to 0-indexed edges[i] = Edge(source, target, weight) # After finish input and graph creation, use Kruskal algorithm for MST: 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
from collections import defaultdict class Graph: """ A directed 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): """ Add a new directed edge to the graph """ self.graph[source].append(target) def dfs(self,source,target): """ Determine if there is a path from source to target using a depth first search """ visited = [False] * self.vertex_count self.dfsutil(visited,source,target,) def dfsutil(self,visited,source,target): """ 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 """ 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): """ Determine if there is a path from source to 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
import heapq # for priority queue def prims_minimum_spanning(graph_used): """ Prim's algorithm to find weight of minimum spanning tree """ 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
def dfs_transposed(vertex, graph, order, visited): """ 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. """ 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): """ 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. """ 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): """ Add a directed edge to the graph. """ if vertex_from not in graph: graph[vertex_from] = [] graph[vertex_from].append(vertex_to) def scc(graph): ''' Computes the strongly connected components of a 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]: # Each dfs will visit exactly one component dfs(vertex, current_comp, vertex_scc, graph, visited) current_comp += 1 return vertex_scc def build_graph(formula): ''' Builds the implication graph from the 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): """ Solves the 2-SAT problem """ graph = build_graph(formula) vertex_scc = scc(graph) for (var, _) in graph: if vertex_scc[(var, False)] == vertex_scc[(var, True)]: return None # The formula is contradictory comp_repr = {} # An arbitrary representant from each component for vertex in graph: if not vertex_scc[vertex] in comp_repr: comp_repr[vertex_scc[vertex]] = vertex comp_value = {} # True/False value for each strongly connected component 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(): """ Entry point for testing """ 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
from algorithms.graph.graph import DirectedGraph # pylint: disable=too-few-public-methods class Tarjan: """ A directed graph used for finding strongly connected components """ def __init__(self, dict_graph): self.graph = DirectedGraph(dict_graph) self.index = 0 self.stack = [] # Runs Tarjan # Set all node index to None 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): """ 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 vertex.index = self.index vertex.lowlink = self.index self.index += 1 self.stack.append(vertex) vertex.on_stack = True # Consider successors of v for adjacent in self.graph.adjacency_list[vertex]: if adjacent.index is None: # Successor w has not yet been visited; recurse on it self.strongconnect(adjacent, sccs) vertex.lowlink = min(vertex.lowlink, adjacent.lowlink) elif adjacent.on_stack: # 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 vertex.lowlink = min(vertex.lowlink, adjacent.index) # If v is a root node, pop the stack and generate an SCC if vertex.lowlink == vertex.index: # start a new strongly connected component 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
class Graph: """ This class represents a directed graph using adjacency lists """ def __init__(self, vertices): # No. of vertices self.vertex_count = vertices # default dictionary to store graph self.graph = {} # To store transitive closure self.closure = [[0 for j in range(vertices)] for i in range(vertices)] def add_edge(self, source, target): """ Adds a directed edge to the graph """ if source in self.graph: self.graph[source].append(target) else: self.graph[source] = [target] def dfs_util(self, source, target): """ A recursive DFS traversal function that finds all reachable vertices for source """ # Mark reachability from source to target as true. self.closure[source][target] = 1 # Find all the vertices reachable through target for adjacent in self.graph[target]: if self.closure[source][adjacent] == 0: self.dfs_util(source, adjacent) def transitive_closure(self): """ 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 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. # def dfs_traverse(graph, start): """ Traversal by depth first search. """ 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): """ Traversal by breadth first search. """ 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): """ Traversal by recursive depth first search. """ 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
from abc import ABCMeta, abstractmethod class AbstractHeapmetaclassABCMeta: Pass. abstractmethod def percupself, i: Pass. abstractmethod def percdownself, i: Pass. abstractmethod def removeminself: Binary Heap Class def initself: self.currentsize 0 self.heap 0 def percupself, i: while i 2 0: if self.heapi self.heapi 2: Swap value of child with value of its parent self.heapi, self.heapi2 self.heapi2, self.heapi i i 2 def insertself, val: self.heap.appendval self.currentsize self.currentsize 1 self.percupself.currentsize def minchildself, i: if 2 i 1 self.currentsize: No right child return 2 i if self.heap2 i self.heap2 i 1: return 2 i 1 return 2 i def percdownself, i: while 2 i self.currentsize: minchild self.minchildi if self.heapminchild self.heapi: Swap min child with parent self.heapminchild, self.heapi self.heapi, self.heapminchild i minchild def removeminself: ret self.heap1 the smallest value at beginning Replace it by the last value self.heap1 self.heapself.currentsize self.currentsize self.currentsize 1 self.heap.pop self.percdown1 return ret
r""" Binary Heap. A min heap is a complete binary tree where each node is smaller than its children. The root, therefore, is the minimum element in the tree. The min heap uses an array to represent the data and operation. For example a min heap: 4 / \ 50 7 / \ / 55 90 87 Heap [0, 4, 50, 7, 55, 90, 87] Method in class: insert, remove_min For example insert(2) in a min heap: 4 4 2 / \ / \ / \ 50 7 --> 50 2 --> 50 4 / \ / \ / \ / \ / \ / \ 55 90 87 2 55 90 87 7 55 90 87 7 For example remove_min() in a min heap: 4 87 7 / \ / \ / \ 50 7 --> 50 7 --> 50 87 / \ / / \ / \ 55 90 87 55 90 55 90 """ from abc import ABCMeta, abstractmethod class AbstractHeap(metaclass=ABCMeta): """Abstract Class for Binary Heap.""" def __init__(self): """Pass.""" @abstractmethod def perc_up(self, i): """Pass.""" @abstractmethod def insert(self, val): """Pass.""" @abstractmethod def perc_down(self, i): """Pass.""" @abstractmethod def min_child(self, i): """Pass.""" @abstractmethod def remove_min(self): """Pass.""" class BinaryHeap(AbstractHeap): """Binary Heap Class""" def __init__(self): self.current_size = 0 self.heap = [(0)] def perc_up(self, i): while i // 2 > 0: if self.heap[i] < self.heap[i // 2]: # Swap value of child with value of its parent self.heap[i], self.heap[i//2] = self.heap[i//2], self.heap[i] i = i // 2 def insert(self, val): """ Method insert always start by inserting the element at the bottom. It inserts rightmost spot so as to maintain the complete tree property. Then, it fixes the tree by swapping the new element with its parent, until it finds an appropriate spot for the element. It essentially perc_up the minimum element Complexity: O(logN) """ self.heap.append(val) self.current_size = self.current_size + 1 self.perc_up(self.current_size) """ Method min_child returns the index of smaller of 2 children of parent at index i """ def min_child(self, i): if 2 * i + 1 > self.current_size: # No right child return 2 * i if self.heap[2 * i] > self.heap[2 * i + 1]: return 2 * i + 1 return 2 * i def perc_down(self, i): while 2 * i < self.current_size: min_child = self.min_child(i) if self.heap[min_child] < self.heap[i]: # Swap min child with parent self.heap[min_child], self.heap[i] = self.heap[i], self.heap[min_child] i = min_child """ Remove Min method removes the minimum element and swap it with the last element in the heap( the bottommost, rightmost element). Then, it perc_down this element, swapping it with one of its children until the min heap property is restored Complexity: O(logN) """ def remove_min(self): ret = self.heap[1] # the smallest value at beginning # Replace it by the last value self.heap[1] = self.heap[self.current_size] self.current_size = self.current_size - 1 self.heap.pop() self.perc_down(1) return ret
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
from heapq import heapify, heappushpop def k_closest(points, k, origin=(0, 0)): # 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. """ heap = [(-distance(p, origin), p) for p in points[:k]] heapify(heap) """ 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. """ for point in points[k:]: dist = distance(point, origin) heappushpop(heap, (-dist, point)) # 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 [point for nd, point in heap] # return points in heap def distance(point, origin=(0, 0)): """ Calculates the distance for a point from origo""" 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
from heapq import heappop, heapreplace, heapify from queue import PriorityQueue # Definition for singly-linked list. class ListNode(object): """ ListNode Class""" def __init__(self, val): self.val = val self.next = None def merge_k_lists(lists): """ Merge 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) # only change heap size when necessary 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): """ Merge List """ 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] # These two lines seem to curr = curr.next # be equivalent to :- curr = q.get()[1] if curr.next: q.put((curr.next.val, curr.next)) return dummy.next """ 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 """
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], ...] """ import heapq def get_skyline(lrh): """ Wortst Time Complexity: O(NlogN) :type buildings: List[List[int]] :rtype: List[List[int]] """ 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
import collections def max_sliding_window(nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ 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
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: """ converts a positive integer into a (reversed) linked list. for example: give 112 result 2 -> 1 -> 1 """ 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: """ converts the non-negative number list into a string. """ result = "" while l: result += str(l.val) l = l.next return result class TestSuite(unittest.TestCase): """ testsuite for the linked list structure and the adding function, above. """ 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): # 1. test case 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) # 2. test case 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) # 3. test case number5 = Node(1) number6 = Node(0) result = convert_to_str(add_two_numbers(number5, number6)) self.assertEqual("1", result) # 4. test case 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
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): """ :type head: RandomListNode :rtype: RandomListNode """ 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) # O(n) def copy_random_pointer_v2(head): """ :type head: RandomListNode :rtype: RandomListNode """ 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
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): # make linkedlist 1 -> 2 -> 3 -> 4 head = Node(1) curr = head for i in range(2, 6): curr.next = Node(i) curr = curr.next # node3 = 3 node3 = head.next.next # after delete_node => 1 -> 2 -> 4 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
import unittest class Node: def __init__(self, x): self.val = x self.next = None def first_cyclic_node(head): """ :type head: Node :rtype: Node """ 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): # create linked list => A -> B -> C -> D -> E -> C 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
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): # We hit the end of one of the lists, set a flag for this flag = (count, h1.next, h2.next) if h1: h1 = h1.next if h2: h2 = h2.next long_len = count # Mark the length of the longer of the two lists 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: # force the longer of the two lists to "catch up" longer = longer.next long_len -= 1 if longer == shorter: # The nodes match, return the node return longer else: longer = longer.next shorter = shorter.next return None class TestSuite(unittest.TestCase): def test_intersection(self): # create linked list as: # 1 -> 3 -> 5 # \ # 7 -> 9 -> 11 # / # 2 -> 4 -> 6 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
class Node: def __init__(self, x): self.val = x self.next = None def is_cyclic(head): """ :type head: Node :rtype: bool """ 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.
def is_palindrome(head): if not head: return True # split the list to two parts fast, slow = head.next, head while fast and fast.next: fast = fast.next.next slow = slow.next second = slow.next slow.next = None # Don't forget here! But forget still works! # reverse the second part node = None while second: nxt = second.next second.next = node node = second second = nxt # compare two parts # second part has the same or one less node 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 # 1. Get the midpoint (slow) slow = fast = cur = head while fast and fast.next: fast, slow = fast.next.next, slow.next # 2. Push the second half into the stack stack = [slow.val] while slow.next: slow = slow.next stack.append(slow.val) # 3. Comparison while stack: if stack.pop() != cur.val: return False cur = cur.next return True def is_palindrome_dict(head): """ 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. """ 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
class Node(): def __init__(self, val=None): self.val = val self.next = None def kth_to_last_eval(head, k): """ 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 """ 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): """ 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 """ 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): """ 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. """ if not (head or k > -1): return False p1 = head p2 = head for i in range(1, k+1): if p1 is None: # Went too far, k is not valid 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(): # def make_test_li # A A B C D C F G 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) # test kth_to_last_eval 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 # test kth_to_last_dict 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 # test kth_to_last 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
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 # recursively 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
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 # cache previous value in case it needs to be pointed elsewhere 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
class Node(): def __init__(self, val = None): self.val = val self.next = None def remove_dups(head): """ Time Complexity: O(N) Space Complexity: O(N) """ 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): """ Time Complexity: O(N^2) Space Complexity: O(1) """ 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) # A A B C D C F G 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
def remove_range(head, start, end): assert(start <= end) # Case: remove node at head if start == 0: for i in range(0, end+1): if head != None: head = head.next else: current = head # Move pointer to start position for i in range(0,start-1): current = current.next # Remove data until the end 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) # def reverse_list(head): """ :type head: ListNode :rtype: ListNode """ 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 # # Recursive solution # T(n)- O(n) # def reverse_list_recursive(head): """ :type head: ListNode :rtype: ListNode """ 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 def rotate_right(head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ if not head or not head.next: return head current = head length = 1 # count length of the list while current.next: current = current.next length += 1 # make it circular current.next = head k = k % length # rotate until length-k 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
class HashTable(object): """ 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. """ _empty = object() _deleted = object() def __init__(self, size=11): self.size = size self._len = 0 self._keys = [self._empty] * size # keys self._values = [self._empty] * size # values 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: # can assign to hash_ index self._keys[hash_] = key self._values[hash_] = value self._len += 1 return elif self._keys[hash_] == key: # key already exists here, assign over self._keys[hash_] = key self._values[hash_] = value return hash_ = self._rehash(hash_) if initial_hash == hash_: # table is full raise ValueError("Table is full") def get(self, key): initial_hash = hash_ = self.hash(key) while True: if self._keys[hash_] is self._empty: # That key was never assigned return None elif self._keys[hash_] == key: # key found return self._values[hash_] hash_ = self._rehash(hash_) if initial_hash == hash_: # table is full and wrapped around return None def del_(self, key): initial_hash = hash_ = self.hash(key) while True: if self._keys[hash_] is self._empty: # That key was never assigned return None elif self._keys[hash_] == key: # key found, assign with deleted sentinel self._keys[hash_] = self._deleted self._values[hash_] = self._deleted self._len -= 1 return hash_ = self._rehash(hash_) if initial_hash == hash_: # table is full and wrapped around return None def hash(self, key): return key % self.size def _rehash(self, old_hash): """ linear probing """ 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) # increase size of dict * 2 if filled >= 2/3 size (like python dict) if len(self) >= (self.size * 2) / 3: self.__resize() def __resize(self): keys, values = self._keys, self._values self.size *= 2 # this will be the new size 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
def is_anagram(s, t): """ :type s: str :type t: str :rtype: bool """ 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
def is_isomorphic(s, t): """ :type s: str :type t: str :rtype: bool """ 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
def max_common_sub_string(s1, s2): # Assuming s2 has all unique chars 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
def longest_palindromic_subsequence(s): k = len(s) olist = [0] * k # 申请长度为n的列表,并初始化 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 # 当 j 时,第 i 个子串为回文子串 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]: # 当j-i>1时,判断s[i]是否等于s[j],并判断当j-1时,第i+1个子串是否为回文子串 nList[i] = 1 # 当 j 时,第 i 个子串为回文子串 len_t = j - i + 1 if logestLen < len_t: logestSubStr = s[i:j + 1] logestLen = len_t olist = nList # 覆盖旧的列表 nList = [0] * k # 新的列表清空 # ~ from icecream import ic # ~ ic(s, logestSubStr) return logestLen#, logestSubStr
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
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): """ 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 """ _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
import string def int_to_base(num, base): """ :type num: int :type base: int :rtype: str """ 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): """ Note : You can use int() built-in function instead of this. :type str_to_convert: str :type base: int :rtype: int """ 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
from typing import List from algorithms.maths.gcd import gcd def solve_chinese_remainder(nums : List[int], rems : List[int]): """ 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 """ 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:
def combination(n, r): """This function calculates nCr.""" if n == r or r == 0: return 1 return combination(n-1, r-1) + combination(n-1, r) def combination_memo(n, r): """This function calculates nCr using memoization method.""" 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
import math def _l2_distance(vec): """ Calculate l2 distance from two given vectors. """ norm = 0. for element in vec: norm += element * element norm = math.sqrt(norm) return norm def cosine_similarity(vec1, vec2): """ Calculate cosine similarity between given two vectors :type vec1: list :type vec2: list """ 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. # Calculate the dot product of two vectors 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
def decimal_to_binary_util(val): """ Convert 8-bit decimal number to binary representation :type val: str :rtype: str """ 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): """ Convert dotted-decimal ip address to binary representation with help of decimal_to_binary_util """ 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
import math from random import randint """ Code from /algorithms/maths/prime_check.py, written by 'goswami-rahul' and 'Hai Honag Dang' """ def prime_check(num): """Return True if num is a prime number Else return False. """ 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 """ 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. """ def find_order(a, n): if (a == 1) & (n == 1): # Exception Handeling : 1 is the order of of 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 """ 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' """ def euler_totient(n): """Euler's totient function or Phi function. Time Complexity: O(sqrt(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 """ 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. """ def find_primitive_root(n): """ Returns all primitive roots of n. """ if n == 1: # Exception Handeling : 0 is the only primitive root of 1 return [0] phi = euler_totient(n) p_root_list = [] for i in range (1, n): if math.gcd(i, n) != 1: # To have order, a and n must be relative prime with each other. continue order = find_order(i, n) if order == phi: p_root_list.append(i) return p_root_list """ 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. """ def alice_private_key(p): """Alice determine her private key in the range of 1 ~ p-1. This must be kept in secret""" return randint(1, p-1) def alice_public_key(a_pr_k, a, p): """Alice calculate her public key with her private key. This is open to public""" return pow(a, a_pr_k) % p def bob_private_key(p): """Bob determine his private key in the range of 1 ~ p-1. This must be kept in secret""" return randint(1, p-1) def bob_public_key(b_pr_k, a, p): """Bob calculate his public key with his private key. This is open to public""" return pow(a, b_pr_k) % p def alice_shared_key(b_pu_k, a_pr_k, p): """ Alice calculate secret key shared with Bob, with her private key and Bob's public key. This must be kept in secret""" return pow(b_pu_k, a_pr_k) % p def bob_shared_key(a_pu_k, b_pr_k, p): """ Bob calculate secret key shared with Alice, with his private key and Alice's public key. This must be kept in secret""" return pow(a_pu_k, b_pr_k) % p def diffie_hellman_key_exchange(a, p, option = None): """ Perform diffie-helmman key exchange. """ if option is not None: # Print explanation of process when option parameter is given option = 1 if prime_check(p) is False: print(f"{p} is not a prime number") # p must be large 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}") # a must be 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}") # In here, Alice send her public key to Bob, and Bob also send his public key to Alice. 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
def euler_totient(n): """Euler's totient function or Phi function. Time Complexity: O(sqrt(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.
def extended_gcd(num1, num2): """Extended GCD algorithm. Return s, t, g such that num1 * s + num2 * t = GCD(num1, num2) and s and t are co-prime. """ 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:
def factorial(n, mod=None): """Calculates factorial iteratively. If mod is not None, then return (n! % mod) Time Complexity - O(n)""" 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): """Calculates factorial recursively. If mod is not None, then return (n! % mod) Time Complexity - O(n)""" 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
from cmath import exp, pi def fft(x): """ Recursive implementation of the Cooley-Tukey""" N = len(x) if N == 1: return x # get the elements at even/odd indices 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
import math def find_order(a, n): """ Find order for positive integer n and given integer a that satisfies gcd(a, n) = 1. """ if (a == 1) & (n == 1): # Exception Handeling : 1 is the order of of 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.
import math """ 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. """ def find_order(a, n): """ Find order for positive integer n and given integer a that satisfies gcd(a, n) = 1. Time complexity O(nlog(n)) """ if (a == 1) & (n == 1): # Exception Handeling : 1 is the order of of 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 """ 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' """ def euler_totient(n): """Euler's totient function or Phi function. Time Complexity: O(sqrt(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 """ 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. """ def find_primitive_root(n): if n == 1: # Exception Handeling : 0 is the only primitive root of 1 return [0] phi = euler_totient(n) p_root_list = [] """ It will return every primitive roots of n. """ for i in range (1, n): #To have order, a and n must be relative prime with each other. 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:
def gcd(a, 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 """ 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): """Computes the lowest common multiple of integers a and b.""" return abs(a) * abs(b) / gcd(a, 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 """ def trailing_zero(x): count = 0 while x and not x & 1: count += 1 x >>= 1 return count """ Given two non-negative integer a and b, computes the greatest common divisor of a and b using bitwise operator. """ def gcd_bit(a, b): """ Similar to gcd but uses bitwise operators and less error handling.""" 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
def gen_strobogrammatic(n): """ Given n, generate all strobogrammatic numbers of length n. :type n: int :rtype: List[str] """ 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): """ :type low: str :type high: str :rtype: int """ 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
def hailstone(n): """ Return the 'hailstone sequence' from n to 1 n: The starting point of the hailstone sequence """ sequence = [n] while n > 1: if n%2 != 0: n = 3*n + 1 else: n = int(n/2) sequence.append(n) return sequence
A strobogrammatic number is a number that looks the same when rotated 180 degrees looked at upside down. Write a function to determine if a number is strobogrammatic. The number is represented as a string. For example, the numbers 69, 88, and 818 are all strobogrammatic. :type num: str :rtype: bool Another implementation. return num num::1.replace'6', ''.replace'9', '6'.replace'', '9'
def is_strobogrammatic(num): """ :type num: str :rtype: bool """ comb = "00 11 88 69 96" i = 0 j = len(num) - 1 while i <= j: if comb.find(num[i]+num[j]) == -1: return False i += 1 j -= 1 return True def is_strobogrammatic2(num: str): """Another implementation.""" return num == num[::-1].replace('6', '#').replace('9', '6').replace('#', '9')
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
def find_factorial(n): """ Calculates the factorial of a given number 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 # 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 sum_of_digits sum_of_digits += find_factorial(temp % 10) # replace value of temp by temp/10 # i.e. will remove the last digit from temp temp //= 10 # returns True if number is krishnamurthy 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
def magic_number(n): """ Checks if n is a magic number """ total_sum = 0 # will end when n becomes 0 # AND # sum becomes single digit. while n > 0 or total_sum > 9: # when n becomes 0 but we have a total_sum, # we update the value of n with the value of the sum digits if n == 0: n = total_sum # only when sum of digits isn't single digit total_sum = 0 total_sum += n % 10 n //= 10 # Return true if sum becomes 1 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
def modular_exponential(base, exponent, mod): """Computes (base ^ exponent) % mod. Time complexity - O(log n) Use similar to Python in-built function pow.""" if exponent < 0: raise ValueError("Exponent must be positive.") base %= mod result = 1 while exponent > 0: # If the last bit is 1, add 2^k. 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
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 def extended_gcd(a: int, b: int) -> [int, int, int]: """Extended GCD algorithm. Return s, t, g such that a * s + b * t = GCD(a, b) and s and t are co-prime. """ 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: """ Returns x such that a * x = 1 (mod m) a and m must be coprime """ 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.
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 # no such number exists 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] # prefer slicing instead of reversed(digits[idx:]) 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
def find_next_square(sq): root = sq ** 0.5 if root.is_integer(): return (root + 1)**2 return -1 def find_next_square2(sq): """ Alternative method, works by evaluating anything non-zero as True (0.000001 --> True) """ 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
def find_nth_digit(n): """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 """ 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.
import math def num_perfect_squares(number): """ 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. if int(math.sqrt(number))**2 == number: return 1 # 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). while number > 0 and number % 4 == 0: number /= 4 # 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. if number % 8 == 7: return 4 # 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. 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 from fractions import Fraction from typing import Dict, Union, Set, Iterable from numbers import Rational from functools import reduce class Monomial: """ A simple Monomial class to record the details of all variables that a typical monomial is composed of. """ def __init__(self, variables: Dict[int, int], coeff: Union[int, float, Fraction, None]= None) -> None: ''' 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) ''' 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): ''' A helper for converting numbers to Fraction only when possible. ''' if isinstance(num, Rational): res = Fraction(num, 1) return Fraction(res.numerator, res.denominator) else: return num # def equal_upto_scalar(self, other: Monomial) -> bool: def equal_upto_scalar(self, other) -> bool: """ Return True if other is a monomial and is equivalent to self up to a scalar multiple. """ if not isinstance(other, Monomial): raise ValueError('Can only compare monomials.') return other.variables == self.variables # def __add__(self, other: Union[int, float, Fraction, Monomial]): def __add__(self, other: Union[int, float, Fraction]): """ Define the addition of two monomials or the addition of a monomial with an int, float, or a 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() # 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. raise ValueError(f'Cannot add {str(other)} to {self.__str__()} because they don\'t have same variables.') # def __eq__(self, other: Monomial) -> bool: def __eq__(self, other) -> bool: """ Return True if two monomials are equal upto a scalar multiple. """ return self.equal_upto_scalar(other) and self.coeff == other.coeff # def __mul__(self, other: Union[int, float, Fraction, Monomial]) -> Monomial: def __mul__(self, other: Union[int, float, Fraction]): """ 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 """ 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) -> Monomial: def inverse(self): """ 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) """ 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, Monomial]) -> Monomial: def __truediv__(self, other: Union[int, float, Fraction]): """ Compute the division between two monomials or a monomial and some other datatype like 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, Monomial]) -> Monomial: def __floordiv__(self, other: Union[int, float, Fraction]): """ For monomials, floor div is the same as true div. """ return self.__truediv__(other) # def clone(self) -> Monomial: def clone(self): """ Clone the monomial. """ 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) -> Monomial: def clean(self): """ Clean the monomial by dropping any variables that have power 0. """ 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, Monomial]) -> Monomial: def __sub__(self, other: Union[int, float, Fraction]): """ Compute the subtraction of a monomial and a datatype such as int, float, Fraction, or Monomial. """ 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: """ 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. """ 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: """ Get the set of all variables present in the monomial. """ return set(sorted(self.variables.keys())) def substitute(self, substitutions: Union[int, float, Fraction, Dict[int, Union[int, float, Fraction]]]) -> Fraction: """ Substitute the variables in the monomial for values defined by the substitutions dictionary. """ 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: """ Get a string representation of the monomial. """ 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: """ A simple implementation of a polynomial class that records the details about two polynomials that are potentially comprised of multiple variables. """ def __init__(self, monomials: Iterable[Union[int, float, Fraction, Monomial]]) -> None: ''' 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 ''' 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): ''' A helper for converting numbers to Fraction only when possible. ''' 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, Polynomial]) -> Polynomial: def __add__(self, other: Union[int, float, Fraction, Monomial]): """ Add a given poylnomial to a copy of self. """ 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, Polynomial]) -> Polynomial: def __sub__(self, other: Union[int, float, Fraction, Monomial]): """ Subtract the given polynomial from a copy of self. """ 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, Polynomial]) -> Polynomial: def __mul__(self, other: Union[int, float, Fraction, Monomial]): """ Multiply a given polynomial to a copy of self. """ 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, Polynomial]) -> Polynomial: def __floordiv__(self, other: Union[int, float, Fraction, Monomial]): """ For Polynomials, floordiv is the same as truediv. """ return self.__truediv__(other) # def __truediv__(self, other: Union[int, float, Fraction, Monomial, Polynomial]) -> Polynomial: def __truediv__(self, other: Union[int, float, Fraction, Monomial]): """ For Polynomials, only division by a monomial is defined. TODO: Implement polynomial / polynomial. """ 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) -> Polynomial: def clone(self): """ Clone the polynomial. """ return Polynomial(list({m.clone() for m in self.all_monomials()})) def variables(self) -> Set: """ Get all the variables present in this polynomials. """ res = set() for i in self.all_monomials(): res |= {j for j in i.variables} res = list(res) # res.sort() return set(res) def all_monomials(self) -> Iterable[Monomial]: """ Get the monomials of this polynomial. """ return {m for m in self.monomials if m != Monomial({}, 0)} def __eq__(self, other) -> bool: """ Return True if the other polynomial is the same as this. """ 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]: """ Get the value after substituting certain values for the variables defined in substitutions. """ 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: """ Get a string representation of the polynomial. """ 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
def power(a: int, n: int, mod: int = None): """ 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) """ 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): """ 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)) """ 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.
def prime_check(n): """Return True if n is a prime number Else return False. """ 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:
def get_primes(n): """Return list of all primes less than n, Using sieve of Eratosthenes. """ if n <= 0: raise ValueError("'n' must be a positive integer.") # If x is even, exclude x from list (-1): sieve_size = (n // 2 - 1) if n % 2 == 0 else (n // 2) sieve = [True for _ in range(sieve_size)] # Sieve primes = [] # List of Primes if n >= 2: primes.append(2) # 2 is prime by default 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.
def pythagoras(opposite, adjacent, hypotenuse): """ Returns length of a third side of a right angled triangle. Passing "?" will indicate the unknown side. """ 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
import random def is_prime(n, k): def pow2_factor(num): """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 valid_witness(a): """ 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 """ 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 # precondition n >= 5 if n < 5: return n == 2 or n == 3 # True for prime 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.
def recursive_binomial_coefficient(n,k): """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 """ if k>n: raise ValueError('Invalid Inputs, ensure that n >= k') #function is only defined for n>=k if k == 0 or n == k: #C(n,0) = C(n,n) = 1, so this is our base case. return 1 if k > n/2: #C(n,k) = C(n,n-k), so if n/2 is sufficiently small, we can reduce the problem size. return recursive_binomial_coefficient(n,n-k) #else, we know C(n,k) = (n/k)C(n-1,k-1), so we can use this to reduce our problem size. 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 import random def generate_key(k, seed=None): """ the RSA key generating algorithm k is the number of bits in n """ def modinv(a, m): """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 gen_prime(k, seed=None): """generate a prime with k bits""" 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 # size in bits of p and q need to add up to the size of n p_size = k / 2 q_size = k - p_size e = gen_prime(k, seed) # in many cases, e is also chosen to be a small constant 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) # calculate totient function 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
def square_root(n, epsilon=0.001): """Return square root of n, with maximum absolute error epsilon""" 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:
def sum_dig_pow(low, high): result = [] for number in range(low, high + 1): exponent = 1 # set to 1 summation = 0 # set to 1 number_as_string = str(number) tokens = list(map(int, number_as_string)) # parse the string into individual digits for k in tokens: summation = summation + (k ** exponent) exponent += 1 if summation == number: result.append(number) return result # Some test cases: 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.
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: """ Given two monomials (from the cycle index of a symmetry group), compute the resultant monomial in the cartesian product corresponding to their merging. """ 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]: """ Compute the product of given cycle indices p1, and p2 and evaluate it at q. """ 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: """ 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 """ 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: """ Compute the cycle index of S_n, i.e. the symmetry group of n symbols. """ 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
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 # iterates over all cells in the grid for i in range(m): for j in range(n): # makes sure we are next to a wall. if j == 0 or grid[i][j-1] == 'W': row_e = row_kills(grid, i, j) # makes sure we are next to a wall. if i == 0 or grid[i-1][j] == 'W': col_e[j] = col_kills(grid, i, j) # makes sure the cell contains a 0 if grid[i][j] == '0': # updates the variable max_killed = max(max_killed, row_e + col_e[j]) return max_killed # calculate killed enemies for row i from column j 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 # calculate killed enemies for column j from row i 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 # ----------------- TESTS ------------------------- """ Testsuite for the project """ 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
import math def cholesky_decomposition(A): """ :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 """ 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) # 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)] # Taking care of the edge cases- matrix of size 1xn or mx1 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): # Number of ways to reach a[i][j] = number of ways to reach # a[i-1][j] + a[i][j-1] 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
def multiply(matA: list, matB: list) -> list: """ Multiplies two square matrices matA and matB of size n x n Time Complexity: O(n^3) """ 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: """ Returns the Identity matrix of size n x n Time Complexity: O(n^2) """ 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: """ 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 """ 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
import fractions def invert_matrix(m): """invert an n x n matrix""" # Error conditions 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]] # Calculation elif len(m) == 2: # simple case 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: """some steps combined in helpers to reduce traversals""" # get matrix of minors w/ "checkerboard" signs m_of_minors = get_matrix_of_minors(m) # calculate determinant (we need to know 1/det) multiplier = fractions.Fraction(1, get_determinant(m)) # adjugate (swap on diagonals) and multiply by 1/det inverted = transpose_and_multiply(m_of_minors, multiplier) return inverted def get_determinant(m): """recursively calculate the determinant of an n x n matrix, n >= 2""" if len(m) == 2: # trivial case 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): """get the matrix of minors and alternate signs""" 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): """ get the minor of the matrix position m[row][col] (all values m[r][c] where r != row and c != 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): """swap values along diagonal, optionally adding multiplier""" 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
def multiply(multiplicand: list, multiplier: list) -> list: """ :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] """ 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.") # create a result 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
from heapq import heappush, heappop from typing import List def sort_diagonally(mat: List[List[int]]) -> List[List[int]]: # If the input is a vector, return the vector if len(mat) == 1 or len(mat[0]) == 1: return mat # Rows + columns - 1 # The -1 helps you to not repeat a column for i in range(len(mat)+len(mat[0])-1): # Process the rows if i+1 < len(mat): # Initialize heap, set row and column h = [] row = len(mat)-(i+1) col = 0 # Traverse diagonally, and add the values to the heap while row < len(mat): heappush(h, (mat[row][col])) row += 1 col += 1 # Sort the diagonal row = len(mat)-(i+1) col = 0 while h: ele = heappop(h) mat[row][col] = ele row += 1 col += 1 else: # Process the columns # Initialize heap, row and column h = [] row = 0 col = i - (len(mat)-1) # Traverse Diagonally while col < len(mat[0]) and row < len(mat): heappush(h, (mat[row][col])) row += 1 col += 1 # Sort the diagonal row = 0 col = i - (len(mat)-1) while h: ele = heappop(h) mat[row][col] = ele row += 1 col += 1 # Return the updated matrix 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 """ 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.]))) # 10 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): def multiply(self, a, b): """ :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] """ 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 # Python solution with only one table for B (~196ms): def multiply(self, a, b): """ :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] """ 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 # Python solution with two tables (~196ms): def multiply(self, a, b): """ :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] """ 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 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 # Without hash-table/dict def valid_solution(board): correct = [1, 2, 3, 4, 5, 6, 7, 8, 9] # check rows for row in board: if sorted(row) != correct: return False # check columns for column in zip(*board): if sorted(column) != correct: return False # check regions 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 # if everything correct return True # Using set 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 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 # Calculate and print sum of current sub-square 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
import math def distance(x,y): """[summary] HELPER-FUNCTION calculates the (eulidean) distance between vector x and y. Arguments: x {[tuple]} -- [vector] y {[tuple]} -- [vector] """ 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): """[summary] Implements the nearest neighbor algorithm Arguments: x {[tupel]} -- [vector] tSet {[dict]} -- [training set] Returns: [type] -- [result of the AND-function] """ 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.
import collections def max_sliding_window(arr, k): qi = collections.deque() # queue storing indexes of elements 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.
from __future__ import division from collections import deque class MovingAverage(object): def __init__(self, size): """ Initialize your data structure here. :type size: int """ self.queue = deque(maxlen=size) def next(self, val): """ :type val: int :rtype: float """ self.queue.append(val) return sum(self.queue) / len(self.queue) # Given a stream of integers and a window size, # calculate the moving average of all integers in the sliding window. 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
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): """Create a priority queue with items (list or iterable). If items is not passed, create empty priority queue.""" 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 size of the priority queue. """ return len(self.priority_queue_list) def push(self, item, priority=None): """Push the item in the priority queue. if priority is not given, priority is set to the value of item. """ 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 # when traversed complete queue self.priority_queue_list.append(node) def pop(self): """Remove and return the item with the lowest priority. """ # remove and return the first node from the queue return self.priority_queue_list.pop().data