Datasets:

zip
stringlengths
19
109
filename
stringlengths
4
185
contents
stringlengths
0
30.1M
type_annotations
sequencelengths
0
1.97k
type_annotation_starts
sequencelengths
0
1.97k
type_annotation_ends
sequencelengths
0
1.97k
archives/1098994933_python.zip
dynamic_programming/minimum_partition.py
""" Partition a set into two subsets such that the difference of subset sums is minimum """ def findMin(arr): n = len(arr) s = sum(arr) dp = [[False for x in range(s+1)]for y in range(n+1)] for i in range(1, n+1): dp[i][0] = True for i in range(1, s+1): dp[0][i] = False for i in range(1, n+1): for j in range(1, s+1): dp[i][j]= dp[i][j-1] if (arr[i-1] <= j): dp[i][j] = dp[i][j] or dp[i-1][j-arr[i-1]] for j in range(int(s/2), -1, -1): if dp[n][j] == True: diff = s-2*j break; return diff
[]
[]
[]
archives/1098994933_python.zip
dynamic_programming/rod_cutting.py
""" This module provides two implementations for the rod-cutting problem: 1. A naive recursive implementation which has an exponential runtime 2. Two dynamic programming implementations which have quadratic runtime The rod-cutting problem is the problem of finding the maximum possible revenue obtainable from a rod of length ``n`` given a list of prices for each integral piece of the rod. The maximum revenue can thus be obtained by cutting the rod and selling the pieces separately or not cutting it at all if the price of it is the maximum obtainable. """ def naive_cut_rod_recursive(n: int, prices: list): """ Solves the rod-cutting problem via naively without using the benefit of dynamic programming. The results is the same sub-problems are solved several times leading to an exponential runtime Runtime: O(2^n) Arguments ------- n: int, the length of the rod prices: list, the prices for each piece of rod. ``p[i-i]`` is the price for a rod of length ``i`` Returns ------- The maximum revenue obtainable for a rod of length n given the list of prices for each piece. Examples -------- >>> naive_cut_rod_recursive(4, [1, 5, 8, 9]) 10 >>> naive_cut_rod_recursive(10, [1, 5, 8, 9, 10, 17, 17, 20, 24, 30]) 30 """ _enforce_args(n, prices) if n == 0: return 0 max_revue = float("-inf") for i in range(1, n + 1): max_revue = max(max_revue, prices[i - 1] + naive_cut_rod_recursive(n - i, prices)) return max_revue def top_down_cut_rod(n: int, prices: list): """ Constructs a top-down dynamic programming solution for the rod-cutting problem via memoization. This function serves as a wrapper for _top_down_cut_rod_recursive Runtime: O(n^2) Arguments -------- n: int, the length of the rod prices: list, the prices for each piece of rod. ``p[i-i]`` is the price for a rod of length ``i`` Note ---- For convenience and because Python's lists using 0-indexing, length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of length 0. Returns ------- The maximum revenue obtainable for a rod of length n given the list of prices for each piece. Examples ------- >>> top_down_cut_rod(4, [1, 5, 8, 9]) 10 >>> top_down_cut_rod(10, [1, 5, 8, 9, 10, 17, 17, 20, 24, 30]) 30 """ _enforce_args(n, prices) max_rev = [float("-inf") for _ in range(n + 1)] return _top_down_cut_rod_recursive(n, prices, max_rev) def _top_down_cut_rod_recursive(n: int, prices: list, max_rev: list): """ Constructs a top-down dynamic programming solution for the rod-cutting problem via memoization. Runtime: O(n^2) Arguments -------- n: int, the length of the rod prices: list, the prices for each piece of rod. ``p[i-i]`` is the price for a rod of length ``i`` max_rev: list, the computed maximum revenue for a piece of rod. ``max_rev[i]`` is the maximum revenue obtainable for a rod of length ``i`` Returns ------- The maximum revenue obtainable for a rod of length n given the list of prices for each piece. """ if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: max_revenue = float("-inf") for i in range(1, n + 1): max_revenue = max(max_revenue, prices[i - 1] + _top_down_cut_rod_recursive(n - i, prices, max_rev)) max_rev[n] = max_revenue return max_rev[n] def bottom_up_cut_rod(n: int, prices: list): """ Constructs a bottom-up dynamic programming solution for the rod-cutting problem Runtime: O(n^2) Arguments ---------- n: int, the maximum length of the rod. prices: list, the prices for each piece of rod. ``p[i-i]`` is the price for a rod of length ``i`` Returns ------- The maximum revenue obtainable from cutting a rod of length n given the prices for each piece of rod p. Examples ------- >>> bottom_up_cut_rod(4, [1, 5, 8, 9]) 10 >>> bottom_up_cut_rod(10, [1, 5, 8, 9, 10, 17, 17, 20, 24, 30]) 30 """ _enforce_args(n, prices) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of length 0. max_rev = [float("-inf") for _ in range(n + 1)] max_rev[0] = 0 for i in range(1, n + 1): max_revenue_i = max_rev[i] for j in range(1, i + 1): max_revenue_i = max(max_revenue_i, prices[j - 1] + max_rev[i - j]) max_rev[i] = max_revenue_i return max_rev[n] def _enforce_args(n: int, prices: list): """ Basic checks on the arguments to the rod-cutting algorithms n: int, the length of the rod prices: list, the price list for each piece of rod. Throws ValueError: if n is negative or there are fewer items in the price list than the length of the rod """ if n < 0: raise ValueError(f"n must be greater than or equal to 0. Got n = {n}") if n > len(prices): raise ValueError(f"Each integral piece of rod must have a corresponding " f"price. Got n = {n} but length of prices = {len(prices)}") def main(): prices = [6, 10, 12, 15, 20, 23] n = len(prices) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. expected_max_revenue = 36 max_rev_top_down = top_down_cut_rod(n, prices) max_rev_bottom_up = bottom_up_cut_rod(n, prices) max_rev_naive = naive_cut_rod_recursive(n, prices) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == '__main__': main()
[ "int", "list", "int", "list", "int", "list", "list", "int", "list", "int", "list" ]
[ 595, 608, 1480, 1493, 2425, 2438, 2453, 3303, 3316, 4268, 4281 ]
[ 598, 612, 1483, 1497, 2428, 2442, 2457, 3306, 3320, 4271, 4285 ]
archives/1098994933_python.zip
dynamic_programming/subset_generation.py
# python program to print all subset combination of n element in given set of r element . #arr[] ---> Input Array #data[] ---> Temporary array to store current combination # start & end ---> Staring and Ending indexes in arr[] # index ---> Current index in data[] #r ---> Size of a combination to be printed def combinationUtil(arr,n,r,index,data,i): #Current combination is ready to be printed, # print it if(index == r): for j in range(r): print(data[j],end =" ") print(" ") return # When no more elements are there to put in data[] if(i >= n): return #current is included, put next at next # location data[index] = arr[i] combinationUtil(arr,n,r,index+1,data,i+1) # current is excluded, replace it with # next (Note that i+1 is passed, but # index is not changed) combinationUtil(arr,n,r,index,data,i+1) # The main function that prints all combinations #of size r in arr[] of size n. This function #mainly uses combinationUtil() def printcombination(arr,n,r): # A temporary array to store all combination # one by one data = [0]*r #Print all combination using temprary #array 'data[]' combinationUtil(arr,n,r,0,data,0) # Driver function to check for above function arr = [10,20,30,40,50] printcombination(arr,len(arr),3) #This code is contributed by Ambuj sahu
[]
[]
[]
archives/1098994933_python.zip
dynamic_programming/sum_of_subset.py
def isSumSubset(arr, arrLen, requiredSum): # a subset value says 1 if that subset sum can be formed else 0 #initially no subsets can be formed hence False/0 subset = ([[False for i in range(requiredSum + 1)] for i in range(arrLen + 1)]) #for each arr value, a sum of zero(0) can be formed by not taking any element hence True/1 for i in range(arrLen + 1): subset[i][0] = True #sum is not zero and set is empty then false for i in range(1, requiredSum + 1): subset[0][i] = False for i in range(1, arrLen + 1): for j in range(1, requiredSum + 1): if arr[i-1]>j: subset[i][j] = subset[i-1][j] if arr[i-1]<=j: subset[i][j] = (subset[i-1][j] or subset[i-1][j-arr[i-1]]) #uncomment to print the subset # for i in range(arrLen+1): # print(subset[i]) return subset[arrLen][requiredSum] arr = [2, 4, 6, 8] requiredSum = 5 arrLen = len(arr) if isSumSubset(arr, arrLen, requiredSum): print("Found a subset with required sum") else: print("No subset with required sum")
[]
[]
[]
archives/1098994933_python.zip
file_transfer/recieve_file.py
if __name__ == '__main__': import socket # Import socket module sock = socket.socket() # Create a socket object host = socket.gethostname() # Get local machine name port = 12312 sock.connect((host, port)) sock.send(b'Hello server!') with open('Received_file', 'wb') as out_file: print('File opened') print('Receiving data...') while True: data = sock.recv(1024) print(f"data={data}") if not data: break out_file.write(data) # Write data to a file print('Successfully got the file') sock.close() print('Connection closed')
[]
[]
[]
archives/1098994933_python.zip
file_transfer/send_file.py
if __name__ == '__main__': import socket # Import socket module ONE_CONNECTION_ONLY = True # Set this to False if you wish to continuously accept connections filename='mytext.txt' port = 12312 # Reserve a port for your service. sock = socket.socket() # Create a socket object host = socket.gethostname() # Get local machine name sock.bind((host, port)) # Bind to the port sock.listen(5) # Now wait for client connection. print('Server listening....') while True: conn, addr = sock.accept() # Establish connection with client. print(f"Got connection from {addr}") data = conn.recv(1024) print(f"Server received {data}") with open(filename,'rb') as in_file: data = in_file.read(1024) while (data): conn.send(data) print(f"Sent {data!r}") data = in_file.read(1024) print('Done sending') conn.close() if ONE_CONNECTION_ONLY: # This is to make sure that the program doesn't hang while testing break sock.shutdown(1) sock.close()
[]
[]
[]
archives/1098994933_python.zip
graphs/a_star.py
grid = [[0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0],#0 are free path whereas 1's are obstacles [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 1, 0]] ''' heuristic = [[9, 8, 7, 6, 5, 4], [8, 7, 6, 5, 4, 3], [7, 6, 5, 4, 3, 2], [6, 5, 4, 3, 2, 1], [5, 4, 3, 2, 1, 0]]''' init = [0, 0] goal = [len(grid)-1, len(grid[0])-1] #all coordinates are given in format [y,x] cost = 1 #the cost map which pushes the path closer to the goal heuristic = [[0 for row in range(len(grid[0]))] for col in range(len(grid))] for i in range(len(grid)): for j in range(len(grid[0])): heuristic[i][j] = abs(i - goal[0]) + abs(j - goal[1]) if grid[i][j] == 1: heuristic[i][j] = 99 #added extra penalty in the heuristic map #the actions we can take delta = [[-1, 0 ], # go up [ 0, -1], # go left [ 1, 0 ], # go down [ 0, 1 ]] # go right #function to search the path def search(grid,init,goal,cost,heuristic): closed = [[0 for col in range(len(grid[0]))] for row in range(len(grid))]# the referrence grid closed[init[0]][init[1]] = 1 action = [[0 for col in range(len(grid[0]))] for row in range(len(grid))]#the action grid x = init[0] y = init[1] g = 0 f = g + heuristic[init[0]][init[0]] cell = [[f, g, x, y]] found = False # flag that is set when search is complete resign = False # flag set if we can't find expand while not found and not resign: if len(cell) == 0: resign = True return "FAIL" else: cell.sort()#to choose the least costliest action so as to move closer to the goal cell.reverse() next = cell.pop() x = next[2] y = next[3] g = next[1] f = next[0] if x == goal[0] and y == goal[1]: found = True else: for i in range(len(delta)):#to try out different valid actions x2 = x + delta[i][0] y2 = y + delta[i][1] if x2 >= 0 and x2 < len(grid) and y2 >=0 and y2 < len(grid[0]): if closed[x2][y2] == 0 and grid[x2][y2] == 0: g2 = g + cost f2 = g2 + heuristic[x2][y2] cell.append([f2, g2, x2, y2]) closed[x2][y2] = 1 action[x2][y2] = i invpath = [] x = goal[0] y = goal[1] invpath.append([x, y])#we get the reverse path from here while x != init[0] or y != init[1]: x2 = x - delta[action[x][y]][0] y2 = y - delta[action[x][y]][1] x = x2 y = y2 invpath.append([x, y]) path = [] for i in range(len(invpath)): path.append(invpath[len(invpath) - 1 - i]) print("ACTION MAP") for i in range(len(action)): print(action[i]) return path a = search(grid,init,goal,cost,heuristic) for i in range(len(a)): print(a[i])
[]
[]
[]
archives/1098994933_python.zip
graphs/articulation_points.py
# Finding Articulation Points in Undirected Graph def computeAP(l): n = len(l) outEdgeCount = 0 low = [0] * n visited = [False] * n isArt = [False] * n def dfs(root, at, parent, outEdgeCount): if parent == root: outEdgeCount += 1 visited[at] = True low[at] = at for to in l[at]: if to == parent: pass elif not visited[to]: outEdgeCount = dfs(root, to, at, outEdgeCount) low[at] = min(low[at], low[to]) # AP found via bridge if at < low[to]: isArt[at] = True # AP found via cycle if at == low[to]: isArt[at] = True else: low[at] = min(low[at], to) return outEdgeCount for i in range(n): if not visited[i]: outEdgeCount = 0 outEdgeCount = dfs(i, i, -1, outEdgeCount) isArt[i] = (outEdgeCount > 1) for x in range(len(isArt)): if isArt[x] == True: print(x) # Adjacency list of graph l = {0:[1,2], 1:[0,2], 2:[0,1,3,5], 3:[2,4], 4:[3], 5:[2,6,8], 6:[5,7], 7:[6,8], 8:[5,7]} computeAP(l)
[]
[]
[]
archives/1098994933_python.zip
graphs/basic_graphs.py
if __name__ == "__main__": # Accept No. of Nodes and edges n, m = map(int, input().split(" ")) # Initialising Dictionary of edges g = {} for i in range(n): g[i + 1] = [] """ ---------------------------------------------------------------------------- Accepting edges of Unweighted Directed Graphs ---------------------------------------------------------------------------- """ for _ in range(m): x, y = map(int, input().strip().split(" ")) g[x].append(y) """ ---------------------------------------------------------------------------- Accepting edges of Unweighted Undirected Graphs ---------------------------------------------------------------------------- """ for _ in range(m): x, y = map(int, input().strip().split(" ")) g[x].append(y) g[y].append(x) """ ---------------------------------------------------------------------------- Accepting edges of Weighted Undirected Graphs ---------------------------------------------------------------------------- """ for _ in range(m): x, y, r = map(int, input().strip().split(" ")) g[x].append([y, r]) g[y].append([x, r]) """ -------------------------------------------------------------------------------- Depth First Search. Args : G - Dictionary of edges s - Starting Node Vars : vis - Set of visited nodes S - Traversal Stack -------------------------------------------------------------------------------- """ def dfs(G, s): vis, S = set([s]), [s] print(s) while S: flag = 0 for i in G[S[-1]]: if i not in vis: S.append(i) vis.add(i) flag = 1 print(i) break if not flag: S.pop() """ -------------------------------------------------------------------------------- Breadth First Search. Args : G - Dictionary of edges s - Starting Node Vars : vis - Set of visited nodes Q - Traveral Stack -------------------------------------------------------------------------------- """ from collections import deque def bfs(G, s): vis, Q = set([s]), deque([s]) print(s) while Q: u = Q.popleft() for v in G[u]: if v not in vis: vis.add(v) Q.append(v) print(v) """ -------------------------------------------------------------------------------- Dijkstra's shortest path Algorithm Args : G - Dictionary of edges s - Starting Node Vars : dist - Dictionary storing shortest distance from s to every other node known - Set of knows nodes path - Preceding node in path -------------------------------------------------------------------------------- """ def dijk(G, s): dist, known, path = {s: 0}, set(), {s: 0} while True: if len(known) == len(G) - 1: break mini = 100000 for i in dist: if i not in known and dist[i] < mini: mini = dist[i] u = i known.add(u) for v in G[u]: if v[0] not in known: if dist[u] + v[1] < dist.get(v[0], 100000): dist[v[0]] = dist[u] + v[1] path[v[0]] = u for i in dist: if i != s: print(dist[i]) """ -------------------------------------------------------------------------------- Topological Sort -------------------------------------------------------------------------------- """ from collections import deque def topo(G, ind=None, Q=None): if Q is None: Q = [1] if ind is None: ind = [0] * (len(G) + 1) # SInce oth Index is ignored for u in G: for v in G[u]: ind[v] += 1 Q = deque() for i in G: if ind[i] == 0: Q.append(i) if len(Q) == 0: return v = Q.popleft() print(v) for w in G[v]: ind[w] -= 1 if ind[w] == 0: Q.append(w) topo(G, ind, Q) """ -------------------------------------------------------------------------------- Reading an Adjacency matrix -------------------------------------------------------------------------------- """ def adjm(): n = input().strip() a = [] for i in range(n): a.append(map(int, input().strip().split())) return a, n """ -------------------------------------------------------------------------------- Floyd Warshall's algorithm Args : G - Dictionary of edges s - Starting Node Vars : dist - Dictionary storing shortest distance from s to every other node known - Set of knows nodes path - Preceding node in path -------------------------------------------------------------------------------- """ def floy(A_and_n): (A, n) = A_and_n dist = list(A) path = [[0] * n for i in range(n)] for k in range(n): for i in range(n): for j in range(n): if dist[i][j] > dist[i][k] + dist[k][j]: dist[i][j] = dist[i][k] + dist[k][j] path[i][k] = k print(dist) """ -------------------------------------------------------------------------------- Prim's MST Algorithm Args : G - Dictionary of edges s - Starting Node Vars : dist - Dictionary storing shortest distance from s to nearest node known - Set of knows nodes path - Preceding node in path -------------------------------------------------------------------------------- """ def prim(G, s): dist, known, path = {s: 0}, set(), {s: 0} while True: if len(known) == len(G) - 1: break mini = 100000 for i in dist: if i not in known and dist[i] < mini: mini = dist[i] u = i known.add(u) for v in G[u]: if v[0] not in known: if v[1] < dist.get(v[0], 100000): dist[v[0]] = v[1] path[v[0]] = u """ -------------------------------------------------------------------------------- Accepting Edge list Vars : n - Number of nodes m - Number of edges Returns : l - Edge list n - Number of Nodes -------------------------------------------------------------------------------- """ def edglist(): n, m = map(int, input().split(" ")) l = [] for i in range(m): l.append(map(int, input().split(' '))) return l, n """ -------------------------------------------------------------------------------- Kruskal's MST Algorithm Args : E - Edge list n - Number of Nodes Vars : s - Set of all nodes as unique disjoint sets (initially) -------------------------------------------------------------------------------- """ def krusk(E_and_n): # Sort edges on the basis of distance (E, n) = E_and_n E.sort(reverse=True, key=lambda x: x[2]) s = [set([i]) for i in range(1, n + 1)] while True: if len(s) == 1: break print(s) x = E.pop() for i in range(len(s)): if x[0] in s[i]: break for j in range(len(s)): if x[1] in s[j]: if i == j: break s[j].update(s[i]) s.pop(i) break # find the isolated node in the graph def find_isolated_nodes(graph): isolated = [] for node in graph: if not graph[node]: isolated.append(node) return isolated
[]
[]
[]
archives/1098994933_python.zip
graphs/bellman_ford.py
def printDist(dist, V): print("\nVertex Distance") for i in range(V): if dist[i] != float('inf') : print(i,"\t",int(dist[i]),end = "\t") else: print(i,"\t","INF",end="\t") print() def BellmanFord(graph, V, E, src): mdist=[float('inf') for i in range(V)] mdist[src] = 0.0 for i in range(V-1): for j in range(V): u = graph[j]["src"] v = graph[j]["dst"] w = graph[j]["weight"] if mdist[u] != float('inf') and mdist[u] + w < mdist[v]: mdist[v] = mdist[u] + w for j in range(V): u = graph[j]["src"] v = graph[j]["dst"] w = graph[j]["weight"] if mdist[u] != float('inf') and mdist[u] + w < mdist[v]: print("Negative cycle found. Solution not possible.") return printDist(mdist, V) if __name__ == "__main__": V = int(input("Enter number of vertices: ").strip()) E = int(input("Enter number of edges: ").strip()) graph = [dict() for j in range(E)] for i in range(V): graph[i][i] = 0.0 for i in range(E): print("\nEdge ",i+1) src = int(input("Enter source:").strip()) dst = int(input("Enter destination:").strip()) weight = float(input("Enter weight:").strip()) graph[i] = {"src": src,"dst": dst, "weight": weight} gsrc = int(input("\nEnter shortest path source:").strip()) BellmanFord(graph, V, E, gsrc)
[]
[]
[]
archives/1098994933_python.zip
graphs/bfs.py
""" BFS. pseudo-code: BFS(graph G, start vertex s): // all nodes initially unexplored mark s as explored let Q = queue data structure, initialized with s while Q is non-empty: remove the first node of Q, call it v for each edge(v, w): // for w in graph[v] if w unexplored: mark w as explored add w to Q (at the end) """ G = {'A': ['B', 'C'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F'], 'D': ['B'], 'E': ['B', 'F'], 'F': ['C', 'E']} def bfs(graph, start): """ >>> ''.join(sorted(bfs(G, 'A'))) 'ABCDEF' """ explored, queue = set(), [start] # collections.deque([start]) explored.add(start) while queue: v = queue.pop(0) # queue.popleft() for w in graph[v]: if w not in explored: explored.add(w) queue.append(w) return explored if __name__ == '__main__': print(bfs(G, 'A'))
[]
[]
[]
archives/1098994933_python.zip
graphs/bfs_shortest_path.py
graph = {'A': ['B', 'C', 'E'], 'B': ['A','D', 'E'], 'C': ['A', 'F', 'G'], 'D': ['B'], 'E': ['A', 'B','D'], 'F': ['C'], 'G': ['C']} def bfs_shortest_path(graph, start, goal): # keep track of explored nodes explored = [] # keep track of all the paths to be checked queue = [[start]] # return path if start is goal if start == goal: return "That was easy! Start = goal" # keeps looping until all possible paths have been checked while queue: # pop the first path from the queue path = queue.pop(0) # get the last node from the path node = path[-1] if node not in explored: neighbours = graph[node] # go through all neighbour nodes, construct a new path and # push it into the queue for neighbour in neighbours: new_path = list(path) new_path.append(neighbour) queue.append(new_path) # return path if neighbour is goal if neighbour == goal: return new_path # mark node as explored explored.append(node) # in case there's no path between the 2 nodes return "So sorry, but a connecting path doesn't exist :(" bfs_shortest_path(graph, 'G', 'D') # returns ['G', 'C', 'A', 'B', 'D']
[]
[]
[]
archives/1098994933_python.zip
graphs/breadth_first_search.py
#!/usr/bin/python # encoding=utf8 """ Author: OMKAR PATHAK """ class Graph(): def __init__(self): self.vertex = {} # for printing the Graph vertexes def printGraph(self): for i in self.vertex.keys(): print(i,' -> ', ' -> '.join([str(j) for j in self.vertex[i]])) # for adding the edge beween two vertexes def addEdge(self, fromVertex, toVertex): # check if vertex is already present, if fromVertex in self.vertex.keys(): self.vertex[fromVertex].append(toVertex) else: # else make a new vertex self.vertex[fromVertex] = [toVertex] def BFS(self, startVertex): # Take a list for stoting already visited vertexes visited = [False] * len(self.vertex) # create a list to store all the vertexes for BFS queue = [] # mark the source node as visited and enqueue it visited[startVertex] = True queue.append(startVertex) while queue: startVertex = queue.pop(0) print(startVertex, end = ' ') # mark all adjacent nodes as visited and print them for i in self.vertex[startVertex]: if visited[i] == False: queue.append(i) visited[i] = True if __name__ == '__main__': g = Graph() g.addEdge(0, 1) g.addEdge(0, 2) g.addEdge(1, 2) g.addEdge(2, 0) g.addEdge(2, 3) g.addEdge(3, 3) g.printGraph() print('BFS:') g.BFS(2) # OUTPUT: # 0  ->  1 -> 2 # 1  ->  2 # 2  ->  0 -> 3 # 3  ->  3 # BFS: # 2 0 3 1
[]
[]
[]
archives/1098994933_python.zip
graphs/check_bipartite_graph_bfs.py
# Check whether Graph is Bipartite or Not using BFS # A Bipartite Graph is a graph whose vertices can be divided into two independent sets, # U and V such that every edge (u, v) either connects a vertex from U to V or a vertex # from V to U. In other words, for every edge (u, v), either u belongs to U and v to V, # or u belongs to V and v to U. We can also say that there is no edge that connects # vertices of same set. def checkBipartite(l): queue = [] visited = [False] * len(l) color = [-1] * len(l) def bfs(): while(queue): u = queue.pop(0) visited[u] = True for neighbour in l[u]: if neighbour == u: return False if color[neighbour] == -1: color[neighbour] = 1 - color[u] queue.append(neighbour) elif color[neighbour] == color[u]: return False return True for i in range(len(l)): if not visited[i]: queue.append(i) color[i] = 0 if bfs() == False: return False return True # Adjacency List of graph l = {0:[1,3], 1:[0,2], 2:[1,3], 3:[0,2]} print(checkBipartite(l))
[]
[]
[]
archives/1098994933_python.zip
graphs/check_bipartite_graph_dfs.py
# Check whether Graph is Bipartite or Not using DFS # A Bipartite Graph is a graph whose vertices can be divided into two independent sets, # U and V such that every edge (u, v) either connects a vertex from U to V or a vertex # from V to U. In other words, for every edge (u, v), either u belongs to U and v to V, # or u belongs to V and v to U. We can also say that there is no edge that connects # vertices of same set. def check_bipartite_dfs(l): visited = [False] * len(l) color = [-1] * len(l) def dfs(v, c): visited[v] = True color[v] = c for u in l[v]: if not visited[u]: dfs(u, 1 - c) for i in range(len(l)): if not visited[i]: dfs(i, 0) for i in range(len(l)): for j in l[i]: if color[i] == color[j]: return False return True # Adjacency list of graph l = {0:[1,3], 1:[0,2], 2:[1,3], 3:[0,2], 4: []} print(check_bipartite_dfs(l))
[]
[]
[]
archives/1098994933_python.zip
graphs/depth_first_search.py
#!/usr/bin/python # encoding=utf8 """ Author: OMKAR PATHAK """ class Graph(): def __init__(self): self.vertex = {} # for printing the Graph vertexes def printGraph(self): print(self.vertex) for i in self.vertex.keys(): print(i,' -> ', ' -> '.join([str(j) for j in self.vertex[i]])) # for adding the edge beween two vertexes def addEdge(self, fromVertex, toVertex): # check if vertex is already present, if fromVertex in self.vertex.keys(): self.vertex[fromVertex].append(toVertex) else: # else make a new vertex self.vertex[fromVertex] = [toVertex] def DFS(self): # visited array for storing already visited nodes visited = [False] * len(self.vertex) # call the recursive helper function for i in range(len(self.vertex)): if visited[i] == False: self.DFSRec(i, visited) def DFSRec(self, startVertex, visited): # mark start vertex as visited visited[startVertex] = True print(startVertex, end = ' ') # Recur for all the vertexes that are adjacent to this node for i in self.vertex.keys(): if visited[i] == False: self.DFSRec(i, visited) if __name__ == '__main__': g = Graph() g.addEdge(0, 1) g.addEdge(0, 2) g.addEdge(1, 2) g.addEdge(2, 0) g.addEdge(2, 3) g.addEdge(3, 3) g.printGraph() print('DFS:') g.DFS() # OUTPUT: # 0  ->  1 -> 2 # 1  ->  2 # 2  ->  0 -> 3 # 3  ->  3 # DFS: # 0 1 2 3
[]
[]
[]
archives/1098994933_python.zip
graphs/dfs.py
"""pseudo-code""" """ DFS(graph G, start vertex s): // all nodes initially unexplored mark s as explored for every edge (s, v): if v unexplored: DFS(G, v) """ def dfs(graph, start): """The DFS function simply calls itself recursively for every unvisited child of its argument. We can emulate that behaviour precisely using a stack of iterators. Instead of recursively calling with a node, we'll push an iterator to the node's children onto the iterator stack. When the iterator at the top of the stack terminates, we'll pop it off the stack.""" explored, stack = set(), [start] while stack: v = stack.pop() # one difference from BFS is to pop last element here instead of first one if v in explored: continue explored.add(v) for w in graph[v]: if w not in explored: stack.append(w) return explored G = {'A': ['B', 'C'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F'], 'D': ['B'], 'E': ['B', 'F'], 'F': ['C', 'E']} print(dfs(G, 'A'))
[]
[]
[]
archives/1098994933_python.zip
graphs/dijkstra.py
"""pseudo-code""" """ DIJKSTRA(graph G, start vertex s, destination vertex d): //all nodes initially unexplored 1 - let H = min heap data structure, initialized with 0 and s [here 0 indicates the distance from start vertex s] 2 - while H is non-empty: 3 - remove the first node and cost of H, call it U and cost 4 - if U has been previously explored: 5 - go to the while loop, line 2 //Once a node is explored there is no need to make it again 6 - mark U as explored 7 - if U is d: 8 - return cost // total cost from start to destination vertex 9 - for each edge(U, V): c=cost of edge(U,V) // for V in graph[U] 10 - if V explored: 11 - go to next V in line 9 12 - total_cost = cost + c 13 - add (total_cost,V) to H You can think at cost as a distance where Dijkstra finds the shortest distance between vertexes s and v in a graph G. The use of a min heap as H guarantees that if a vertex has already been explored there will be no other path with shortest distance, that happens because heapq.heappop will always return the next vertex with the shortest distance, considering that the heap stores not only the distance between previous vertex and current vertex but the entire distance between each vertex that makes up the path from start vertex to target vertex. """ import heapq def dijkstra(graph, start, end): """Return the cost of the shortest path between vertexes start and end. >>> dijkstra(G, "E", "C") 6 >>> dijkstra(G2, "E", "F") 3 >>> dijkstra(G3, "E", "F") 3 """ heap = [(0, start)] # cost from start node,end node visited = set() while heap: (cost, u) = heapq.heappop(heap) if u in visited: continue visited.add(u) if u == end: return cost for v, c in graph[u]: if v in visited: continue next = cost + c heapq.heappush(heap, (next, v)) return -1 G = { "A": [["B", 2], ["C", 5]], "B": [["A", 2], ["D", 3], ["E", 1], ["F", 1]], "C": [["A", 5], ["F", 3]], "D": [["B", 3]], "E": [["B", 4], ["F", 3]], "F": [["C", 3], ["E", 3]], } r""" Layout of G2: E -- 1 --> B -- 1 --> C -- 1 --> D -- 1 --> F \ /\ \ || ----------------- 3 -------------------- """ G2 = { "B": [["C", 1]], "C": [["D", 1]], "D": [["F", 1]], "E": [["B", 1], ["F", 3]], "F": [], } r""" Layout of G3: E -- 1 --> B -- 1 --> C -- 1 --> D -- 1 --> F \ /\ \ || -------- 2 ---------> G ------- 1 ------ """ G3 = { "B": [["C", 1]], "C": [["D", 1]], "D": [["F", 1]], "E": [["B", 1], ["G", 2]], "F": [], "G": [["F", 1]], } shortDistance = dijkstra(G, "E", "C") print(shortDistance) # E -- 3 --> F -- 3 --> C == 6 shortDistance = dijkstra(G2, "E", "F") print(shortDistance) # E -- 3 --> F == 3 shortDistance = dijkstra(G3, "E", "F") print(shortDistance) # E -- 2 --> G -- 1 --> F == 3 if __name__ == "__main__": import doctest doctest.testmod()
[]
[]
[]
archives/1098994933_python.zip
graphs/dijkstra_2.py
def printDist(dist, V): print("\nVertex Distance") for i in range(V): if dist[i] != float('inf') : print(i,"\t",int(dist[i]),end = "\t") else: print(i,"\t","INF",end="\t") print() def minDist(mdist, vset, V): minVal = float('inf') minInd = -1 for i in range(V): if (not vset[i]) and mdist[i] < minVal : minInd = i minVal = mdist[i] return minInd def Dijkstra(graph, V, src): mdist=[float('inf') for i in range(V)] vset = [False for i in range(V)] mdist[src] = 0.0 for i in range(V-1): u = minDist(mdist, vset, V) vset[u] = True for v in range(V): if (not vset[v]) and graph[u][v]!=float('inf') and mdist[u] + graph[u][v] < mdist[v]: mdist[v] = mdist[u] + graph[u][v] printDist(mdist, V) if __name__ == "__main__": V = int(input("Enter number of vertices: ").strip()) E = int(input("Enter number of edges: ").strip()) graph = [[float('inf') for i in range(V)] for j in range(V)] for i in range(V): graph[i][i] = 0.0 for i in range(E): print("\nEdge ",i+1) src = int(input("Enter source:").strip()) dst = int(input("Enter destination:").strip()) weight = float(input("Enter weight:").strip()) graph[src][dst] = weight gsrc = int(input("\nEnter shortest path source:").strip()) Dijkstra(graph, V, gsrc)
[]
[]
[]
archives/1098994933_python.zip
graphs/dijkstra_algorithm.py
# Title: Dijkstra's Algorithm for finding single source shortest path from scratch # Author: Shubham Malik # References: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm import math import sys # For storing the vertex set to retreive node with the lowest distance class PriorityQueue: # Based on Min Heap def __init__(self): self.cur_size = 0 self.array = [] self.pos = {} # To store the pos of node in array def isEmpty(self): return self.cur_size == 0 def min_heapify(self, idx): lc = self.left(idx) rc = self.right(idx) if lc < self.cur_size and self.array(lc)[0] < self.array(idx)[0]: smallest = lc else: smallest = idx if rc < self.cur_size and self.array(rc)[0] < self.array(smallest)[0]: smallest = rc if smallest != idx: self.swap(idx, smallest) self.min_heapify(smallest) def insert(self, tup): # Inserts a node into the Priority Queue self.pos[tup[1]] = self.cur_size self.cur_size += 1 self.array.append((sys.maxsize, tup[1])) self.decrease_key((sys.maxsize, tup[1]), tup[0]) def extract_min(self): # Removes and returns the min element at top of priority queue min_node = self.array[0][1] self.array[0] = self.array[self.cur_size - 1] self.cur_size -= 1 self.min_heapify(1) del self.pos[min_node] return min_node def left(self, i): # returns the index of left child return 2 * i + 1 def right(self, i): # returns the index of right child return 2 * i + 2 def par(self, i): # returns the index of parent return math.floor(i / 2) def swap(self, i, j): # swaps array elements at indices i and j # update the pos{} self.pos[self.array[i][1]] = j self.pos[self.array[j][1]] = i temp = self.array[i] self.array[i] = self.array[j] self.array[j] = temp def decrease_key(self, tup, new_d): idx = self.pos[tup[1]] # assuming the new_d is atmost old_d self.array[idx] = (new_d, tup[1]) while idx > 0 and self.array[self.par(idx)][0] > self.array[idx][0]: self.swap(idx, self.par(idx)) idx = self.par(idx) class Graph: def __init__(self, num): self.adjList = {} # To store graph: u -> (v,w) self.num_nodes = num # Number of nodes in graph # To store the distance from source vertex self.dist = [0] * self.num_nodes self.par = [-1] * self.num_nodes # To store the path def add_edge(self, u, v, w): # Edge going from node u to v and v to u with weight w # u (w)-> v, v (w) -> u # Check if u already in graph if u in self.adjList.keys(): self.adjList[u].append((v, w)) else: self.adjList[u] = [(v, w)] # Assuming undirected graph if v in self.adjList.keys(): self.adjList[v].append((u, w)) else: self.adjList[v] = [(u, w)] def show_graph(self): # u -> v(w) for u in self.adjList: print(u, '->', ' -> '.join(str("{}({})".format(v, w)) for v, w in self.adjList[u])) def dijkstra(self, src): # Flush old junk values in par[] self.par = [-1] * self.num_nodes # src is the source node self.dist[src] = 0 Q = PriorityQueue() Q.insert((0, src)) # (dist from src, node) for u in self.adjList.keys(): if u != src: self.dist[u] = sys.maxsize # Infinity self.par[u] = -1 while not Q.isEmpty(): u = Q.extract_min() # Returns node with the min dist from source # Update the distance of all the neighbours of u and # if their prev dist was INFINITY then push them in Q for v, w in self.adjList[u]: new_dist = self.dist[u] + w if self.dist[v] > new_dist: if self.dist[v] == sys.maxsize: Q.insert((new_dist, v)) else: Q.decrease_key((self.dist[v], v), new_dist) self.dist[v] = new_dist self.par[v] = u # Show the shortest distances from src self.show_distances(src) def show_distances(self, src): print("Distance from node: {}".format(src)) for u in range(self.num_nodes): print('Node {} has distance: {}'.format(u, self.dist[u])) def show_path(self, src, dest): # To show the shortest path from src to dest # WARNING: Use it *after* calling dijkstra path = [] cost = 0 temp = dest # Backtracking from dest to src while self.par[temp] != -1: path.append(temp) if temp != src: for v, w in self.adjList[temp]: if v == self.par[temp]: cost += w break temp = self.par[temp] path.append(src) path.reverse() print('----Path to reach {} from {}----'.format(dest, src)) for u in path: print('{}'.format(u), end=' ') if u != dest: print('-> ', end='') print('\nTotal cost of path: ', cost) if __name__ == '__main__': graph = Graph(9) graph.add_edge(0, 1, 4) graph.add_edge(0, 7, 8) graph.add_edge(1, 2, 8) graph.add_edge(1, 7, 11) graph.add_edge(2, 3, 7) graph.add_edge(2, 8, 2) graph.add_edge(2, 5, 4) graph.add_edge(3, 4, 9) graph.add_edge(3, 5, 14) graph.add_edge(4, 5, 10) graph.add_edge(5, 6, 2) graph.add_edge(6, 7, 1) graph.add_edge(6, 8, 6) graph.add_edge(7, 8, 7) graph.show_graph() graph.dijkstra(0) graph.show_path(0, 4) # OUTPUT # 0 -> 1(4) -> 7(8) # 1 -> 0(4) -> 2(8) -> 7(11) # 7 -> 0(8) -> 1(11) -> 6(1) -> 8(7) # 2 -> 1(8) -> 3(7) -> 8(2) -> 5(4) # 3 -> 2(7) -> 4(9) -> 5(14) # 8 -> 2(2) -> 6(6) -> 7(7) # 5 -> 2(4) -> 3(14) -> 4(10) -> 6(2) # 4 -> 3(9) -> 5(10) # 6 -> 5(2) -> 7(1) -> 8(6) # Distance from node: 0 # Node 0 has distance: 0 # Node 1 has distance: 4 # Node 2 has distance: 12 # Node 3 has distance: 19 # Node 4 has distance: 21 # Node 5 has distance: 11 # Node 6 has distance: 9 # Node 7 has distance: 8 # Node 8 has distance: 14 # ----Path to reach 4 from 0---- # 0 -> 7 -> 6 -> 5 -> 4 # Total cost of path: 21
[]
[]
[]
archives/1098994933_python.zip
graphs/directed_and_undirected_(weighted)_graph.py
from collections import deque import random as rand import math as math import time # the dfault weight is 1 if not assigend but all the implementation is weighted class DirectedGraph: def __init__(self): self.graph = {} # adding vertices and edges # adding the weight is optional # handels repetition def add_pair(self, u, v, w = 1): if self.graph.get(u): if self.graph[u].count([w,v]) == 0: self.graph[u].append([w, v]) else: self.graph[u] = [[w, v]] if not self.graph.get(v): self.graph[v] = [] def all_nodes(self): return list(self.graph) # handels if the input does not exist def remove_pair(self, u, v): if self.graph.get(u): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(_) # if no destination is meant the defaut value is -1 def dfs(self, s = -2, d = -1): if s == d: return [] stack = [] visited = [] if s == -2: s = list(self.graph.keys())[0] stack.append(s) visited.append(s) ss = s while True: # check if there is any non isolated nodes if len(self.graph[s]) != 0: ss = s for __ in self.graph[s]: if visited.count(__[1]) < 1: if __[1] == d: visited.append(d) return visited else: stack.append(__[1]) visited.append(__[1]) ss =__[1] break # check if all the children are visited if s == ss : stack.pop() if len(stack) != 0: s = stack[len(stack) - 1] else: s = ss # check if se have reached the starting point if len(stack) == 0: return visited # c is the count of nodes you want and if you leave it or pass -1 to the funtion the count # will be random from 10 to 10000 def fill_graph_randomly(self, c = -1): if c == -1: c = (math.floor(rand.random() * 10000)) + 10 for _ in range(c): # every vertex has max 100 edges e = math.floor(rand.random() * 102) + 1 for __ in range(e): n = math.floor(rand.random() * (c)) + 1 if n == _: continue self.add_pair(_, n, 1) def bfs(self, s = -2): d = deque() visited = [] if s == -2: s = list(self.graph.keys())[0] d.append(s) visited.append(s) while d: s = d.popleft() if len(self.graph[s]) != 0: for __ in self.graph[s]: if visited.count(__[1]) < 1: d.append(__[1]) visited.append(__[1]) return visited def in_degree(self, u): count = 0 for _ in self.graph: for __ in self.graph[_]: if __[1] == u: count += 1 return count def out_degree(self, u): return len(self.graph[u]) def topological_sort(self, s = -2): stack = [] visited = [] if s == -2: s = list(self.graph.keys())[0] stack.append(s) visited.append(s) ss = s sorted_nodes = [] while True: # check if there is any non isolated nodes if len(self.graph[s]) != 0: ss = s for __ in self.graph[s]: if visited.count(__[1]) < 1: stack.append(__[1]) visited.append(__[1]) ss =__[1] break # check if all the children are visited if s == ss : sorted_nodes.append(stack.pop()) if len(stack) != 0: s = stack[len(stack) - 1] else: s = ss # check if se have reached the starting point if len(stack) == 0: return sorted_nodes def cycle_nodes(self): stack = [] visited = [] s = list(self.graph.keys())[0] stack.append(s) visited.append(s) parent = -2 indirect_parents = [] ss = s on_the_way_back = False anticipating_nodes = set() while True: # check if there is any non isolated nodes if len(self.graph[s]) != 0: ss = s for __ in self.graph[s]: if visited.count(__[1]) > 0 and __[1] != parent and indirect_parents.count(__[1]) > 0 and not on_the_way_back: l = len(stack) - 1 while True and l >= 0: if stack[l] == __[1]: anticipating_nodes.add(__[1]) break else: anticipating_nodes.add(stack[l]) l -= 1 if visited.count(__[1]) < 1: stack.append(__[1]) visited.append(__[1]) ss =__[1] break # check if all the children are visited if s == ss : stack.pop() on_the_way_back = True if len(stack) != 0: s = stack[len(stack) - 1] else: on_the_way_back = False indirect_parents.append(parent) parent = s s = ss # check if se have reached the starting point if len(stack) == 0: return list(anticipating_nodes) def has_cycle(self): stack = [] visited = [] s = list(self.graph.keys())[0] stack.append(s) visited.append(s) parent = -2 indirect_parents = [] ss = s on_the_way_back = False anticipating_nodes = set() while True: # check if there is any non isolated nodes if len(self.graph[s]) != 0: ss = s for __ in self.graph[s]: if visited.count(__[1]) > 0 and __[1] != parent and indirect_parents.count(__[1]) > 0 and not on_the_way_back: l = len(stack) - 1 while True and l >= 0: if stack[l] == __[1]: anticipating_nodes.add(__[1]) break else: return True anticipating_nodes.add(stack[l]) l -= 1 if visited.count(__[1]) < 1: stack.append(__[1]) visited.append(__[1]) ss =__[1] break # check if all the children are visited if s == ss : stack.pop() on_the_way_back = True if len(stack) != 0: s = stack[len(stack) - 1] else: on_the_way_back = False indirect_parents.append(parent) parent = s s = ss # check if se have reached the starting point if len(stack) == 0: return False def dfs_time(self, s = -2, e = -1): begin = time.time() self.dfs(s,e) end = time.time() return end - begin def bfs_time(self, s = -2): begin = time.time() self.bfs(s) end = time.time() return end - begin class Graph: def __init__(self): self.graph = {} # adding vertices and edges # adding the weight is optional # handels repetition def add_pair(self, u, v, w = 1): # check if the u exists if self.graph.get(u): # if there already is a edge if self.graph[u].count([w,v]) == 0: self.graph[u].append([w, v]) else: # if u does not exist self.graph[u] = [[w, v]] # add the other way if self.graph.get(v): # if there already is a edge if self.graph[v].count([w,u]) == 0: self.graph[v].append([w, u]) else: # if u does not exist self.graph[v] = [[w, u]] # handels if the input does not exist def remove_pair(self, u, v): if self.graph.get(u): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(_) # the other way round if self.graph.get(v): for _ in self.graph[v]: if _[1] == u: self.graph[v].remove(_) # if no destination is meant the defaut value is -1 def dfs(self, s = -2, d = -1): if s == d: return [] stack = [] visited = [] if s == -2: s = list(self.graph.keys())[0] stack.append(s) visited.append(s) ss = s while True: # check if there is any non isolated nodes if len(self.graph[s]) != 0: ss = s for __ in self.graph[s]: if visited.count(__[1]) < 1: if __[1] == d: visited.append(d) return visited else: stack.append(__[1]) visited.append(__[1]) ss =__[1] break # check if all the children are visited if s == ss : stack.pop() if len(stack) != 0: s = stack[len(stack) - 1] else: s = ss # check if se have reached the starting point if len(stack) == 0: return visited # c is the count of nodes you want and if you leave it or pass -1 to the funtion the count # will be random from 10 to 10000 def fill_graph_randomly(self, c = -1): if c == -1: c = (math.floor(rand.random() * 10000)) + 10 for _ in range(c): # every vertex has max 100 edges e = math.floor(rand.random() * 102) + 1 for __ in range(e): n = math.floor(rand.random() * (c)) + 1 if n == _: continue self.add_pair(_, n, 1) def bfs(self, s = -2): d = deque() visited = [] if s == -2: s = list(self.graph.keys())[0] d.append(s) visited.append(s) while d: s = d.popleft() if len(self.graph[s]) != 0: for __ in self.graph[s]: if visited.count(__[1]) < 1: d.append(__[1]) visited.append(__[1]) return visited def degree(self, u): return len(self.graph[u]) def cycle_nodes(self): stack = [] visited = [] s = list(self.graph.keys())[0] stack.append(s) visited.append(s) parent = -2 indirect_parents = [] ss = s on_the_way_back = False anticipating_nodes = set() while True: # check if there is any non isolated nodes if len(self.graph[s]) != 0: ss = s for __ in self.graph[s]: if visited.count(__[1]) > 0 and __[1] != parent and indirect_parents.count(__[1]) > 0 and not on_the_way_back: l = len(stack) - 1 while True and l >= 0: if stack[l] == __[1]: anticipating_nodes.add(__[1]) break else: anticipating_nodes.add(stack[l]) l -= 1 if visited.count(__[1]) < 1: stack.append(__[1]) visited.append(__[1]) ss =__[1] break # check if all the children are visited if s == ss : stack.pop() on_the_way_back = True if len(stack) != 0: s = stack[len(stack) - 1] else: on_the_way_back = False indirect_parents.append(parent) parent = s s = ss # check if se have reached the starting point if len(stack) == 0: return list(anticipating_nodes) def has_cycle(self): stack = [] visited = [] s = list(self.graph.keys())[0] stack.append(s) visited.append(s) parent = -2 indirect_parents = [] ss = s on_the_way_back = False anticipating_nodes = set() while True: # check if there is any non isolated nodes if len(self.graph[s]) != 0: ss = s for __ in self.graph[s]: if visited.count(__[1]) > 0 and __[1] != parent and indirect_parents.count(__[1]) > 0 and not on_the_way_back: l = len(stack) - 1 while True and l >= 0: if stack[l] == __[1]: anticipating_nodes.add(__[1]) break else: return True anticipating_nodes.add(stack[l]) l -= 1 if visited.count(__[1]) < 1: stack.append(__[1]) visited.append(__[1]) ss =__[1] break # check if all the children are visited if s == ss : stack.pop() on_the_way_back = True if len(stack) != 0: s = stack[len(stack) - 1] else: on_the_way_back = False indirect_parents.append(parent) parent = s s = ss # check if se have reached the starting point if len(stack) == 0: return False def all_nodes(self): return list(self.graph) def dfs_time(self, s = -2, e = -1): begin = time.time() self.dfs(s,e) end = time.time() return end - begin def bfs_time(self, s = -2): begin = time.time() self.bfs(s) end = time.time() return end - begin
[]
[]
[]
archives/1098994933_python.zip
graphs/edmonds_karp_multiple_source_and_sink.py
class FlowNetwork: def __init__(self, graph, sources, sinks): self.sourceIndex = None self.sinkIndex = None self.graph = graph self._normalizeGraph(sources, sinks) self.verticesCount = len(graph) self.maximumFlowAlgorithm = None # make only one source and one sink def _normalizeGraph(self, sources, sinks): if sources is int: sources = [sources] if sinks is int: sinks = [sinks] if len(sources) == 0 or len(sinks) == 0: return self.sourceIndex = sources[0] self.sinkIndex = sinks[0] # make fake vertex if there are more # than one source or sink if len(sources) > 1 or len(sinks) > 1: maxInputFlow = 0 for i in sources: maxInputFlow += sum(self.graph[i]) size = len(self.graph) + 1 for room in self.graph: room.insert(0, 0) self.graph.insert(0, [0] * size) for i in sources: self.graph[0][i + 1] = maxInputFlow self.sourceIndex = 0 size = len(self.graph) + 1 for room in self.graph: room.append(0) self.graph.append([0] * size) for i in sinks: self.graph[i + 1][size - 1] = maxInputFlow self.sinkIndex = size - 1 def findMaximumFlow(self): if self.maximumFlowAlgorithm is None: raise Exception("You need to set maximum flow algorithm before.") if self.sourceIndex is None or self.sinkIndex is None: return 0 self.maximumFlowAlgorithm.execute() return self.maximumFlowAlgorithm.getMaximumFlow() def setMaximumFlowAlgorithm(self, Algorithm): self.maximumFlowAlgorithm = Algorithm(self) class FlowNetworkAlgorithmExecutor(object): def __init__(self, flowNetwork): self.flowNetwork = flowNetwork self.verticesCount = flowNetwork.verticesCount self.sourceIndex = flowNetwork.sourceIndex self.sinkIndex = flowNetwork.sinkIndex # it's just a reference, so you shouldn't change # it in your algorithms, use deep copy before doing that self.graph = flowNetwork.graph self.executed = False def execute(self): if not self.executed: self._algorithm() self.executed = True # You should override it def _algorithm(self): pass class MaximumFlowAlgorithmExecutor(FlowNetworkAlgorithmExecutor): def __init__(self, flowNetwork): super(MaximumFlowAlgorithmExecutor, self).__init__(flowNetwork) # use this to save your result self.maximumFlow = -1 def getMaximumFlow(self): if not self.executed: raise Exception("You should execute algorithm before using its result!") return self.maximumFlow class PushRelabelExecutor(MaximumFlowAlgorithmExecutor): def __init__(self, flowNetwork): super(PushRelabelExecutor, self).__init__(flowNetwork) self.preflow = [[0] * self.verticesCount for i in range(self.verticesCount)] self.heights = [0] * self.verticesCount self.excesses = [0] * self.verticesCount def _algorithm(self): self.heights[self.sourceIndex] = self.verticesCount # push some substance to graph for nextVertexIndex, bandwidth in enumerate(self.graph[self.sourceIndex]): self.preflow[self.sourceIndex][nextVertexIndex] += bandwidth self.preflow[nextVertexIndex][self.sourceIndex] -= bandwidth self.excesses[nextVertexIndex] += bandwidth # Relabel-to-front selection rule verticesList = [i for i in range(self.verticesCount) if i != self.sourceIndex and i != self.sinkIndex] # move through list i = 0 while i < len(verticesList): vertexIndex = verticesList[i] previousHeight = self.heights[vertexIndex] self.processVertex(vertexIndex) if self.heights[vertexIndex] > previousHeight: # if it was relabeled, swap elements # and start from 0 index verticesList.insert(0, verticesList.pop(i)) i = 0 else: i += 1 self.maximumFlow = sum(self.preflow[self.sourceIndex]) def processVertex(self, vertexIndex): while self.excesses[vertexIndex] > 0: for neighbourIndex in range(self.verticesCount): # if it's neighbour and current vertex is higher if self.graph[vertexIndex][neighbourIndex] - self.preflow[vertexIndex][neighbourIndex] > 0\ and self.heights[vertexIndex] > self.heights[neighbourIndex]: self.push(vertexIndex, neighbourIndex) self.relabel(vertexIndex) def push(self, fromIndex, toIndex): preflowDelta = min(self.excesses[fromIndex], self.graph[fromIndex][toIndex] - self.preflow[fromIndex][toIndex]) self.preflow[fromIndex][toIndex] += preflowDelta self.preflow[toIndex][fromIndex] -= preflowDelta self.excesses[fromIndex] -= preflowDelta self.excesses[toIndex] += preflowDelta def relabel(self, vertexIndex): minHeight = None for toIndex in range(self.verticesCount): if self.graph[vertexIndex][toIndex] - self.preflow[vertexIndex][toIndex] > 0: if minHeight is None or self.heights[toIndex] < minHeight: minHeight = self.heights[toIndex] if minHeight is not None: self.heights[vertexIndex] = minHeight + 1 if __name__ == '__main__': entrances = [0] exits = [3] # graph = [ # [0, 0, 4, 6, 0, 0], # [0, 0, 5, 2, 0, 0], # [0, 0, 0, 0, 4, 4], # [0, 0, 0, 0, 6, 6], # [0, 0, 0, 0, 0, 0], # [0, 0, 0, 0, 0, 0], # ] graph = [[0, 7, 0, 0], [0, 0, 6, 0], [0, 0, 0, 8], [9, 0, 0, 0]] # prepare our network flowNetwork = FlowNetwork(graph, entrances, exits) # set algorithm flowNetwork.setMaximumFlowAlgorithm(PushRelabelExecutor) # and calculate maximumFlow = flowNetwork.findMaximumFlow() print("maximum flow is {}".format(maximumFlow))
[]
[]
[]
archives/1098994933_python.zip
graphs/eulerian_path_and_circuit_for_undirected_graph.py
# Eulerian Path is a path in graph that visits every edge exactly once. # Eulerian Circuit is an Eulerian Path which starts and ends on the same # vertex. # time complexity is O(V+E) # space complexity is O(VE) # using dfs for finding eulerian path traversal def dfs(u, graph, visited_edge, path=[]): path = path + [u] for v in graph[u]: if visited_edge[u][v] == False: visited_edge[u][v], visited_edge[v][u] = True, True path = dfs(v, graph, visited_edge, path) return path # for checking in graph has euler path or circuit def check_circuit_or_path(graph, max_node): odd_degree_nodes = 0 odd_node = -1 for i in range(max_node): if i not in graph.keys(): continue if len(graph[i]) % 2 == 1: odd_degree_nodes += 1 odd_node = i if odd_degree_nodes == 0: return 1, odd_node if odd_degree_nodes == 2: return 2, odd_node return 3, odd_node def check_euler(graph, max_node): visited_edge = [[False for _ in range(max_node + 1)] for _ in range(max_node + 1)] check, odd_node = check_circuit_or_path(graph, max_node) if check == 3: print("graph is not Eulerian") print("no path") return start_node = 1 if check == 2: start_node = odd_node print("graph has a Euler path") if check == 1: print("graph has a Euler cycle") path = dfs(start_node, graph, visited_edge) print(path) def main(): G1 = { 1: [2, 3, 4], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [4] } G2 = { 1: [2, 3, 4, 5], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [1, 4] } G3 = { 1: [2, 3, 4], 2: [1, 3, 4], 3: [1, 2], 4: [1, 2, 5], 5: [4] } G4 = { 1: [2, 3], 2: [1, 3], 3: [1, 2], } G5 = { 1: [], 2: [] # all degree is zero } max_node = 10 check_euler(G1, max_node) check_euler(G2, max_node) check_euler(G3, max_node) check_euler(G4, max_node) check_euler(G5, max_node) if __name__ == "__main__": main()
[]
[]
[]
archives/1098994933_python.zip
graphs/even_tree.py
""" You are given a tree(a simple connected graph with no cycles). The tree has N nodes numbered from 1 to N and is rooted at node 1. Find the maximum number of edges you can remove from the tree to get a forest such that each connected component of the forest contains an even number of nodes. Constraints 2 <= 2 <= 100 Note: The tree input will be such that it can always be decomposed into components containing an even number of nodes. """ # pylint: disable=invalid-name from collections import defaultdict def dfs(start): """DFS traversal""" # pylint: disable=redefined-outer-name ret = 1 visited[start] = True for v in tree.get(start): if v not in visited: ret += dfs(v) if ret % 2 == 0: cuts.append(start) return ret def even_tree(): """ 2 1 3 1 4 3 5 2 6 1 7 2 8 6 9 8 10 8 On removing edges (1,3) and (1,6), we can get the desired result 2. """ dfs(1) if __name__ == '__main__': n, m = 10, 9 tree = defaultdict(list) visited = {} cuts = [] count = 0 edges = [ (2, 1), (3, 1), (4, 3), (5, 2), (6, 1), (7, 2), (8, 6), (9, 8), (10, 8), ] for u, v in edges: tree[u].append(v) tree[v].append(u) even_tree() print(len(cuts) - 1)
[]
[]
[]
archives/1098994933_python.zip
graphs/finding_bridges.py
# Finding Bridges in Undirected Graph def computeBridges(l): id = 0 n = len(l) # No of vertices in graph low = [0] * n visited = [False] * n def dfs(at, parent, bridges, id): visited[at] = True low[at] = id id += 1 for to in l[at]: if to == parent: pass elif not visited[to]: dfs(to, at, bridges, id) low[at] = min(low[at], low[to]) if at < low[to]: bridges.append([at, to]) else: # This edge is a back edge and cannot be a bridge low[at] = min(low[at], to) bridges = [] for i in range(n): if (not visited[i]): dfs(i, -1, bridges, id) print(bridges) l = {0:[1,2], 1:[0,2], 2:[0,1,3,5], 3:[2,4], 4:[3], 5:[2,6,8], 6:[5,7], 7:[6,8], 8:[5,7]} computeBridges(l)
[]
[]
[]
archives/1098994933_python.zip
graphs/graph_list.py
#!/usr/bin/python # encoding=utf8 # Author: OMKAR PATHAK # We can use Python's dictionary for constructing the graph. class AdjacencyList(object): def __init__(self): self.List = {} def addEdge(self, fromVertex, toVertex): # check if vertex is already present if fromVertex in self.List.keys(): self.List[fromVertex].append(toVertex) else: self.List[fromVertex] = [toVertex] def printList(self): for i in self.List: print((i,'->',' -> '.join([str(j) for j in self.List[i]]))) if __name__ == '__main__': al = AdjacencyList() al.addEdge(0, 1) al.addEdge(0, 4) al.addEdge(4, 1) al.addEdge(4, 3) al.addEdge(1, 0) al.addEdge(1, 4) al.addEdge(1, 3) al.addEdge(1, 2) al.addEdge(2, 3) al.addEdge(3, 4) al.printList() # OUTPUT: # 0 -> 1 -> 4 # 1 -> 0 -> 4 -> 3 -> 2 # 2 -> 3 # 3 -> 4 # 4 -> 1 -> 3
[]
[]
[]
archives/1098994933_python.zip
graphs/graph_matrix.py
class Graph: def __init__(self, vertex): self.vertex = vertex self.graph = [[0] * vertex for i in range(vertex) ] def add_edge(self, u, v): self.graph[u - 1][v - 1] = 1 self.graph[v - 1][u - 1] = 1 def show(self): for i in self.graph: for j in i: print(j, end=' ') print(' ') g = Graph(100) g.add_edge(1,4) g.add_edge(4,2) g.add_edge(4,5) g.add_edge(2,5) g.add_edge(5,3) g.show()
[]
[]
[]
archives/1098994933_python.zip
graphs/graphs_floyd_warshall.py
# floyd_warshall.py """ The problem is to find the shortest distance between all pairs of vertices in a weighted directed graph that can have negative edge weights. """ def _print_dist(dist, v): print("\nThe shortest path matrix using Floyd Warshall algorithm\n") for i in range(v): for j in range(v): if dist[i][j] != float('inf') : print(int(dist[i][j]),end = "\t") else: print("INF",end="\t") print() def floyd_warshall(graph, v): """ :param graph: 2D array calculated from weight[edge[i, j]] :type graph: List[List[float]] :param v: number of vertices :type v: int :return: shortest distance between all vertex pairs distance[u][v] will contain the shortest distance from vertex u to v. 1. For all edges from v to n, distance[i][j] = weight(edge(i, j)). 3. The algorithm then performs distance[i][j] = min(distance[i][j], distance[i][k] + distance[k][j]) for each possible pair i, j of vertices. 4. The above is repeated for each vertex k in the graph. 5. Whenever distance[i][j] is given a new minimum value, next vertex[i][j] is updated to the next vertex[i][k]. """ dist=[[float('inf') for _ in range(v)] for _ in range(v)] for i in range(v): for j in range(v): dist[i][j] = graph[i][j] # check vertex k against all other vertices (i, j) for k in range(v): # looping through rows of graph array for i in range(v): # looping through columns of graph array for j in range(v): if dist[i][k]!=float('inf') and dist[k][j]!=float('inf') and dist[i][k]+dist[k][j] < dist[i][j]: dist[i][j] = dist[i][k] + dist[k][j] _print_dist(dist, v) return dist, v if __name__== '__main__': v = int(input("Enter number of vertices: ")) e = int(input("Enter number of edges: ")) graph = [[float('inf') for i in range(v)] for j in range(v)] for i in range(v): graph[i][i] = 0.0 # src and dst are indices that must be within the array size graph[e][v] # failure to follow this will result in an error for i in range(e): print("\nEdge ",i+1) src = int(input("Enter source:")) dst = int(input("Enter destination:")) weight = float(input("Enter weight:")) graph[src][dst] = weight floyd_warshall(graph, v) # Example Input # Enter number of vertices: 3 # Enter number of edges: 2 # # generated graph from vertex and edge inputs # [[inf, inf, inf], [inf, inf, inf], [inf, inf, inf]] # [[0.0, inf, inf], [inf, 0.0, inf], [inf, inf, 0.0]] # specify source, destination and weight for edge #1 # Edge 1 # Enter source:1 # Enter destination:2 # Enter weight:2 # specify source, destination and weight for edge #2 # Edge 2 # Enter source:2 # Enter destination:1 # Enter weight:1 # # Expected Output from the vertice, edge and src, dst, weight inputs!! # 0 INF INF # INF 0 2 # INF 1 0
[]
[]
[]
archives/1098994933_python.zip
graphs/kahns_algorithm_long.py
# Finding longest distance in Directed Acyclic Graph using KahnsAlgorithm def longestDistance(l): indegree = [0] * len(l) queue = [] longDist = [1] * len(l) for key, values in l.items(): for i in values: indegree[i] += 1 for i in range(len(indegree)): if indegree[i] == 0: queue.append(i) while(queue): vertex = queue.pop(0) for x in l[vertex]: indegree[x] -= 1 if longDist[vertex] + 1 > longDist[x]: longDist[x] = longDist[vertex] + 1 if indegree[x] == 0: queue.append(x) print(max(longDist)) # Adjacency list of Graph l = {0:[2,3,4], 1:[2,7], 2:[5], 3:[5,7], 4:[7], 5:[6], 6:[7], 7:[]} longestDistance(l)
[]
[]
[]
archives/1098994933_python.zip
graphs/kahns_algorithm_topo.py
# Kahn's Algorithm is used to find Topological ordering of Directed Acyclic Graph using BFS def topologicalSort(l): indegree = [0] * len(l) queue = [] topo = [] cnt = 0 for key, values in l.items(): for i in values: indegree[i] += 1 for i in range(len(indegree)): if indegree[i] == 0: queue.append(i) while(queue): vertex = queue.pop(0) cnt += 1 topo.append(vertex) for x in l[vertex]: indegree[x] -= 1 if indegree[x] == 0: queue.append(x) if cnt != len(l): print("Cycle exists") else: print(topo) # Adjacency List of Graph l = {0:[1,2], 1:[3], 2:[3], 3:[4,5], 4:[], 5:[]} topologicalSort(l)
[]
[]
[]
archives/1098994933_python.zip
graphs/minimum_spanning_tree_kruskal.py
if __name__ == "__main__": num_nodes, num_edges = list(map(int, input().strip().split())) edges = [] for i in range(num_edges): node1, node2, cost = list(map(int, input().strip().split())) edges.append((i,node1,node2,cost)) edges = sorted(edges, key=lambda edge: edge[3]) parent = list(range(num_nodes)) def find_parent(i): if i != parent[i]: parent[i] = find_parent(parent[i]) return parent[i] minimum_spanning_tree_cost = 0 minimum_spanning_tree = [] for edge in edges: parent_a = find_parent(edge[1]) parent_b = find_parent(edge[2]) if parent_a != parent_b: minimum_spanning_tree_cost += edge[3] minimum_spanning_tree.append(edge) parent[parent_a] = parent_b print(minimum_spanning_tree_cost) for edge in minimum_spanning_tree: print(edge)
[]
[]
[]
archives/1098994933_python.zip
graphs/minimum_spanning_tree_prims.py
import sys from collections import defaultdict def PrimsAlgorithm(l): nodePosition = [] def getPosition(vertex): return nodePosition[vertex] def setPosition(vertex, pos): nodePosition[vertex] = pos def topToBottom(heap, start, size, positions): if start > size // 2 - 1: return else: if 2 * start + 2 >= size: m = 2 * start + 1 else: if heap[2 * start + 1] < heap[2 * start + 2]: m = 2 * start + 1 else: m = 2 * start + 2 if heap[m] < heap[start]: temp, temp1 = heap[m], positions[m] heap[m], positions[m] = heap[start], positions[start] heap[start], positions[start] = temp, temp1 temp = getPosition(positions[m]) setPosition(positions[m], getPosition(positions[start])) setPosition(positions[start], temp) topToBottom(heap, m, size, positions) # Update function if value of any node in min-heap decreases def bottomToTop(val, index, heap, position): temp = position[index] while(index != 0): if index % 2 == 0: parent = int( (index-2) / 2 ) else: parent = int( (index-1) / 2 ) if val < heap[parent]: heap[index] = heap[parent] position[index] = position[parent] setPosition(position[parent], index) else: heap[index] = val position[index] = temp setPosition(temp, index) break index = parent else: heap[0] = val position[0] = temp setPosition(temp, 0) def heapify(heap, positions): start = len(heap) // 2 - 1 for i in range(start, -1, -1): topToBottom(heap, i, len(heap), positions) def deleteMinimum(heap, positions): temp = positions[0] heap[0] = sys.maxsize topToBottom(heap, 0, len(heap), positions) return temp visited = [0 for i in range(len(l))] Nbr_TV = [-1 for i in range(len(l))] # Neighboring Tree Vertex of selected vertex # Minimum Distance of explored vertex with neighboring vertex of partial tree formed in graph Distance_TV = [] # Heap of Distance of vertices from their neighboring vertex Positions = [] for x in range(len(l)): p = sys.maxsize Distance_TV.append(p) Positions.append(x) nodePosition.append(x) TreeEdges = [] visited[0] = 1 Distance_TV[0] = sys.maxsize for x in l[0]: Nbr_TV[ x[0] ] = 0 Distance_TV[ x[0] ] = x[1] heapify(Distance_TV, Positions) for i in range(1, len(l)): vertex = deleteMinimum(Distance_TV, Positions) if visited[vertex] == 0: TreeEdges.append((Nbr_TV[vertex], vertex)) visited[vertex] = 1 for v in l[vertex]: if visited[v[0]] == 0 and v[1] < Distance_TV[ getPosition(v[0]) ]: Distance_TV[ getPosition(v[0]) ] = v[1] bottomToTop(v[1], getPosition(v[0]), Distance_TV, Positions) Nbr_TV[ v[0] ] = vertex return TreeEdges if __name__ == "__main__": # < --------- Prims Algorithm --------- > n = int(input("Enter number of vertices: ").strip()) e = int(input("Enter number of edges: ").strip()) adjlist = defaultdict(list) for x in range(e): l = [int(x) for x in input().strip().split()] adjlist[l[0]].append([ l[1], l[2] ]) adjlist[l[1]].append([ l[0], l[2] ]) print(PrimsAlgorithm(adjlist))
[]
[]
[]
archives/1098994933_python.zip
graphs/multi_hueristic_astar.py
import heapq import numpy as np class PriorityQueue: def __init__(self): self.elements = [] self.set = set() def minkey(self): if not self.empty(): return self.elements[0][0] else: return float('inf') def empty(self): return len(self.elements) == 0 def put(self, item, priority): if item not in self.set: heapq.heappush(self.elements, (priority, item)) self.set.add(item) else: # update # print("update", item) temp = [] (pri, x) = heapq.heappop(self.elements) while x != item: temp.append((pri, x)) (pri, x) = heapq.heappop(self.elements) temp.append((priority, item)) for (pro, xxx) in temp: heapq.heappush(self.elements, (pro, xxx)) def remove_element(self, item): if item in self.set: self.set.remove(item) temp = [] (pro, x) = heapq.heappop(self.elements) while x != item: temp.append((pro, x)) (pro, x) = heapq.heappop(self.elements) for (prito, yyy) in temp: heapq.heappush(self.elements, (prito, yyy)) def top_show(self): return self.elements[0][1] def get(self): (priority, item) = heapq.heappop(self.elements) self.set.remove(item) return (priority, item) def consistent_hueristic(P, goal): # euclidean distance a = np.array(P) b = np.array(goal) return np.linalg.norm(a - b) def hueristic_2(P, goal): # integer division by time variable return consistent_hueristic(P, goal) // t def hueristic_1(P, goal): # manhattan distance return abs(P[0] - goal[0]) + abs(P[1] - goal[1]) def key(start, i, goal, g_function): ans = g_function[start] + W1 * hueristics[i](start, goal) return ans def do_something(back_pointer, goal, start): grid = np.chararray((n, n)) for i in range(n): for j in range(n): grid[i][j] = '*' for i in range(n): for j in range(n): if (j, (n-1)-i) in blocks: grid[i][j] = "#" grid[0][(n-1)] = "-" x = back_pointer[goal] while x != start: (x_c, y_c) = x # print(x) grid[(n-1)-y_c][x_c] = "-" x = back_pointer[x] grid[(n-1)][0] = "-" for i in range(n): for j in range(n): if (i, j) == (0, n-1): print(grid[i][j], end=' ') print("<-- End position", end=' ') else: print(grid[i][j], end=' ') print() print("^") print("Start position") print() print("# is an obstacle") print("- is the path taken by algorithm") print("PATH TAKEN BY THE ALGORITHM IS:-") x = back_pointer[goal] while x != start: print(x, end=' ') x = back_pointer[x] print(x) quit() def valid(p): if p[0] < 0 or p[0] > n-1: return False if p[1] < 0 or p[1] > n-1: return False return True def expand_state(s, j, visited, g_function, close_list_anchor, close_list_inad, open_list, back_pointer): for itera in range(n_hueristic): open_list[itera].remove_element(s) # print("s", s) # print("j", j) (x, y) = s left = (x-1, y) right = (x+1, y) up = (x, y+1) down = (x, y-1) for neighbours in [left, right, up, down]: if neighbours not in blocks: if valid(neighbours) and neighbours not in visited: # print("neighbour", neighbours) visited.add(neighbours) back_pointer[neighbours] = -1 g_function[neighbours] = float('inf') if valid(neighbours) and g_function[neighbours] > g_function[s] + 1: g_function[neighbours] = g_function[s] + 1 back_pointer[neighbours] = s if neighbours not in close_list_anchor: open_list[0].put(neighbours, key(neighbours, 0, goal, g_function)) if neighbours not in close_list_inad: for var in range(1,n_hueristic): if key(neighbours, var, goal, g_function) <= W2 * key(neighbours, 0, goal, g_function): # print("why not plssssssssss") open_list[j].put(neighbours, key(neighbours, var, goal, g_function)) # print def make_common_ground(): some_list = [] # block 1 for x in range(1, 5): for y in range(1, 6): some_list.append((x, y)) # line for x in range(15, 20): some_list.append((x, 17)) # block 2 big for x in range(10, 19): for y in range(1, 15): some_list.append((x, y)) # L block for x in range(1, 4): for y in range(12, 19): some_list.append((x, y)) for x in range(3, 13): for y in range(16, 19): some_list.append((x, y)) return some_list hueristics = {0: consistent_hueristic, 1: hueristic_1, 2: hueristic_2} blocks_blk = [(0, 1),(1, 1),(2, 1),(3, 1),(4, 1),(5, 1),(6, 1),(7, 1),(8, 1),(9, 1),(10, 1),(11, 1),(12, 1),(13, 1),(14, 1),(15, 1),(16, 1),(17, 1),(18, 1), (19, 1)] blocks_no = [] blocks_all = make_common_ground() blocks = blocks_blk # hyper parameters W1 = 1 W2 = 1 n = 20 n_hueristic = 3 # one consistent and two other inconsistent # start and end destination start = (0, 0) goal = (n-1, n-1) t = 1 def multi_a_star(start, goal, n_hueristic): g_function = {start: 0, goal: float('inf')} back_pointer = {start:-1, goal:-1} open_list = [] visited = set() for i in range(n_hueristic): open_list.append(PriorityQueue()) open_list[i].put(start, key(start, i, goal, g_function)) close_list_anchor = [] close_list_inad = [] while open_list[0].minkey() < float('inf'): for i in range(1, n_hueristic): # print("i", i) # print(open_list[0].minkey(), open_list[i].minkey()) if open_list[i].minkey() <= W2 * open_list[0].minkey(): global t t += 1 # print("less prio") if g_function[goal] <= open_list[i].minkey(): if g_function[goal] < float('inf'): do_something(back_pointer, goal, start) else: _, get_s = open_list[i].top_show() visited.add(get_s) expand_state(get_s, i, visited, g_function, close_list_anchor, close_list_inad, open_list, back_pointer) close_list_inad.append(get_s) else: # print("more prio") if g_function[goal] <= open_list[0].minkey(): if g_function[goal] < float('inf'): do_something(back_pointer, goal, start) else: # print("hoolla") get_s = open_list[0].top_show() visited.add(get_s) expand_state(get_s, 0, visited, g_function, close_list_anchor, close_list_inad, open_list, back_pointer) close_list_anchor.append(get_s) print("No path found to goal") print() for i in range(n-1,-1, -1): for j in range(n): if (j, i) in blocks: print('#', end=' ') elif (j, i) in back_pointer: if (j, i) == (n-1, n-1): print('*', end=' ') else: print('-', end=' ') else: print('*', end=' ') if (j, i) == (n-1, n-1): print('<-- End position', end=' ') print() print("^") print("Start position") print() print("# is an obstacle") print("- is the path taken by algorithm") if __name__ == "__main__": multi_a_star(start, goal, n_hueristic)
[]
[]
[]
archives/1098994933_python.zip
graphs/page_rank.py
''' Author: https://github.com/bhushan-borole ''' ''' The input graph for the algorithm is: A B C A 0 1 1 B 0 0 1 C 1 0 0 ''' graph = [[0, 1, 1], [0, 0, 1], [1, 0, 0]] class Node: def __init__(self, name): self.name = name self.inbound = [] self.outbound = [] def add_inbound(self, node): self.inbound.append(node) def add_outbound(self, node): self.outbound.append(node) def __repr__(self): return 'Node {}: Inbound: {} ; Outbound: {}'.format(self.name, self.inbound, self.outbound) def page_rank(nodes, limit=3, d=0.85): ranks = {} for node in nodes: ranks[node.name] = 1 outbounds = {} for node in nodes: outbounds[node.name] = len(node.outbound) for i in range(limit): print("======= Iteration {} =======".format(i+1)) for j, node in enumerate(nodes): ranks[node.name] = (1 - d) + d * sum([ ranks[ib]/outbounds[ib] for ib in node.inbound ]) print(ranks) def main(): names = list(input('Enter Names of the Nodes: ').split()) nodes = [Node(name) for name in names] for ri, row in enumerate(graph): for ci, col in enumerate(row): if col == 1: nodes[ci].add_inbound(names[ri]) nodes[ri].add_outbound(names[ci]) print("======= Nodes =======") for node in nodes: print(node) page_rank(nodes) if __name__ == '__main__': main()
[]
[]
[]
archives/1098994933_python.zip
graphs/prim.py
""" Prim's Algorithm. Determines the minimum spanning tree(MST) of a graph using the Prim's Algorithm Create a list to store x the vertices. G = [vertex(n) for n in range(x)] For each vertex in G, add the neighbors: G[x].addNeighbor(G[y]) G[y].addNeighbor(G[x]) For each vertex in G, add the edges: G[x].addEdge(G[y], w) G[y].addEdge(G[x], w) To solve run: MST = prim(G, G[0]) """ import math class vertex(): """Class Vertex.""" def __init__(self, id): """ Arguments: id - input an id to identify the vertex Attributes: neighbors - a list of the vertices it is linked to edges - a dict to store the edges's weight """ self.id = str(id) self.key = None self.pi = None self.neighbors = [] self.edges = {} # [vertex:distance] def __lt__(self, other): """Comparison rule to < operator.""" return (self.key < other.key) def __repr__(self): """Return the vertex id.""" return self.id def addNeighbor(self, vertex): """Add a pointer to a vertex at neighbor's list.""" self.neighbors.append(vertex) def addEdge(self, vertex, weight): """Destination vertex and weight.""" self.edges[vertex.id] = weight def prim(graph, root): """ Prim's Algorithm. Return a list with the edges of a Minimum Spanning Tree prim(graph, graph[0]) """ A = [] for u in graph: u.key = math.inf u.pi = None root.key = 0 Q = graph[:] while Q: u = min(Q) Q.remove(u) for v in u.neighbors: if (v in Q) and (u.edges[v.id] < v.key): v.pi = u v.key = u.edges[v.id] for i in range(1, len(graph)): A.append([graph[i].id, graph[i].pi.id]) return(A)
[]
[]
[]
archives/1098994933_python.zip
graphs/scc_kosaraju.py
def dfs(u): global g, r, scc, component, visit, stack if visit[u]: return visit[u] = True for v in g[u]: dfs(v) stack.append(u) def dfs2(u): global g, r, scc, component, visit, stack if visit[u]: return visit[u] = True component.append(u) for v in r[u]: dfs2(v) def kosaraju(): global g, r, scc, component, visit, stack for i in range(n): dfs(i) visit = [False]*n for i in stack[::-1]: if visit[i]: continue component = [] dfs2(i) scc.append(component) return scc if __name__ == "__main__": # n - no of nodes, m - no of edges n, m = list(map(int,input().strip().split())) g = [[] for i in range(n)] #graph r = [[] for i in range(n)] #reversed graph # input graph data (edges) for i in range(m): u, v = list(map(int,input().strip().split())) g[u].append(v) r[v].append(u) stack = [] visit = [False]*n scc = [] component = [] print(kosaraju())
[]
[]
[]
archives/1098994933_python.zip
graphs/tarjans_scc.py
from collections import deque def tarjan(g): """ Tarjan's algo for finding strongly connected components in a directed graph Uses two main attributes of each node to track reachability, the index of that node within a component(index), and the lowest index reachable from that node(lowlink). We then perform a dfs of the each component making sure to update these parameters for each node and saving the nodes we visit on the way. If ever we find that the lowest reachable node from a current node is equal to the index of the current node then it must be the root of a strongly connected component and so we save it and it's equireachable vertices as a strongly connected component. Complexity: strong_connect() is called at most once for each node and has a complexity of O(|E|) as it is DFS. Therefore this has complexity O(|V| + |E|) for a graph G = (V, E) """ n = len(g) stack = deque() on_stack = [False for _ in range(n)] index_of = [-1 for _ in range(n)] lowlink_of = index_of[:] def strong_connect(v, index, components): index_of[v] = index # the number when this node is seen lowlink_of[v] = index # lowest rank node reachable from here index += 1 stack.append(v) on_stack[v] = True for w in g[v]: if index_of[w] == -1: index = strong_connect(w, index, components) lowlink_of[v] = lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v] elif on_stack[w]: lowlink_of[v] = lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v] if lowlink_of[v] == index_of[v]: component = [] w = stack.pop() on_stack[w] = False component.append(w) while w != v: w = stack.pop() on_stack[w] = False component.append(w) components.append(component) return index components = [] for v in range(n): if index_of[v] == -1: strong_connect(v, 0, components) return components def create_graph(n, edges): g = [[] for _ in range(n)] for u, v in edges: g[u].append(v) return g if __name__ == '__main__': # Test n_vertices = 7 source = [0, 0, 1, 2, 3, 3, 4, 4, 6] target = [1, 3, 2, 0, 1, 4, 5, 6, 5] edges = [(u, v) for u, v in zip(source, target)] g = create_graph(n_vertices, edges) assert [[5], [6], [4], [3, 2, 1, 0]] == tarjan(g)
[]
[]
[]
archives/1098994933_python.zip
hashes/chaos_machine.py
"""example of simple chaos machine""" # Chaos Machine (K, t, m) K = [0.33, 0.44, 0.55, 0.44, 0.33]; t = 3; m = 5 # Buffer Space (with Parameters Space) buffer_space, params_space = [], [] # Machine Time machine_time = 0 def push(seed): global buffer_space, params_space, machine_time, \ K, m, t # Choosing Dynamical Systems (All) for key, value in enumerate(buffer_space): # Evolution Parameter e = float(seed / value) # Control Theory: Orbit Change value = (buffer_space[(key + 1) % m] + e) % 1 # Control Theory: Trajectory Change r = (params_space[key] + e) % 1 + 3 # Modification (Transition Function) - Jumps buffer_space[key] = \ round(float(r * value * (1 - value)), 10) params_space[key] = \ r # Saving to Parameters Space # Logistic Map assert max(buffer_space) < 1 assert max(params_space) < 4 # Machine Time machine_time += 1 def pull(): global buffer_space, params_space, machine_time, \ K, m, t # PRNG (Xorshift by George Marsaglia) def xorshift(X, Y): X ^= Y >> 13 Y ^= X << 17 X ^= Y >> 5 return X # Choosing Dynamical Systems (Increment) key = machine_time % m # Evolution (Time Length) for i in range(0, t): # Variables (Position + Parameters) r = params_space[key] value = buffer_space[key] # Modification (Transition Function) - Flow buffer_space[key] = \ round(float(r * value * (1 - value)), 10) params_space[key] = \ (machine_time * 0.01 + r * 1.01) % 1 + 3 # Choosing Chaotic Data X = int(buffer_space[(key + 2) % m] * (10 ** 10)) Y = int(buffer_space[(key - 2) % m] * (10 ** 10)) # Machine Time machine_time += 1 return xorshift(X, Y) % 0xFFFFFFFF def reset(): global buffer_space, params_space, machine_time, \ K, m, t buffer_space = K; params_space = [0] * m machine_time = 0 ####################################### # Initialization reset() # Pushing Data (Input) import random message = random.sample(range(0xFFFFFFFF), 100) for chunk in message: push(chunk) # for controlling inp = "" # Pulling Data (Output) while inp in ("e", "E"): print("%s" % format(pull(), '#04x')) print(buffer_space); print(params_space) inp = input("(e)exit? ").strip()
[]
[]
[]
archives/1098994933_python.zip
hashes/enigma_machine.py
alphabets = [chr(i) for i in range(32, 126)] gear_one = [i for i in range(len(alphabets))] gear_two = [i for i in range(len(alphabets))] gear_three = [i for i in range(len(alphabets))] reflector = [i for i in reversed(range(len(alphabets)))] code = [] gear_one_pos = gear_two_pos = gear_three_pos = 0 def rotator(): global gear_one_pos global gear_two_pos global gear_three_pos i = gear_one[0] gear_one.append(i) del gear_one[0] gear_one_pos += 1 if gear_one_pos % int(len(alphabets)) == 0: i = gear_two[0] gear_two.append(i) del gear_two[0] gear_two_pos += 1 if gear_two_pos % int(len(alphabets)) == 0: i = gear_three[0] gear_three.append(i) del gear_three[0] gear_three_pos += 1 def engine(input_character): target = alphabets.index(input_character) target = gear_one[target] target = gear_two[target] target = gear_three[target] target = reflector[target] target = gear_three.index(target) target = gear_two.index(target) target = gear_one.index(target) code.append(alphabets[target]) rotator() if __name__ == '__main__': decode = input("Type your message:\n") decode = list(decode) while True: try: token = int(input("Please set token:(must be only digits)\n")) break except Exception as error: print(error) for i in range(token): rotator() for i in decode: engine(i) print("\n" + "".join(code)) print( f"\nYour Token is {token} please write it down.\nIf you want to decode " f"this message again you should input same digits as token!")
[]
[]
[]
archives/1098994933_python.zip
hashes/md5.py
import math def rearrange(bitString32): """[summary] Regroups the given binary string. Arguments: bitString32 {[string]} -- [32 bit binary] Raises: ValueError -- [if the given string not are 32 bit binary string] Returns: [string] -- [32 bit binary string] >>> rearrange('1234567890abcdfghijklmnopqrstuvw') 'pqrstuvwhijklmno90abcdfg12345678' """ if len(bitString32) != 32: raise ValueError("Need length 32") newString = "" for i in [3, 2,1,0]: newString += bitString32[8*i:8*i+8] return newString def reformatHex(i): """[summary] Converts the given integer into 8-digit hex number. Arguments: i {[int]} -- [integer] >>> reformatHex(666) '9a020000' """ hexrep = format(i, '08x') thing = "" for i in [3, 2,1,0]: thing += hexrep[2*i:2*i+2] return thing def pad(bitString): """[summary] Fills up the binary string to a 512 bit binary string Arguments: bitString {[string]} -- [binary string] Returns: [string] -- [binary string] """ startLength = len(bitString) bitString += '1' while len(bitString) % 512 != 448: bitString += '0' lastPart = format(startLength, '064b') bitString += rearrange(lastPart[32:]) + rearrange(lastPart[:32]) return bitString def getBlock(bitString): """[summary] Iterator: Returns by each call a list of length 16 with the 32 bit integer blocks. Arguments: bitString {[string]} -- [binary string >= 512] """ currPos = 0 while currPos < len(bitString): currPart = bitString[currPos:currPos+512] mySplits = [] for i in range(16): mySplits.append(int(rearrange(currPart[32*i:32*i+32]), 2)) yield mySplits currPos += 512 def not32(i): ''' >>> not32(34) 4294967261 ''' i_str = format(i, '032b') new_str = '' for c in i_str: new_str += '1' if c == '0' else '0' return int(new_str, 2) def sum32(a, b): ''' ''' return (a + b) % 2**32 def leftrot32(i, s): return (i << s) ^ (i >> (32-s)) def md5me(testString): """[summary] Returns a 32-bit hash code of the string 'testString' Arguments: testString {[string]} -- [message] """ bs = '' for i in testString: bs += format(ord(i), '08b') bs = pad(bs) tvals = [int(2**32 * abs(math.sin(i+1))) for i in range(64)] a0 = 0x67452301 b0 = 0xefcdab89 c0 = 0x98badcfe d0 = 0x10325476 s = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, \ 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, \ 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21 ] for m in getBlock(bs): A = a0 B = b0 C = c0 D = d0 for i in range(64): if i <= 15: #f = (B & C) | (not32(B) & D) f = D ^ (B & (C ^ D)) g = i elif i <= 31: #f = (D & B) | (not32(D) & C) f = C ^ (D & (B ^ C)) g = (5*i+1) % 16 elif i <= 47: f = B ^ C ^ D g = (3*i+5) % 16 else: f = C ^ (B | not32(D)) g = (7*i) % 16 dtemp = D D = C C = B B = sum32(B, leftrot32((A + f + tvals[i] + m[g]) % 2**32, s[i])) A = dtemp a0 = sum32(a0, A) b0 = sum32(b0, B) c0 = sum32(c0, C) d0 = sum32(d0, D) digest = reformatHex(a0) + reformatHex(b0) + \ reformatHex(c0) + reformatHex(d0) return digest def test(): assert md5me("") == "d41d8cd98f00b204e9800998ecf8427e" assert md5me( "The quick brown fox jumps over the lazy dog") == "9e107d9d372bb6826bd81d3542a419d6" print("Success.") if __name__ == "__main__": test() import doctest doctest.testmod()
[]
[]
[]
archives/1098994933_python.zip
hashes/sha1.py
""" Demonstrates implementation of SHA1 Hash function in a Python class and gives utilities to find hash of string or hash of text from a file. Usage: python sha1.py --string "Hello World!!" python sha1.py --file "hello_world.txt" When run without any arguments, it prints the hash of the string "Hello World!! Welcome to Cryptography" Also contains a Test class to verify that the generated Hash is same as that returned by the hashlib library SHA1 hash or SHA1 sum of a string is a crytpographic function which means it is easy to calculate forwards but extemely difficult to calculate backwards. What this means is, you can easily calculate the hash of a string, but it is extremely difficult to know the original string if you have its hash. This property is useful to communicate securely, send encrypted messages and is very useful in payment systems, blockchain and cryptocurrency etc. The Algorithm as described in the reference: First we start with a message. The message is padded and the length of the message is added to the end. It is then split into blocks of 512 bits or 64 bytes. The blocks are then processed one at a time. Each block must be expanded and compressed. The value after each compression is added to a 160bit buffer called the current hash state. After the last block is processed the current hash state is returned as the final hash. Reference: https://deadhacker.com/2006/02/21/sha-1-illustrated/ """ import argparse import struct import hashlib #hashlib is only used inside the Test class import unittest class SHA1Hash: """ Class to contain the entire pipeline for SHA1 Hashing Algorithm >>> SHA1Hash(bytes('Allan', 'utf-8')).final_hash() '872af2d8ac3d8695387e7c804bf0e02c18df9e6e' """ def __init__(self, data): """ Inititates the variables data and h. h is a list of 5 8-digit Hexadecimal numbers corresponding to (1732584193, 4023233417, 2562383102, 271733878, 3285377520) respectively. We will start with this as a message digest. 0x is how you write Hexadecimal numbers in Python """ self.data = data self.h = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0] @staticmethod def rotate(n, b): """ Static method to be used inside other methods. Left rotates n by b. >>> SHA1Hash('').rotate(12,2) 48 """ return ((n << b) | (n >> (32 - b))) & 0xffffffff def padding(self): """ Pads the input message with zeros so that padded_data has 64 bytes or 512 bits """ padding = b'\x80' + b'\x00'*(63 - (len(self.data) + 8) % 64) padded_data = self.data + padding + struct.pack('>Q', 8 * len(self.data)) return padded_data def split_blocks(self): """ Returns a list of bytestrings each of length 64 """ return [self.padded_data[i:i+64] for i in range(0, len(self.padded_data), 64)] # @staticmethod def expand_block(self, block): """ Takes a bytestring-block of length 64, unpacks it to a list of integers and returns a list of 80 integers after some bit operations """ w = list(struct.unpack('>16L', block)) + [0] * 64 for i in range(16, 80): w[i] = self.rotate((w[i-3] ^ w[i-8] ^ w[i-14] ^ w[i-16]), 1) return w def final_hash(self): """ Calls all the other methods to process the input. Pads the data, then splits into blocks and then does a series of operations for each block (including expansion). For each block, the variable h that was initialized is copied to a,b,c,d,e and these 5 variables a,b,c,d,e undergo several changes. After all the blocks are processed, these 5 variables are pairwise added to h ie a to h[0], b to h[1] and so on. This h becomes our final hash which is returned. """ self.padded_data = self.padding() self.blocks = self.split_blocks() for block in self.blocks: expanded_block = self.expand_block(block) a, b, c, d, e = self.h for i in range(0, 80): if 0 <= i < 20: f = (b & c) | ((~b) & d) k = 0x5A827999 elif 20 <= i < 40: f = b ^ c ^ d k = 0x6ED9EBA1 elif 40 <= i < 60: f = (b & c) | (b & d) | (c & d) k = 0x8F1BBCDC elif 60 <= i < 80: f = b ^ c ^ d k = 0xCA62C1D6 a, b, c, d, e = self.rotate(a, 5) + f + e + k + expanded_block[i] & 0xffffffff,\ a, self.rotate(b, 30), c, d self.h = self.h[0] + a & 0xffffffff,\ self.h[1] + b & 0xffffffff,\ self.h[2] + c & 0xffffffff,\ self.h[3] + d & 0xffffffff,\ self.h[4] + e & 0xffffffff return '%08x%08x%08x%08x%08x' %tuple(self.h) class SHA1HashTest(unittest.TestCase): """ Test class for the SHA1Hash class. Inherits the TestCase class from unittest """ def testMatchHashes(self): msg = bytes('Test String', 'utf-8') self.assertEqual(SHA1Hash(msg).final_hash(), hashlib.sha1(msg).hexdigest()) def main(): """ Provides option 'string' or 'file' to take input and prints the calculated SHA1 hash. unittest.main() has been commented because we probably dont want to run the test each time. """ # unittest.main() parser = argparse.ArgumentParser(description='Process some strings or files') parser.add_argument('--string', dest='input_string', default='Hello World!! Welcome to Cryptography', help='Hash the string') parser.add_argument('--file', dest='input_file', help='Hash contents of a file') args = parser.parse_args() input_string = args.input_string #In any case hash input should be a bytestring if args.input_file: with open(args.input_file, 'rb') as f: hash_input = f.read() else: hash_input = bytes(input_string, 'utf-8') print(SHA1Hash(hash_input).final_hash()) if __name__ == '__main__': main() import doctest doctest.testmod()
[]
[]
[]
archives/1098994933_python.zip
linear_algebra/src/lib.py
# -*- coding: utf-8 -*- """ Created on Mon Feb 26 14:29:11 2018 @author: Christian Bender @license: MIT-license This module contains some useful classes and functions for dealing with linear algebra in python. Overview: - class Vector - function zeroVector(dimension) - function unitBasisVector(dimension,pos) - function axpy(scalar,vector1,vector2) - function randomVector(N,a,b) - class Matrix - function squareZeroMatrix(N) - function randomMatrix(W,H,a,b) """ import math import random class Vector(object): """ This class represents a vector of arbitray size. You need to give the vector components. Overview about the methods: constructor(components : list) : init the vector set(components : list) : changes the vector components. __str__() : toString method component(i : int): gets the i-th component (start by 0) __len__() : gets the size of the vector (number of components) euclidLength() : returns the eulidean length of the vector. operator + : vector addition operator - : vector subtraction operator * : scalar multiplication and dot product copy() : copies this vector and returns it. changeComponent(pos,value) : changes the specified component. TODO: compare-operator """ def __init__(self,components=[]): """ input: components or nothing simple constructor for init the vector """ self.__components = list(components) def set(self,components): """ input: new components changes the components of the vector. replace the components with newer one. """ if len(components) > 0: self.__components = list(components) else: raise Exception("please give any vector") def __str__(self): """ returns a string representation of the vector """ return "(" + ",".join(map(str, self.__components)) + ")" def component(self,i): """ input: index (start at 0) output: the i-th component of the vector. """ if type(i) is int and -len(self.__components) <= i < len(self.__components) : return self.__components[i] else: raise Exception("index out of range") def __len__(self): """ returns the size of the vector """ return len(self.__components) def eulidLength(self): """ returns the eulidean length of the vector """ summe = 0 for c in self.__components: summe += c**2 return math.sqrt(summe) def __add__(self,other): """ input: other vector assumes: other vector has the same size returns a new vector that represents the sum. """ size = len(self) if size == len(other): result = [self.__components[i] + other.component(i) for i in range(size)] return Vector(result) else: raise Exception("must have the same size") def __sub__(self,other): """ input: other vector assumes: other vector has the same size returns a new vector that represents the differenz. """ size = len(self) if size == len(other): result = [self.__components[i] - other.component(i) for i in range(size)] return result else: # error case raise Exception("must have the same size") def __mul__(self,other): """ mul implements the scalar multiplication and the dot-product """ if isinstance(other,float) or isinstance(other,int): ans = [c*other for c in self.__components] return ans elif (isinstance(other,Vector) and (len(self) == len(other))): size = len(self) summe = 0 for i in range(size): summe += self.__components[i] * other.component(i) return summe else: # error case raise Exception("invalide operand!") def copy(self): """ copies this vector and returns it. """ return Vector(self.__components) def changeComponent(self,pos,value): """ input: an index (pos) and a value changes the specified component (pos) with the 'value' """ #precondition assert (-len(self.__components) <= pos < len(self.__components)) self.__components[pos] = value def zeroVector(dimension): """ returns a zero-vector of size 'dimension' """ #precondition assert(isinstance(dimension,int)) return Vector([0]*dimension) def unitBasisVector(dimension,pos): """ returns a unit basis vector with a One at index 'pos' (indexing at 0) """ #precondition assert(isinstance(dimension,int) and (isinstance(pos,int))) ans = [0]*dimension ans[pos] = 1 return Vector(ans) def axpy(scalar,x,y): """ input: a 'scalar' and two vectors 'x' and 'y' output: a vector computes the axpy operation """ # precondition assert(isinstance(x,Vector) and (isinstance(y,Vector)) \ and (isinstance(scalar,int) or isinstance(scalar,float))) return (x*scalar + y) def randomVector(N,a,b): """ input: size (N) of the vector. random range (a,b) output: returns a random vector of size N, with random integer components between 'a' and 'b'. """ random.seed(None) ans = [random.randint(a,b) for i in range(N)] return Vector(ans) class Matrix(object): """ class: Matrix This class represents a arbitrary matrix. Overview about the methods: __str__() : returns a string representation operator * : implements the matrix vector multiplication implements the matrix-scalar multiplication. changeComponent(x,y,value) : changes the specified component. component(x,y) : returns the specified component. width() : returns the width of the matrix height() : returns the height of the matrix operator + : implements the matrix-addition. operator - _ implements the matrix-subtraction """ def __init__(self,matrix,w,h): """ simple constructor for initialzes the matrix with components. """ self.__matrix = matrix self.__width = w self.__height = h def __str__(self): """ returns a string representation of this matrix. """ ans = "" for i in range(self.__height): ans += "|" for j in range(self.__width): if j < self.__width -1: ans += str(self.__matrix[i][j]) + "," else: ans += str(self.__matrix[i][j]) + "|\n" return ans def changeComponent(self,x,y, value): """ changes the x-y component of this matrix """ if x >= 0 and x < self.__height and y >= 0 and y < self.__width: self.__matrix[x][y] = value else: raise Exception ("changeComponent: indices out of bounds") def component(self,x,y): """ returns the specified (x,y) component """ if x >= 0 and x < self.__height and y >= 0 and y < self.__width: return self.__matrix[x][y] else: raise Exception ("changeComponent: indices out of bounds") def width(self): """ getter for the width """ return self.__width def height(self): """ getter for the height """ return self.__height def __mul__(self,other): """ implements the matrix-vector multiplication. implements the matrix-scalar multiplication """ if isinstance(other, Vector): # vector-matrix if (len(other) == self.__width): ans = zeroVector(self.__height) for i in range(self.__height): summe = 0 for j in range(self.__width): summe += other.component(j) * self.__matrix[i][j] ans.changeComponent(i,summe) summe = 0 return ans else: raise Exception("vector must have the same size as the " + "number of columns of the matrix!") elif isinstance(other,int) or isinstance(other,float): # matrix-scalar matrix = [[self.__matrix[i][j] * other for j in range(self.__width)] for i in range(self.__height)] return Matrix(matrix,self.__width,self.__height) def __add__(self,other): """ implements the matrix-addition. """ if (self.__width == other.width() and self.__height == other.height()): matrix = [] for i in range(self.__height): row = [] for j in range(self.__width): row.append(self.__matrix[i][j] + other.component(i,j)) matrix.append(row) return Matrix(matrix,self.__width,self.__height) else: raise Exception("matrix must have the same dimension!") def __sub__(self,other): """ implements the matrix-subtraction. """ if (self.__width == other.width() and self.__height == other.height()): matrix = [] for i in range(self.__height): row = [] for j in range(self.__width): row.append(self.__matrix[i][j] - other.component(i,j)) matrix.append(row) return Matrix(matrix,self.__width,self.__height) else: raise Exception("matrix must have the same dimension!") def squareZeroMatrix(N): """ returns a square zero-matrix of dimension NxN """ ans = [[0]*N for i in range(N)] return Matrix(ans,N,N) def randomMatrix(W,H,a,b): """ returns a random matrix WxH with integer components between 'a' and 'b' """ random.seed(None) matrix = [[random.randint(a,b) for j in range(W)] for i in range(H)] return Matrix(matrix,W,H)
[]
[]
[]
archives/1098994933_python.zip
linear_algebra/src/polynom-for-points.py
def points_to_polynomial(coordinates): """ coordinates is a two dimensional matrix: [[x, y], [x, y], ...] number of points you want to use >>> print(points_to_polynomial([])) The program cannot work out a fitting polynomial. >>> print(points_to_polynomial([[]])) The program cannot work out a fitting polynomial. >>> print(points_to_polynomial([[1, 0], [2, 0], [3, 0]])) f(x)=x^2*0.0+x^1*-0.0+x^0*0.0 >>> print(points_to_polynomial([[1, 1], [2, 1], [3, 1]])) f(x)=x^2*0.0+x^1*-0.0+x^0*1.0 >>> print(points_to_polynomial([[1, 3], [2, 3], [3, 3]])) f(x)=x^2*0.0+x^1*-0.0+x^0*3.0 >>> print(points_to_polynomial([[1, 1], [2, 2], [3, 3]])) f(x)=x^2*0.0+x^1*1.0+x^0*0.0 >>> print(points_to_polynomial([[1, 1], [2, 4], [3, 9]])) f(x)=x^2*1.0+x^1*-0.0+x^0*0.0 >>> print(points_to_polynomial([[1, 3], [2, 6], [3, 11]])) f(x)=x^2*1.0+x^1*-0.0+x^0*2.0 >>> print(points_to_polynomial([[1, -3], [2, -6], [3, -11]])) f(x)=x^2*-1.0+x^1*-0.0+x^0*-2.0 >>> print(points_to_polynomial([[1, 5], [2, 2], [3, 9]])) f(x)=x^2*5.0+x^1*-18.0+x^0*18.0 """ try: check = 1 more_check = 0 d = coordinates[0][0] for j in range(len(coordinates)): if j == 0: continue if d == coordinates[j][0]: more_check += 1 solved = "x=" + str(coordinates[j][0]) if more_check == len(coordinates) - 1: check = 2 break elif more_check > 0 and more_check != len(coordinates) - 1: check = 3 else: check = 1 if len(coordinates) == 1 and coordinates[0][0] == 0: check = 2 solved = "x=0" except Exception: check = 3 x = len(coordinates) if check == 1: count_of_line = 0 matrix = [] # put the x and x to the power values in a matrix while count_of_line < x: count_in_line = 0 a = coordinates[count_of_line][0] count_line = [] while count_in_line < x: count_line.append(a ** (x - (count_in_line + 1))) count_in_line += 1 matrix.append(count_line) count_of_line += 1 count_of_line = 0 # put the y values into a vector vector = [] while count_of_line < x: count_in_line = 0 vector.append(coordinates[count_of_line][1]) count_of_line += 1 count = 0 while count < x: zahlen = 0 while zahlen < x: if count == zahlen: zahlen += 1 if zahlen == x: break bruch = (matrix[zahlen][count]) / (matrix[count][count]) for counting_columns, item in enumerate(matrix[count]): # manipulating all the values in the matrix matrix[zahlen][counting_columns] -= item * bruch # manipulating the values in the vector vector[zahlen] -= vector[count] * bruch zahlen += 1 count += 1 count = 0 # make solutions solution = [] while count < x: solution.append(vector[count] / matrix[count][count]) count += 1 count = 0 solved = "f(x)=" while count < x: remove_e = str(solution[count]).split("E") if len(remove_e) > 1: solution[count] = remove_e[0] + "*10^" + remove_e[1] solved += "x^" + str(x - (count + 1)) + "*" + str(solution[count]) if count + 1 != x: solved += "+" count += 1 return solved elif check == 2: return solved else: return "The program cannot work out a fitting polynomial." if __name__ == "__main__": print(points_to_polynomial([])) print(points_to_polynomial([[]])) print(points_to_polynomial([[1, 0], [2, 0], [3, 0]])) print(points_to_polynomial([[1, 1], [2, 1], [3, 1]])) print(points_to_polynomial([[1, 3], [2, 3], [3, 3]])) print(points_to_polynomial([[1, 1], [2, 2], [3, 3]])) print(points_to_polynomial([[1, 1], [2, 4], [3, 9]])) print(points_to_polynomial([[1, 3], [2, 6], [3, 11]])) print(points_to_polynomial([[1, -3], [2, -6], [3, -11]])) print(points_to_polynomial([[1, 5], [2, 2], [3, 9]]))
[]
[]
[]
archives/1098994933_python.zip
linear_algebra/src/tests.py
# -*- coding: utf-8 -*- """ Created on Mon Feb 26 15:40:07 2018 @author: Christian Bender @license: MIT-license This file contains the test-suite for the linear algebra library. """ import unittest from lib import * class Test(unittest.TestCase): def test_component(self): """ test for method component """ x = Vector([1,2,3]) self.assertEqual(x.component(0),1) self.assertEqual(x.component(2),3) try: y = Vector() self.assertTrue(False) except: self.assertTrue(True) def test_str(self): """ test for toString() method """ x = Vector([0,0,0,0,0,1]) self.assertEqual(str(x),"(0,0,0,0,0,1)") def test_size(self): """ test for size()-method """ x = Vector([1,2,3,4]) self.assertEqual(len(x),4) def test_euclidLength(self): """ test for the eulidean length """ x = Vector([1,2]) self.assertAlmostEqual(x.eulidLength(),2.236,3) def test_add(self): """ test for + operator """ x = Vector([1,2,3]) y = Vector([1,1,1]) self.assertEqual((x+y).component(0),2) self.assertEqual((x+y).component(1),3) self.assertEqual((x+y).component(2),4) def test_sub(self): """ test for - operator """ x = Vector([1,2,3]) y = Vector([1,1,1]) self.assertEqual((x-y).component(0),0) self.assertEqual((x-y).component(1),1) self.assertEqual((x-y).component(2),2) def test_mul(self): """ test for * operator """ x = Vector([1,2,3]) a = Vector([2,-1,4]) # for test of dot-product b = Vector([1,-2,-1]) self.assertEqual(str(x*3.0),"(3.0,6.0,9.0)") self.assertEqual((a*b),0) def test_zeroVector(self): """ test for the global function zeroVector(...) """ self.assertTrue(str(zeroVector(10)).count("0") == 10) def test_unitBasisVector(self): """ test for the global function unitBasisVector(...) """ self.assertEqual(str(unitBasisVector(3,1)),"(0,1,0)") def test_axpy(self): """ test for the global function axpy(...) (operation) """ x = Vector([1,2,3]) y = Vector([1,0,1]) self.assertEqual(str(axpy(2,x,y)),"(3,4,7)") def test_copy(self): """ test for the copy()-method """ x = Vector([1,0,0,0,0,0]) y = x.copy() self.assertEqual(str(x),str(y)) def test_changeComponent(self): """ test for the changeComponent(...)-method """ x = Vector([1,0,0]) x.changeComponent(0,0) x.changeComponent(1,1) self.assertEqual(str(x),"(0,1,0)") def test_str_matrix(self): A = Matrix([[1,2,3],[2,4,5],[6,7,8]],3,3) self.assertEqual("|1,2,3|\n|2,4,5|\n|6,7,8|\n",str(A)) def test__mul__matrix(self): A = Matrix([[1,2,3],[4,5,6],[7,8,9]],3,3) x = Vector([1,2,3]) self.assertEqual("(14,32,50)",str(A*x)) self.assertEqual("|2,4,6|\n|8,10,12|\n|14,16,18|\n",str(A*2)) def test_changeComponent_matrix(self): A = Matrix([[1,2,3],[2,4,5],[6,7,8]],3,3) A.changeComponent(0,2,5) self.assertEqual("|1,2,5|\n|2,4,5|\n|6,7,8|\n",str(A)) def test_component_matrix(self): A = Matrix([[1,2,3],[2,4,5],[6,7,8]],3,3) self.assertEqual(7,A.component(2,1),0.01) def test__add__matrix(self): A = Matrix([[1,2,3],[2,4,5],[6,7,8]],3,3) B = Matrix([[1,2,7],[2,4,5],[6,7,10]],3,3) self.assertEqual("|2,4,10|\n|4,8,10|\n|12,14,18|\n",str(A+B)) def test__sub__matrix(self): A = Matrix([[1,2,3],[2,4,5],[6,7,8]],3,3) B = Matrix([[1,2,7],[2,4,5],[6,7,10]],3,3) self.assertEqual("|0,0,-4|\n|0,0,0|\n|0,0,-2|\n",str(A-B)) def test_squareZeroMatrix(self): self.assertEqual('|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|' +'\n|0,0,0,0,0|\n',str(squareZeroMatrix(5))) if __name__ == "__main__": unittest.main()
[]
[]
[]
archives/1098994933_python.zip
machine_learning/decision_tree.py
""" Implementation of a basic regression decision tree. Input data set: The input data set must be 1-dimensional with continuous labels. Output: The decision tree maps a real number input to a real number output. """ import numpy as np class Decision_Tree: def __init__(self, depth = 5, min_leaf_size = 5): self.depth = depth self.decision_boundary = 0 self.left = None self.right = None self.min_leaf_size = min_leaf_size self.prediction = None def mean_squared_error(self, labels, prediction): """ mean_squared_error: @param labels: a one dimensional numpy array @param prediction: a floating point value return value: mean_squared_error calculates the error if prediction is used to estimate the labels """ if labels.ndim != 1: print("Error: Input labels must be one dimensional") return np.mean((labels - prediction) ** 2) def train(self, X, y): """ train: @param X: a one dimensional numpy array @param y: a one dimensional numpy array. The contents of y are the labels for the corresponding X values train does not have a return value """ """ this section is to check that the inputs conform to our dimensionality constraints """ if X.ndim != 1: print("Error: Input data set must be one dimensional") return if len(X) != len(y): print("Error: X and y have different lengths") return if y.ndim != 1: print("Error: Data set labels must be one dimensional") return if len(X) < 2 * self.min_leaf_size: self.prediction = np.mean(y) return if self.depth == 1: self.prediction = np.mean(y) return best_split = 0 min_error = self.mean_squared_error(X,np.mean(y)) * 2 """ loop over all possible splits for the decision tree. find the best split. if no split exists that is less than 2 * error for the entire array then the data set is not split and the average for the entire array is used as the predictor """ for i in range(len(X)): if len(X[:i]) < self.min_leaf_size: continue elif len(X[i:]) < self.min_leaf_size: continue else: error_left = self.mean_squared_error(X[:i], np.mean(y[:i])) error_right = self.mean_squared_error(X[i:], np.mean(y[i:])) error = error_left + error_right if error < min_error: best_split = i min_error = error if best_split != 0: left_X = X[:best_split] left_y = y[:best_split] right_X = X[best_split:] right_y = y[best_split:] self.decision_boundary = X[best_split] self.left = Decision_Tree(depth = self.depth - 1, min_leaf_size = self.min_leaf_size) self.right = Decision_Tree(depth = self.depth - 1, min_leaf_size = self.min_leaf_size) self.left.train(left_X, left_y) self.right.train(right_X, right_y) else: self.prediction = np.mean(y) return def predict(self, x): """ predict: @param x: a floating point value to predict the label of the prediction function works by recursively calling the predict function of the appropriate subtrees based on the tree's decision boundary """ if self.prediction is not None: return self.prediction elif self.left or self.right is not None: if x >= self.decision_boundary: return self.right.predict(x) else: return self.left.predict(x) else: print("Error: Decision tree not yet trained") return None def main(): """ In this demonstration we're generating a sample data set from the sin function in numpy. We then train a decision tree on the data set and use the decision tree to predict the label of 10 different test values. Then the mean squared error over this test is displayed. """ X = np.arange(-1., 1., 0.005) y = np.sin(X) tree = Decision_Tree(depth = 10, min_leaf_size = 10) tree.train(X,y) test_cases = (np.random.rand(10) * 2) - 1 predictions = np.array([tree.predict(x) for x in test_cases]) avg_error = np.mean((predictions - test_cases) ** 2) print("Test values: " + str(test_cases)) print("Predictions: " + str(predictions)) print("Average error: " + str(avg_error)) if __name__ == '__main__': main()
[]
[]
[]
archives/1098994933_python.zip
machine_learning/gradient_descent.py
""" Implementation of gradient descent algorithm for minimizing cost of a linear hypothesis function. """ import numpy # List of input, output pairs train_data = (((5, 2, 3), 15), ((6, 5, 9), 25), ((11, 12, 13), 41), ((1, 1, 1), 8), ((11, 12, 13), 41)) test_data = (((515, 22, 13), 555), ((61, 35, 49), 150)) parameter_vector = [2, 4, 1, 5] m = len(train_data) LEARNING_RATE = 0.009 def _error(example_no, data_set='train'): """ :param data_set: train data or test data :param example_no: example number whose error has to be checked :return: error in example pointed by example number. """ return calculate_hypothesis_value(example_no, data_set) - output(example_no, data_set) def _hypothesis_value(data_input_tuple): """ Calculates hypothesis function value for a given input :param data_input_tuple: Input tuple of a particular example :return: Value of hypothesis function at that point. Note that there is an 'biased input' whose value is fixed as 1. It is not explicitly mentioned in input data.. But, ML hypothesis functions use it. So, we have to take care of it separately. Line 36 takes care of it. """ hyp_val = 0 for i in range(len(parameter_vector) - 1): hyp_val += data_input_tuple[i]*parameter_vector[i+1] hyp_val += parameter_vector[0] return hyp_val def output(example_no, data_set): """ :param data_set: test data or train data :param example_no: example whose output is to be fetched :return: output for that example """ if data_set == 'train': return train_data[example_no][1] elif data_set == 'test': return test_data[example_no][1] def calculate_hypothesis_value(example_no, data_set): """ Calculates hypothesis value for a given example :param data_set: test data or train_data :param example_no: example whose hypothesis value is to be calculated :return: hypothesis value for that example """ if data_set == "train": return _hypothesis_value(train_data[example_no][0]) elif data_set == "test": return _hypothesis_value(test_data[example_no][0]) def summation_of_cost_derivative(index, end=m): """ Calculates the sum of cost function derivative :param index: index wrt derivative is being calculated :param end: value where summation ends, default is m, number of examples :return: Returns the summation of cost derivative Note: If index is -1, this means we are calculating summation wrt to biased parameter. """ summation_value = 0 for i in range(end): if index == -1: summation_value += _error(i) else: summation_value += _error(i)*train_data[i][0][index] return summation_value def get_cost_derivative(index): """ :param index: index of the parameter vector wrt to derivative is to be calculated :return: derivative wrt to that index Note: If index is -1, this means we are calculating summation wrt to biased parameter. """ cost_derivative_value = summation_of_cost_derivative(index, m)/m return cost_derivative_value def run_gradient_descent(): global parameter_vector # Tune these values to set a tolerance value for predicted output absolute_error_limit = 0.000002 relative_error_limit = 0 j = 0 while True: j += 1 temp_parameter_vector = [0, 0, 0, 0] for i in range(0, len(parameter_vector)): cost_derivative = get_cost_derivative(i-1) temp_parameter_vector[i] = parameter_vector[i] - \ LEARNING_RATE*cost_derivative if numpy.allclose(parameter_vector, temp_parameter_vector, atol=absolute_error_limit, rtol=relative_error_limit): break parameter_vector = temp_parameter_vector print(("Number of iterations:", j)) def test_gradient_descent(): for i in range(len(test_data)): print(("Actual output value:", output(i, 'test'))) print(("Hypothesis output:", calculate_hypothesis_value(i, 'test'))) if __name__ == '__main__': run_gradient_descent() print("\nTesting gradient descent for a linear hypothesis function.\n") test_gradient_descent()
[]
[]
[]
archives/1098994933_python.zip
machine_learning/k_means_clust.py
'''README, Author - Anurag Kumar(mailto:anuragkumarak95@gmail.com) Requirements: - sklearn - numpy - matplotlib Python: - 3.5 Inputs: - X , a 2D numpy array of features. - k , number of clusters to create. - initial_centroids , initial centroid values generated by utility function(mentioned in usage). - maxiter , maximum number of iterations to process. - heterogeneity , empty list that will be filled with hetrogeneity values if passed to kmeans func. Usage: 1. define 'k' value, 'X' features array and 'hetrogeneity' empty list 2. create initial_centroids, initial_centroids = get_initial_centroids( X, k, seed=0 # seed value for initial centroid generation, None for randomness(default=None) ) 3. find centroids and clusters using kmeans function. centroids, cluster_assignment = kmeans( X, k, initial_centroids, maxiter=400, record_heterogeneity=heterogeneity, verbose=True # whether to print logs in console or not.(default=False) ) 4. Plot the loss function, hetrogeneity values for every iteration saved in hetrogeneity list. plot_heterogeneity( heterogeneity, k ) 5. Have fun.. ''' from sklearn.metrics import pairwise_distances import numpy as np TAG = 'K-MEANS-CLUST/ ' def get_initial_centroids(data, k, seed=None): '''Randomly choose k data points as initial centroids''' if seed is not None: # useful for obtaining consistent results np.random.seed(seed) n = data.shape[0] # number of data points # Pick K indices from range [0, N). rand_indices = np.random.randint(0, n, k) # Keep centroids as dense format, as many entries will be nonzero due to averaging. # As long as at least one document in a cluster contains a word, # it will carry a nonzero weight in the TF-IDF vector of the centroid. centroids = data[rand_indices,:] return centroids def centroid_pairwise_dist(X,centroids): return pairwise_distances(X,centroids,metric='euclidean') def assign_clusters(data, centroids): # Compute distances between each data point and the set of centroids: # Fill in the blank (RHS only) distances_from_centroids = centroid_pairwise_dist(data,centroids) # Compute cluster assignments for each data point: # Fill in the blank (RHS only) cluster_assignment = np.argmin(distances_from_centroids,axis=1) return cluster_assignment def revise_centroids(data, k, cluster_assignment): new_centroids = [] for i in range(k): # Select all data points that belong to cluster i. Fill in the blank (RHS only) member_data_points = data[cluster_assignment==i] # Compute the mean of the data points. Fill in the blank (RHS only) centroid = member_data_points.mean(axis=0) new_centroids.append(centroid) new_centroids = np.array(new_centroids) return new_centroids def compute_heterogeneity(data, k, centroids, cluster_assignment): heterogeneity = 0.0 for i in range(k): # Select all data points that belong to cluster i. Fill in the blank (RHS only) member_data_points = data[cluster_assignment==i, :] if member_data_points.shape[0] > 0: # check if i-th cluster is non-empty # Compute distances from centroid to data points (RHS only) distances = pairwise_distances(member_data_points, [centroids[i]], metric='euclidean') squared_distances = distances**2 heterogeneity += np.sum(squared_distances) return heterogeneity from matplotlib import pyplot as plt def plot_heterogeneity(heterogeneity, k): plt.figure(figsize=(7,4)) plt.plot(heterogeneity, linewidth=4) plt.xlabel('# Iterations') plt.ylabel('Heterogeneity') plt.title('Heterogeneity of clustering over time, K={0:d}'.format(k)) plt.rcParams.update({'font.size': 16}) plt.show() def kmeans(data, k, initial_centroids, maxiter=500, record_heterogeneity=None, verbose=False): '''This function runs k-means on given data and initial set of centroids. maxiter: maximum number of iterations to run.(default=500) record_heterogeneity: (optional) a list, to store the history of heterogeneity as function of iterations if None, do not store the history. verbose: if True, print how many data points changed their cluster labels in each iteration''' centroids = initial_centroids[:] prev_cluster_assignment = None for itr in range(maxiter): if verbose: print(itr, end='') # 1. Make cluster assignments using nearest centroids cluster_assignment = assign_clusters(data,centroids) # 2. Compute a new centroid for each of the k clusters, averaging all data points assigned to that cluster. centroids = revise_centroids(data,k, cluster_assignment) # Check for convergence: if none of the assignments changed, stop if prev_cluster_assignment is not None and \ (prev_cluster_assignment==cluster_assignment).all(): break # Print number of new assignments if prev_cluster_assignment is not None: num_changed = np.sum(prev_cluster_assignment!=cluster_assignment) if verbose: print(' {0:5d} elements changed their cluster assignment.'.format(num_changed)) # Record heterogeneity convergence metric if record_heterogeneity is not None: # YOUR CODE HERE score = compute_heterogeneity(data,k,centroids,cluster_assignment) record_heterogeneity.append(score) prev_cluster_assignment = cluster_assignment[:] return centroids, cluster_assignment # Mock test below if False: # change to true to run this test case. import sklearn.datasets as ds dataset = ds.load_iris() k = 3 heterogeneity = [] initial_centroids = get_initial_centroids(dataset['data'], k, seed=0) centroids, cluster_assignment = kmeans(dataset['data'], k, initial_centroids, maxiter=400, record_heterogeneity=heterogeneity, verbose=True) plot_heterogeneity(heterogeneity, k)
[]
[]
[]
archives/1098994933_python.zip
machine_learning/knn_sklearn.py
from sklearn.model_selection import train_test_split from sklearn.datasets import load_iris from sklearn.neighbors import KNeighborsClassifier #Load iris file iris = load_iris() iris.keys() print('Target names: \n {} '.format(iris.target_names)) print('\n Features: \n {}'.format(iris.feature_names)) #Train set e Test set X_train, X_test, y_train, y_test = train_test_split(iris['data'],iris['target'], random_state=4) #KNN knn = KNeighborsClassifier (n_neighbors = 1) knn.fit(X_train, y_train) #new array to test X_new = [[1,2,1,4], [2,3,4,5]] prediction = knn.predict(X_new) print('\nNew array: \n {}' '\n\nTarget Names Prediction: \n {}'.format(X_new, iris['target_names'][prediction]))
[]
[]
[]
archives/1098994933_python.zip
machine_learning/linear_regression.py
""" Linear regression is the most basic type of regression commonly used for predictive analysis. The idea is pretty simple, we have a dataset and we have a feature's associated with it. The Features should be choose very cautiously as they determine, how much our model will be able to make future predictions. We try to set these Feature weights, over many iterations, so that they best fits our dataset. In this particular code, i had used a CSGO dataset (ADR vs Rating). We try to best fit a line through dataset and estimate the parameters. """ import requests import numpy as np def collect_dataset(): """ Collect dataset of CSGO The dataset contains ADR vs Rating of a Player :return : dataset obtained from the link, as matrix """ response = requests.get('https://raw.githubusercontent.com/yashLadha/' + 'The_Math_of_Intelligence/master/Week1/ADRvs' + 'Rating.csv') lines = response.text.splitlines() data = [] for item in lines: item = item.split(',') data.append(item) data.pop(0) # This is for removing the labels from the list dataset = np.matrix(data) return dataset def run_steep_gradient_descent(data_x, data_y, len_data, alpha, theta): """ Run steep gradient descent and updates the Feature vector accordingly_ :param data_x : contains the dataset :param data_y : contains the output associated with each data-entry :param len_data : length of the data_ :param alpha : Learning rate of the model :param theta : Feature vector (weight's for our model) ;param return : Updated Feature's, using curr_features - alpha_ * gradient(w.r.t. feature) """ n = len_data prod = np.dot(theta, data_x.transpose()) prod -= data_y.transpose() sum_grad = np.dot(prod, data_x) theta = theta - (alpha / n) * sum_grad return theta def sum_of_square_error(data_x, data_y, len_data, theta): """ Return sum of square error for error calculation :param data_x : contains our dataset :param data_y : contains the output (result vector) :param len_data : len of the dataset :param theta : contains the feature vector :return : sum of square error computed from given feature's """ prod = np.dot(theta, data_x.transpose()) prod -= data_y.transpose() sum_elem = np.sum(np.square(prod)) error = sum_elem / (2 * len_data) return error def run_linear_regression(data_x, data_y): """ Implement Linear regression over the dataset :param data_x : contains our dataset :param data_y : contains the output (result vector) :return : feature for line of best fit (Feature vector) """ iterations = 100000 alpha = 0.0001550 no_features = data_x.shape[1] len_data = data_x.shape[0] - 1 theta = np.zeros((1, no_features)) for i in range(0, iterations): theta = run_steep_gradient_descent(data_x, data_y, len_data, alpha, theta) error = sum_of_square_error(data_x, data_y, len_data, theta) print('At Iteration %d - Error is %.5f ' % (i + 1, error)) return theta def main(): """ Driver function """ data = collect_dataset() len_data = data.shape[0] data_x = np.c_[np.ones(len_data), data[:, :-1]].astype(float) data_y = data[:, -1].astype(float) theta = run_linear_regression(data_x, data_y) len_result = theta.shape[1] print('Resultant Feature vector : ') for i in range(0, len_result): print('%.5f' % (theta[0, i])) if __name__ == '__main__': main()
[]
[]
[]
archives/1098994933_python.zip
machine_learning/logistic_regression.py
#!/usr/bin/python # -*- coding: utf-8 -*- ## Logistic Regression from scratch # In[62]: # In[63]: # importing all the required libraries ''' Implementing logistic regression for classification problem Helpful resources : 1.Coursera ML course 2.https://medium.com/@martinpella/logistic-regression-from-scratch-in-python-124c5636b8ac''' import numpy as np import matplotlib.pyplot as plt # get_ipython().run_line_magic('matplotlib', 'inline') from sklearn import datasets # In[67]: # sigmoid function or logistic function is used as a hypothesis function in classification problems def sigmoid_function(z): return 1 / (1 + np.exp(-z)) def cost_function(h, y): return (-y * np.log(h) - (1 - y) * np.log(1 - h)).mean() def log_likelihood(X, Y, weights): scores = np.dot(X, weights) return np.sum(Y*scores - np.log(1 + np.exp(scores)) ) # here alpha is the learning rate, X is the feature matrix,y is the target matrix def logistic_reg( alpha, X, y, max_iterations=70000, ): theta = np.zeros(X.shape[1]) for iterations in range(max_iterations): z = np.dot(X, theta) h = sigmoid_function(z) gradient = np.dot(X.T, h - y) / y.size theta = theta - alpha * gradient # updating the weights z = np.dot(X, theta) h = sigmoid_function(z) J = cost_function(h, y) if iterations % 100 == 0: print(f'loss: {J} \t') # printing the loss after every 100 iterations return theta # In[68]: if __name__ == '__main__': iris = datasets.load_iris() X = iris.data[:, :2] y = (iris.target != 0) * 1 alpha = 0.1 theta = logistic_reg(alpha,X,y,max_iterations=70000) print("theta: ",theta) # printing the theta i.e our weights vector def predict_prob(X): return sigmoid_function(np.dot(X, theta)) # predicting the value of probability from the logistic regression algorithm plt.figure(figsize=(10, 6)) plt.scatter(X[y == 0][:, 0], X[y == 0][:, 1], color='b', label='0') plt.scatter(X[y == 1][:, 0], X[y == 1][:, 1], color='r', label='1') (x1_min, x1_max) = (X[:, 0].min(), X[:, 0].max()) (x2_min, x2_max) = (X[:, 1].min(), X[:, 1].max()) (xx1, xx2) = np.meshgrid(np.linspace(x1_min, x1_max), np.linspace(x2_min, x2_max)) grid = np.c_[xx1.ravel(), xx2.ravel()] probs = predict_prob(grid).reshape(xx1.shape) plt.contour( xx1, xx2, probs, [0.5], linewidths=1, colors='black', ) plt.legend() plt.show()
[]
[]
[]
archives/1098994933_python.zip
machine_learning/random_forest_classification/random_forest_classification.py
# Random Forest Classification # Importing the libraries import os import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset script_dir = os.path.dirname(os.path.realpath(__file__)) dataset = pd.read_csv(os.path.join(script_dir, 'Social_Network_Ads.csv')) X = dataset.iloc[:, [2, 3]].values y = dataset.iloc[:, 4].values # Splitting the dataset into the Training set and Test set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0) # Feature Scaling from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) # Fitting Random Forest Classification to the Training set from sklearn.ensemble import RandomForestClassifier classifier = RandomForestClassifier(n_estimators = 10, criterion = 'entropy', random_state = 0) classifier.fit(X_train, y_train) # Predicting the Test set results y_pred = classifier.predict(X_test) # Making the Confusion Matrix from sklearn.metrics import confusion_matrix cm = confusion_matrix(y_test, y_pred) # Visualising the Training set results from matplotlib.colors import ListedColormap X_set, y_set = X_train, y_train X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01), np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01)) plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape), alpha = 0.75, cmap = ListedColormap(('red', 'green'))) plt.xlim(X1.min(), X1.max()) plt.ylim(X2.min(), X2.max()) for i, j in enumerate(np.unique(y_set)): plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1], c = ListedColormap(('red', 'green'))(i), label = j) plt.title('Random Forest Classification (Training set)') plt.xlabel('Age') plt.ylabel('Estimated Salary') plt.legend() plt.show() # Visualising the Test set results from matplotlib.colors import ListedColormap X_set, y_set = X_test, y_test X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01), np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01)) plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape), alpha = 0.75, cmap = ListedColormap(('red', 'green'))) plt.xlim(X1.min(), X1.max()) plt.ylim(X2.min(), X2.max()) for i, j in enumerate(np.unique(y_set)): plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1], c = ListedColormap(('red', 'green'))(i), label = j) plt.title('Random Forest Classification (Test set)') plt.xlabel('Age') plt.ylabel('Estimated Salary') plt.legend() plt.show()
[]
[]
[]
archives/1098994933_python.zip
machine_learning/random_forest_regression/random_forest_regression.py
# Random Forest Regression # Importing the libraries import os import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset script_dir = os.path.dirname(os.path.realpath(__file__)) dataset = pd.read_csv(os.path.join(script_dir, 'Position_Salaries.csv')) X = dataset.iloc[:, 1:2].values y = dataset.iloc[:, 2].values # Splitting the dataset into the Training set and Test set """from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)""" # Feature Scaling """from sklearn.preprocessing import StandardScaler sc_X = StandardScaler() X_train = sc_X.fit_transform(X_train) X_test = sc_X.transform(X_test) sc_y = StandardScaler() y_train = sc_y.fit_transform(y_train)""" # Fitting Random Forest Regression to the dataset from sklearn.ensemble import RandomForestRegressor regressor = RandomForestRegressor(n_estimators = 10, random_state = 0) regressor.fit(X, y) # Predicting a new result y_pred = regressor.predict([[6.5]]) # Visualising the Random Forest Regression results (higher resolution) X_grid = np.arange(min(X), max(X), 0.01) X_grid = X_grid.reshape((len(X_grid), 1)) plt.scatter(X, y, color = 'red') plt.plot(X_grid, regressor.predict(X_grid), color = 'blue') plt.title('Truth or Bluff (Random Forest Regression)') plt.xlabel('Position level') plt.ylabel('Salary') plt.show()
[]
[]
[]
archives/1098994933_python.zip
machine_learning/scoring_functions.py
import numpy as np """ Here I implemented the scoring functions. MAE, MSE, RMSE, RMSLE are included. Those are used for calculating differences between predicted values and actual values. Metrics are slightly differentiated. Sometimes squared, rooted, even log is used. Using log and roots can be perceived as tools for penalizing big erors. However, using appropriate metrics depends on the situations, and types of data """ #Mean Absolute Error def mae(predict, actual): predict = np.array(predict) actual = np.array(actual) difference = abs(predict - actual) score = difference.mean() return score #Mean Squared Error def mse(predict, actual): predict = np.array(predict) actual = np.array(actual) difference = predict - actual square_diff = np.square(difference) score = square_diff.mean() return score #Root Mean Squared Error def rmse(predict, actual): predict = np.array(predict) actual = np.array(actual) difference = predict - actual square_diff = np.square(difference) mean_square_diff = square_diff.mean() score = np.sqrt(mean_square_diff) return score #Root Mean Square Logarithmic Error def rmsle(predict, actual): predict = np.array(predict) actual = np.array(actual) log_predict = np.log(predict+1) log_actual = np.log(actual+1) difference = log_predict - log_actual square_diff = np.square(difference) mean_square_diff = square_diff.mean() score = np.sqrt(mean_square_diff) return score #Mean Bias Deviation def mbd(predict, actual): predict = np.array(predict) actual = np.array(actual) difference = predict - actual numerator = np.sum(difference) / len(predict) denumerator = np.sum(actual) / len(predict) print(numerator) print(denumerator) score = float(numerator) / denumerator * 100 return score
[]
[]
[]
archives/1098994933_python.zip
machine_learning/sorted_vector_machines.py
from sklearn.datasets import load_iris from sklearn import svm from sklearn.model_selection import train_test_split import doctest # different functions implementing different types of SVM's def NuSVC(train_x, train_y): svc_NuSVC = svm.NuSVC() svc_NuSVC.fit(train_x, train_y) return svc_NuSVC def Linearsvc(train_x, train_y): svc_linear = svm.LinearSVC() svc_linear.fit(train_x, train_y) return svc_linear def SVC(train_x, train_y): # svm.SVC(C=1.0, kernel='rbf', degree=3, gamma=0.0, coef0=0.0, shrinking=True, probability=False,tol=0.001, cache_size=200, class_weight=None, verbose=False, max_iter=-1, random_state=None) # various parameters like "kernal","gamma","C" can effectively tuned for a given machine learning model. SVC = svm.SVC(gamma="auto") SVC.fit(train_x, train_y) return SVC def test(X_new): """ 3 test cases to be passed an array containing the sepal length (cm), sepal width (cm),petal length (cm),petal width (cm) based on which the target name will be predicted >>> test([1,2,1,4]) 'virginica' >>> test([5, 2, 4, 1]) 'versicolor' >>> test([6,3,4,1]) 'versicolor' """ iris = load_iris() # splitting the dataset to test and train train_x, test_x, train_y, test_y = train_test_split( iris["data"], iris["target"], random_state=4 ) # any of the 3 types of SVM can be used # current_model=SVC(train_x, train_y) # current_model=NuSVC(train_x, train_y) current_model = Linearsvc(train_x, train_y) prediction = current_model.predict([X_new]) return iris["target_names"][prediction][0] if __name__ == "__main__": doctest.testmod()
[]
[]
[]
archives/1098994933_python.zip
maths/3n+1.py
from typing import Tuple, List def n31(a: int) -> Tuple[List[int], int]: """ Returns the Collatz sequence and its length of any postiver integer. >>> n31(4) ([4, 2, 1], 3) """ if not isinstance(a, int): raise TypeError('Must be int, not {0}'.format(type(a).__name__)) if a < 1: raise ValueError('Given integer must be greater than 1, not {0}'.format(a)) path = [a] while a != 1: if a % 2 == 0: a = a // 2 else: a = 3*a +1 path += [a] return path, len(path) def main(): num = 4 path , length = n31(num) print("The Collatz sequence of {0} took {1} steps. \nPath: {2}".format(num,length, path)) if __name__ == '__main__': main()
[ "int" ]
[ 43 ]
[ 46 ]
archives/1098994933_python.zip
maths/__init__.py
[]
[]
[]
archives/1098994933_python.zip
maths/abs.py
"""Absolute Value.""" def abs_val(num): """ Find the absolute value of a number. >>abs_val(-5) 5 >>abs_val(0) 0 """ if num < 0: return -num # Returns if number is not < 0 return num def main(): """Print absolute value of -34.""" print(abs_val(-34)) # = 34 if __name__ == '__main__': main()
[]
[]
[]
archives/1098994933_python.zip
maths/abs_max.py
from typing import List def abs_max(x: List[int]) -> int: """ >>> abs_max([0,5,1,11]) 11 >>> abs_max([3,-10,-2]) -10 """ j =x[0] for i in x: if abs(i) > abs(j): j = i return j def abs_max_sort(x): """ >>> abs_max_sort([0,5,1,11]) 11 >>> abs_max_sort([3,-10,-2]) -10 """ return sorted(x,key=abs)[-1] def main(): a = [1,2,-11] assert abs_max(a) == -11 assert abs_max_sort(a) == -11 if __name__ == '__main__': main()
[ "List[int]" ]
[ 41 ]
[ 50 ]
archives/1098994933_python.zip
maths/abs_min.py
from .abs import abs_val def absMin(x): """ >>> absMin([0,5,1,11]) 0 >>> absMin([3,-10,-2]) -2 """ j = x[0] for i in x: if abs_val(i) < abs_val(j): j = i return j def main(): a = [-3,-1,2,-11] print(absMin(a)) # = -1 if __name__ == '__main__': main()
[]
[]
[]
archives/1098994933_python.zip
maths/average_mean.py
"""Find mean of a list of numbers.""" def average(nums): """Find mean of a list of numbers.""" sum = 0 for x in nums: sum += x avg = sum / len(nums) print(avg) return avg def main(): """Call average module to find mean of a specific list of numbers.""" average([2, 4, 6, 8, 20, 50, 70]) if __name__ == '__main__': main()
[]
[]
[]
archives/1098994933_python.zip
maths/average_median.py
def median(nums): """ Find median of a list of numbers. >>> median([0]) 0 >>> median([4,1,3,2]) 2.5 Args: nums: List of nums Returns: Median. """ sorted_list = sorted(nums) med = None if len(sorted_list) % 2 == 0: mid_index_1 = len(sorted_list) // 2 mid_index_2 = (len(sorted_list) // 2) - 1 med = (sorted_list[mid_index_1] + sorted_list[mid_index_2]) / float(2) else: mid_index = (len(sorted_list) - 1) // 2 med = sorted_list[mid_index] return med def main(): print("Odd number of numbers:") print(median([2, 4, 6, 8, 20, 50, 70])) print("Even number of numbers:") print(median([2, 4, 6, 8, 20, 50])) if __name__ == '__main__': main()
[]
[]
[]
archives/1098994933_python.zip
maths/basic_maths.py
"""Implementation of Basic Math in Python.""" import math def prime_factors(n): """Find Prime Factors.""" pf = [] while n % 2 == 0: pf.append(2) n = int(n / 2) for i in range(3, int(math.sqrt(n)) + 1, 2): while n % i == 0: pf.append(i) n = int(n / i) if n > 2: pf.append(n) return pf def number_of_divisors(n): """Calculate Number of Divisors of an Integer.""" div = 1 temp = 1 while n % 2 == 0: temp += 1 n = int(n / 2) div = div * (temp) for i in range(3, int(math.sqrt(n)) + 1, 2): temp = 1 while n % i == 0: temp += 1 n = int(n / i) div = div * (temp) return div def sum_of_divisors(n): """Calculate Sum of Divisors.""" s = 1 temp = 1 while n % 2 == 0: temp += 1 n = int(n / 2) if temp > 1: s *= (2**temp - 1) / (2 - 1) for i in range(3, int(math.sqrt(n)) + 1, 2): temp = 1 while n % i == 0: temp += 1 n = int(n / i) if temp > 1: s *= (i**temp - 1) / (i - 1) return s def euler_phi(n): """Calculte Euler's Phi Function.""" l = prime_factors(n) l = set(l) s = n for x in l: s *= (x - 1) / x return s def main(): """Print the Results of Basic Math Operations.""" print(prime_factors(100)) print(number_of_divisors(100)) print(sum_of_divisors(100)) print(euler_phi(100)) if __name__ == '__main__': main()
[]
[]
[]
archives/1098994933_python.zip
maths/binary_exponentiation.py
"""Binary Exponentiation.""" # Author : Junth Basnet # Time Complexity : O(logn) def binary_exponentiation(a, n): if (n == 0): return 1 elif (n % 2 == 1): return binary_exponentiation(a, n - 1) * a else: b = binary_exponentiation(a, n / 2) return b * b if __name__ == "__main__": try: BASE = int(input("Enter Base : ").strip()) POWER = int(input("Enter Power : ").strip()) except ValueError: print("Invalid literal for integer") RESULT = binary_exponentiation(BASE, POWER) print("{}^({}) : {}".format(BASE, POWER, RESULT))
[]
[]
[]
archives/1098994933_python.zip
maths/collatz_sequence.py
def collatz_sequence(n): """ Collatz conjecture: start with any positive integer n.Next termis obtained from the previous term as follows: if the previous term is even, the next term is one half the previous term. If the previous term is odd, the next term is 3 times the previous term plus 1. The conjecture states the sequence will always reach 1 regaardess of starting n. Example: >>> collatz_sequence(43) [43, 130, 65, 196, 98, 49, 148, 74, 37, 112, 56, 28, 14, 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1] """ sequence = [n] while n != 1: if n % 2 == 0:# even n //= 2 else: n = 3*n +1 sequence.append(n) return sequence def main(): n = 43 sequence = collatz_sequence(n) print(sequence) print("collatz sequence from %d took %d steps."%(n,len(sequence))) if __name__ == '__main__': main()
[]
[]
[]
archives/1098994933_python.zip
maths/extended_euclidean_algorithm.py
""" Extended Euclidean Algorithm. Finds 2 numbers a and b such that it satisfies the equation am + bn = gcd(m, n) (a.k.a Bezout's Identity) """ # @Author: S. Sharma <silentcat> # @Date: 2019-02-25T12:08:53-06:00 # @Email: silentcat@protonmail.com # @Last modified by: PatOnTheBack # @Last modified time: 2019-07-05 import sys def extended_euclidean_algorithm(m, n): """ Extended Euclidean Algorithm. Finds 2 numbers a and b such that it satisfies the equation am + bn = gcd(m, n) (a.k.a Bezout's Identity) """ a = 0 a_prime = 1 b = 1 b_prime = 0 q = 0 r = 0 if m > n: c = m d = n else: c = n d = m while True: q = int(c / d) r = c % d if r == 0: break c = d d = r t = a_prime a_prime = a a = t - q * a t = b_prime b_prime = b b = t - q * b pair = None if m > n: pair = (a, b) else: pair = (b, a) return pair def main(): """Call Extended Euclidean Algorithm.""" if len(sys.argv) < 3: print('2 integer arguments required') exit(1) m = int(sys.argv[1]) n = int(sys.argv[2]) print(extended_euclidean_algorithm(m, n)) if __name__ == '__main__': main()
[]
[]
[]
archives/1098994933_python.zip
maths/factorial_python.py
"""Python program to find the factorial of a number provided by the user.""" # change the value for a different result NUM = 10 # uncomment to take input from the user # num = int(input("Enter a number: ")) FACTORIAL = 1 # check if the number is negative, positive or zero if NUM < 0: print("Sorry, factorial does not exist for negative numbers") elif NUM == 0: print("The factorial of 0 is 1") else: for i in range(1, NUM + 1): FACTORIAL = FACTORIAL * i print("The factorial of", NUM, "is", FACTORIAL)
[]
[]
[]
archives/1098994933_python.zip
maths/factorial_recursive.py
def fact(n): """ Return 1, if n is 1 or below, otherwise, return n * fact(n-1). """ return 1 if n <= 1 else n * fact(n - 1) """ Show factorial for i, where i ranges from 1 to 20. """ for i in range(1, 21): print(i, ": ", fact(i), sep='')
[]
[]
[]
archives/1098994933_python.zip
maths/fermat_little_theorem.py
# Python program to show the usage of Fermat's little theorem in a division # According to Fermat's little theorem, (a / b) mod p always equals a * (b ^ (p - 2)) mod p # Here we assume that p is a prime number, b divides a, and p doesn't divide b # Wikipedia reference: https://en.wikipedia.org/wiki/Fermat%27s_little_theorem def binary_exponentiation(a, n, mod): if (n == 0): return 1 elif (n % 2 == 1): return (binary_exponentiation(a, n - 1, mod) * a) % mod else: b = binary_exponentiation(a, n / 2, mod) return (b * b) % mod # a prime number p = 701 a = 1000000000 b = 10 # using binary exponentiation function, O(log(p)): print((a / b) % p == (a * binary_exponentiation(b, p - 2, p)) % p) # using Python operators: print((a / b) % p == (a * b ** (p - 2)) % p)
[]
[]
[]
archives/1098994933_python.zip
maths/fibonacci.py
# fibonacci.py """ 1. Calculates the iterative fibonacci sequence 2. Calculates the fibonacci sequence with a formula an = [ Phin - (phi)n ]/Sqrt[5] reference-->Su, Francis E., et al. "Fibonacci Number Formula." Math Fun Facts. <http://www.math.hmc.edu/funfacts> """ import math import functools import time from decimal import getcontext, Decimal getcontext().prec = 100 def timer_decorator(func): @functools.wraps(func) def timer_wrapper(*args, **kwargs): start = time.time() func(*args, **kwargs) end = time.time() if int(end - start) > 0: print(f'Run time for {func.__name__}: {(end - start):0.2f}s') else: print(f'Run time for {func.__name__}: {(end - start)*1000:0.2f}ms') return func(*args, **kwargs) return timer_wrapper # define Python user-defined exceptions class Error(Exception): """Base class for other exceptions""" class ValueTooLargeError(Error): """Raised when the input value is too large""" class ValueTooSmallError(Error): """Raised when the input value is not greater than one""" class ValueLessThanZero(Error): """Raised when the input value is less than zero""" def _check_number_input(n, min_thresh, max_thresh=None): """ :param n: single integer :type n: int :param min_thresh: min threshold, single integer :type min_thresh: int :param max_thresh: max threshold, single integer :type max_thresh: int :return: boolean """ try: if n >= min_thresh and max_thresh is None: return True elif min_thresh <= n <= max_thresh: return True elif n < 0: raise ValueLessThanZero elif n < min_thresh: raise ValueTooSmallError elif n > max_thresh: raise ValueTooLargeError except ValueLessThanZero: print("Incorrect Input: number must not be less than 0") except ValueTooSmallError: print(f'Incorrect Input: input number must be > {min_thresh} for the recursive calculation') except ValueTooLargeError: print(f'Incorrect Input: input number must be < {max_thresh} for the recursive calculation') return False @timer_decorator def fib_iterative(n): """ :param n: calculate Fibonacci to the nth integer :type n:int :return: Fibonacci sequence as a list """ n = int(n) if _check_number_input(n, 2): seq_out = [0, 1] a, b = 0, 1 for _ in range(n-len(seq_out)): a, b = b, a+b seq_out.append(b) return seq_out @timer_decorator def fib_formula(n): """ :param n: calculate Fibonacci to the nth integer :type n:int :return: Fibonacci sequence as a list """ seq_out = [0, 1] n = int(n) if _check_number_input(n, 2, 1000000): sqrt = Decimal(math.sqrt(5)) phi_1 = Decimal(1 + sqrt) / Decimal(2) phi_2 = Decimal(1 - sqrt) / Decimal(2) for i in range(2, n): temp_out = ((phi_1**Decimal(i)) - (phi_2**Decimal(i))) * (Decimal(sqrt) ** Decimal(-1)) seq_out.append(int(temp_out)) return seq_out if __name__ == '__main__': num = 20 # print(f'{fib_recursive(num)}\n') # print(f'{fib_iterative(num)}\n') # print(f'{fib_formula(num)}\n') fib_iterative(num) fib_formula(num)
[]
[]
[]
archives/1098994933_python.zip
maths/fibonacci_sequence_recursion.py
# Fibonacci Sequence Using Recursion def recur_fibo(n): if n <= 1: return n else: (recur_fibo(n-1) + recur_fibo(n-2)) def isPositiveInteger(limit): return limit >= 0 def main(): limit = int(input("How many terms to include in fibonacci series: ")) if isPositiveInteger(limit): print("The first {limit} terms of the fibonacci series are as follows:") print([recur_fibo(n) for n in range(limit)]) else: print("Please enter a positive integer: ") if __name__ == '__main__': main()
[]
[]
[]
archives/1098994933_python.zip
maths/find_lcm.py
"""Find Least Common Multiple.""" # https://en.wikipedia.org/wiki/Least_common_multiple def find_lcm(num_1, num_2): """Find the least common multiple of two numbers. >>> find_lcm(5,2) 10 >>> find_lcm(12,76) 228 """ if num_1>=num_2: max_num=num_1 else: max_num=num_2 lcm = max_num while True: if ((lcm % num_1 == 0) and (lcm % num_2 == 0)): break lcm += max_num return lcm def main(): """Use test numbers to run the find_lcm algorithm.""" num_1 = int(input().strip()) num_2 = int(input().strip()) print(find_lcm(num_1, num_2)) if __name__ == '__main__': main()
[]
[]
[]
archives/1098994933_python.zip
maths/find_max.py
# NguyenU def find_max(nums): max = nums[0] for x in nums: if x > max: max = x print(max) def main(): find_max([2, 4, 9, 7, 19, 94, 5]) if __name__ == '__main__': main()
[]
[]
[]
archives/1098994933_python.zip
maths/find_min.py
"""Find Minimum Number in a List.""" def main(): """Find Minimum Number in a List.""" def find_min(x): min_num = x[0] for i in x: if min_num > i: min_num = i return min_num print(find_min([0, 1, 2, 3, 4, 5, -3, 24, -56])) # = -56 if __name__ == '__main__': main()
[]
[]
[]
archives/1098994933_python.zip
maths/gaussian.py
""" Reference: https://en.wikipedia.org/wiki/Gaussian_function python/black : True python : 3.7.3 """ from numpy import pi, sqrt, exp def gaussian(x, mu: float = 0.0, sigma: float = 1.0) -> int: """ >>> gaussian(1) 0.24197072451914337 >>> gaussian(24) 3.342714441794458e-126 Supports NumPy Arrays Use numpy.meshgrid with this to generate gaussian blur on images. >>> import numpy as np >>> x = np.arange(15) >>> gaussian(x) array([3.98942280e-01, 2.41970725e-01, 5.39909665e-02, 4.43184841e-03, 1.33830226e-04, 1.48671951e-06, 6.07588285e-09, 9.13472041e-12, 5.05227108e-15, 1.02797736e-18, 7.69459863e-23, 2.11881925e-27, 2.14638374e-32, 7.99882776e-38, 1.09660656e-43]) >>> gaussian(15) 5.530709549844416e-50 >>> gaussian([1,2, 'string']) Traceback (most recent call last): ... TypeError: unsupported operand type(s) for -: 'list' and 'float' >>> gaussian('hello world') Traceback (most recent call last): ... TypeError: unsupported operand type(s) for -: 'str' and 'float' >>> gaussian(10**234) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... OverflowError: (34, 'Result too large') >>> gaussian(10**-326) 0.3989422804014327 >>> gaussian(2523, mu=234234, sigma=3425) 0.0 """ return 1 / sqrt(2 * pi * sigma ** 2) * exp(-(x - mu) ** 2 / 2 * sigma ** 2) if __name__ == "__main__": import doctest doctest.testmod()
[]
[]
[]
archives/1098994933_python.zip
maths/greater_common_divisor.py
""" Greater Common Divisor. Wikipedia reference: https://en.wikipedia.org/wiki/Greatest_common_divisor """ def gcd(a, b): """Calculate Greater Common Divisor (GCD).""" return b if a == 0 else gcd(b % a, a) def main(): """Call GCD Function.""" try: nums = input("Enter two Integers separated by comma (,): ").split(',') num_1 = int(nums[0]) num_2 = int(nums[1]) except (IndexError, UnboundLocalError, ValueError): print("Wrong Input") print(f"gcd({num_1}, {num_2}) = {gcd(num_1, num_2)}") if __name__ == '__main__': main()
[]
[]
[]
archives/1098994933_python.zip
maths/is_square_free.py
""" References: wikipedia:square free number python/black : True flake8 : True """ from typing import List def is_square_free(factors: List[int]) -> bool: """ # doctest: +NORMALIZE_WHITESPACE This functions takes a list of prime factors as input. returns True if the factors are square free. >>> is_square_free([1, 1, 2, 3, 4]) False These are wrong but should return some value it simply checks for repition in the numbers. >>> is_square_free([1, 3, 4, 'sd', 0.0]) True >>> is_square_free([1, 0.5, 2, 0.0]) True >>> is_square_free([1, 2, 2, 5]) False >>> is_square_free('asd') True >>> is_square_free(24) Traceback (most recent call last): ... TypeError: 'int' object is not iterable """ return len(set(factors)) == len(factors) if __name__ == "__main__": import doctest doctest.testmod()
[ "List[int]" ]
[ 145 ]
[ 154 ]
archives/1098994933_python.zip
maths/largest_of_very_large_numbers.py
# Author: Abhijeeth S import math def res(x, y): if 0 not in (x, y): # We use the relation x^y = y*log10(x), where 10 is the base. return y * math.log10(x) else: if x == 0: # 0 raised to any number is 0 return 0 elif y == 0: return 1 # any number raised to 0 is 1 if __name__ == "__main__": # Main function # Read two numbers from input and typecast them to int using map function. # Here x is the base and y is the power. prompt = "Enter the base and the power separated by a comma: " x1, y1 = map(int, input(prompt).split(",")) x2, y2 = map(int, input(prompt).split(",")) # We find the log of each number, using the function res(), which takes two # arguments. res1 = res(x1, y1) res2 = res(x2, y2) # We check for the largest number if res1 > res2: print("Largest number is", x1, "^", y1) elif res2 > res1: print("Largest number is", x2, "^", y2) else: print("Both are equal")
[]
[]
[]
archives/1098994933_python.zip
maths/lucas_lehmer_primality_test.py
# -*- coding: utf-8 -*- """ In mathematics, the Lucas–Lehmer test (LLT) is a primality test for Mersenne numbers. https://en.wikipedia.org/wiki/Lucas%E2%80%93Lehmer_primality_test A Mersenne number is a number that is one less than a power of two. That is M_p = 2^p - 1 https://en.wikipedia.org/wiki/Mersenne_prime The Lucas–Lehmer test is the primality test used by the Great Internet Mersenne Prime Search (GIMPS) to locate large primes. """ # Primality test 2^p - 1 # Return true if 2^p - 1 is prime def lucas_lehmer_test(p: int) -> bool: """ >>> lucas_lehmer_test(p=7) True >>> lucas_lehmer_test(p=11) False # M_11 = 2^11 - 1 = 2047 = 23 * 89 """ if p < 2: raise ValueError("p should not be less than 2!") elif p == 2: return True s = 4 M = (1 << p) - 1 for i in range(p - 2): s = ((s * s) - 2) % M return s == 0 if __name__ == "__main__": print(lucas_lehmer_test(7)) print(lucas_lehmer_test(11))
[ "int" ]
[ 609 ]
[ 612 ]
archives/1098994933_python.zip
maths/lucas_series.py
# Lucas Sequence Using Recursion def recur_luc(n): """ >>> recur_luc(1) 1 >>> recur_luc(0) 2 """ if n == 1: return n if n == 0: return 2 return recur_luc(n - 1) + recur_luc(n - 2) if __name__ == "__main__": limit = int(input("How many terms to include in Lucas series:")) print("Lucas series:") for i in range(limit): print(recur_luc(i))
[]
[]
[]
archives/1098994933_python.zip
maths/mobius_function.py
""" Refrences: https://en.wikipedia.org/wiki/M%C3%B6bius_function References: wikipedia:square free number python/black : True flake8 : True """ from maths.prime_factors import prime_factors from maths.is_square_free import is_square_free def mobius(n: int) -> int: """ Mobius function >>> mobius(24) 0 >>> mobius(-1) 1 >>> mobius('asd') Traceback (most recent call last): ... TypeError: '<=' not supported between instances of 'int' and 'str' >>> mobius(10**400) 0 >>> mobius(10**-400) 1 >>> mobius(-1424) 1 >>> mobius([1, '2', 2.0]) Traceback (most recent call last): ... TypeError: '<=' not supported between instances of 'int' and 'list' """ factors = prime_factors(n) if is_square_free(factors): return -1 if len(factors) % 2 else 1 return 0 if __name__ == "__main__": import doctest doctest.testmod()
[ "int" ]
[ 267 ]
[ 270 ]
archives/1098994933_python.zip
maths/modular_exponential.py
"""Modular Exponential.""" def modular_exponential(base, power, mod): """Calculate Modular Exponential.""" if power < 0: return -1 base %= mod result = 1 while power > 0: if power & 1: result = (result * base) % mod power = power >> 1 base = (base * base) % mod return result def main(): """Call Modular Exponential Function.""" print(modular_exponential(3, 200, 13)) if __name__ == '__main__': main()
[]
[]
[]
archives/1098994933_python.zip
maths/newton_raphson.py
''' Author: P Shreyas Shetty Implementation of Newton-Raphson method for solving equations of kind f(x) = 0. It is an iterative method where solution is found by the expression x[n+1] = x[n] + f(x[n])/f'(x[n]) If no solution exists, then either the solution will not be found when iteration limit is reached or the gradient f'(x[n]) approaches zero. In both cases, exception is raised. If iteration limit is reached, try increasing maxiter. ''' import math as m def calc_derivative(f, a, h=0.001): ''' Calculates derivative at point a for function f using finite difference method ''' return (f(a+h)-f(a-h))/(2*h) def newton_raphson(f, x0=0, maxiter=100, step=0.0001, maxerror=1e-6,logsteps=False): a = x0 #set the initial guess steps = [a] error = abs(f(a)) f1 = lambda x:calc_derivative(f, x, h=step) #Derivative of f(x) for _ in range(maxiter): if f1(a) == 0: raise ValueError("No converging solution found") a = a - f(a)/f1(a) #Calculate the next estimate if logsteps: steps.append(a) if error < maxerror: break else: raise ValueError("Iteration limit reached, no converging solution found") if logsteps: #If logstep is true, then log intermediate steps return a, error, steps return a, error if __name__ == '__main__': import matplotlib.pyplot as plt f = lambda x:m.tanh(x)**2-m.exp(3*x) solution, error, steps = newton_raphson(f, x0=10, maxiter=1000, step=1e-6, logsteps=True) plt.plot([abs(f(x)) for x in steps]) plt.xlabel("step") plt.ylabel("error") plt.show() print("solution = {%f}, error = {%f}" % (solution, error))
[]
[]
[]
archives/1098994933_python.zip
maths/prime_check.py
"""Prime Check.""" import math import unittest def prime_check(number): """ Check to See if a Number is Prime. A number is prime if it has exactly two dividers: 1 and itself. """ if number < 2: # Negatives, 0 and 1 are not primes return False if number < 4: # 2 and 3 are primes return True if number % 2 == 0: # Even values are not primes return False # Except 2, all primes are odd. If any odd value divide # the number, then that number is not prime. odd_numbers = range(3, int(math.sqrt(number)) + 1, 2) return not any(number % i == 0 for i in odd_numbers) class Test(unittest.TestCase): def test_primes(self): self.assertTrue(prime_check(2)) self.assertTrue(prime_check(3)) self.assertTrue(prime_check(5)) self.assertTrue(prime_check(7)) self.assertTrue(prime_check(11)) self.assertTrue(prime_check(13)) self.assertTrue(prime_check(17)) self.assertTrue(prime_check(19)) self.assertTrue(prime_check(23)) self.assertTrue(prime_check(29)) def test_not_primes(self): self.assertFalse(prime_check(-19), "Negative numbers are not prime.") self.assertFalse(prime_check(0), "Zero doesn't have any divider, primes must have two") self.assertFalse(prime_check(1), "One just have 1 divider, primes must have two.") self.assertFalse(prime_check(2 * 2)) self.assertFalse(prime_check(2 * 3)) self.assertFalse(prime_check(3 * 3)) self.assertFalse(prime_check(3 * 5)) self.assertFalse(prime_check(3 * 5 * 7)) if __name__ == '__main__': unittest.main()
[]
[]
[]
archives/1098994933_python.zip
maths/prime_factors.py
""" python/black : True """ from typing import List def prime_factors(n: int) -> List[int]: """ Returns prime factors of n as a list. >>> prime_factors(0) [] >>> prime_factors(100) [2, 2, 5, 5] >>> prime_factors(2560) [2, 2, 2, 2, 2, 2, 2, 2, 2, 5] >>> prime_factors(10**-2) [] >>> prime_factors(0.02) [] >>> x = prime_factors(10**241) # doctest: +NORMALIZE_WHITESPACE >>> x == [2]*241 + [5]*241 True >>> prime_factors(10**-354) [] >>> prime_factors('hello') Traceback (most recent call last): ... TypeError: '<=' not supported between instances of 'int' and 'str' >>> prime_factors([1,2,'hello']) Traceback (most recent call last): ... TypeError: '<=' not supported between instances of 'int' and 'list' """ i = 2 factors = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(i) if n > 1: factors.append(n) return factors if __name__ == "__main__": import doctest doctest.testmod()
[ "int" ]
[ 75 ]
[ 78 ]
archives/1098994933_python.zip
maths/quadratic_equations_complex_numbers.py
from math import sqrt from typing import Tuple def QuadraticEquation(a: int, b: int, c: int) -> Tuple[str, str]: """ Given the numerical coefficients a, b and c, prints the solutions for a quadratic equation, for a*x*x + b*x + c. >>> QuadraticEquation(a=1, b=3, c=-4) ('1.0', '-4.0') >>> QuadraticEquation(5, 6, 1) ('-0.2', '-1.0') """ if a == 0: raise ValueError("Coefficient 'a' must not be zero for quadratic equations.") delta = b * b - 4 * a * c if delta >= 0: return str((-b + sqrt(delta)) / (2 * a)), str((-b - sqrt(delta)) / (2 * a)) """ Treats cases of Complexes Solutions(i = imaginary unit) Ex.: a = 5, b = 2, c = 1 Solution1 = (- 2 + 4.0 *i)/2 and Solution2 = (- 2 + 4.0 *i)/ 10 """ snd = sqrt(-delta) if b == 0: return f"({snd} * i) / 2", f"({snd} * i) / {2 * a}" b = -abs(b) return f"({b}+{snd} * i) / 2", f"({b}+{snd} * i) / {2 * a}" def main(): solutions = QuadraticEquation(a=5, b=6, c=1) print("The equation solutions are: {} and {}".format(*solutions)) # The equation solutions are: -0.2 and -1.0 if __name__ == "__main__": main()
[ "int", "int", "int" ]
[ 74, 82, 90 ]
[ 77, 85, 93 ]
archives/1098994933_python.zip
maths/radix2_fft.py
""" Fast Polynomial Multiplication using radix-2 fast Fourier Transform. """ import mpmath # for roots of unity import numpy as np class FFT: """ Fast Polynomial Multiplication using radix-2 fast Fourier Transform. Reference: https://en.wikipedia.org/wiki/Cooley%E2%80%93Tukey_FFT_algorithm#The_radix-2_DIT_case For polynomials of degree m and n the algorithms has complexity O(n*logn + m*logm) The main part of the algorithm is split in two parts: 1) __DFT: We compute the discrete fourier transform (DFT) of A and B using a bottom-up dynamic approach - 2) __multiply: Once we obtain the DFT of A*B, we can similarly invert it to obtain A*B The class FFT takes two polynomials A and B with complex coefficients as arguments; The two polynomials should be represented as a sequence of coefficients starting from the free term. Thus, for instance x + 2*x^3 could be represented as [0,1,0,2] or (0,1,0,2). The constructor adds some zeros at the end so that the polynomials have the same length which is a power of 2 at least the length of their product. Example: Create two polynomials as sequences >>> A = [0, 1, 0, 2] # x+2x^3 >>> B = (2, 3, 4, 0) # 2+3x+4x^2 Create an FFT object with them >>> x = FFT(A, B) Print product >>> print(x.product) # 2x + 3x^2 + 8x^3 + 4x^4 + 6x^5 [(-0+0j), (2+0j), (3+0j), (8+0j), (6+0j), (8+0j)] __str__ test >>> print(x) A = 0*x^0 + 1*x^1 + 2*x^0 + 3*x^2 B = 0*x^2 + 1*x^3 + 2*x^4 A*B = 0*x^(-0+0j) + 1*x^(2+0j) + 2*x^(3+0j) + 3*x^(8+0j) + 4*x^(6+0j) + 5*x^(8+0j) """ def __init__(self, polyA=[0], polyB=[0]): # Input as list self.polyA = list(polyA)[:] self.polyB = list(polyB)[:] # Remove leading zero coefficients while self.polyA[-1] == 0: self.polyA.pop() self.len_A = len(self.polyA) while self.polyB[-1] == 0: self.polyB.pop() self.len_B = len(self.polyB) # Add 0 to make lengths equal a power of 2 self.C_max_length = int( 2 ** np.ceil( np.log2( len(self.polyA) + len(self.polyB) - 1 ) ) ) while len(self.polyA) < self.C_max_length: self.polyA.append(0) while len(self.polyB) < self.C_max_length: self.polyB.append(0) # A complex root used for the fourier transform self.root = complex( mpmath.root(x=1, n=self.C_max_length, k=1) ) # The product self.product = self.__multiply() # Discrete fourier transform of A and B def __DFT(self, which): if which == "A": dft = [[x] for x in self.polyA] else: dft = [[x] for x in self.polyB] # Corner case if len(dft) <= 1: return dft[0] # next_ncol = self.C_max_length // 2 while next_ncol > 0: new_dft = [[] for i in range(next_ncol)] root = self.root ** next_ncol # First half of next step current_root = 1 for j in range( self.C_max_length // (next_ncol * 2) ): for i in range(next_ncol): new_dft[i].append( dft[i][j] + current_root * dft[i + next_ncol][j] ) current_root *= root # Second half of next step current_root = 1 for j in range( self.C_max_length // (next_ncol * 2) ): for i in range(next_ncol): new_dft[i].append( dft[i][j] - current_root * dft[i + next_ncol][j] ) current_root *= root # Update dft = new_dft next_ncol = next_ncol // 2 return dft[0] # multiply the DFTs of A and B and find A*B def __multiply(self): dftA = self.__DFT("A") dftB = self.__DFT("B") inverseC = [ [ dftA[i] * dftB[i] for i in range(self.C_max_length) ] ] del dftA del dftB # Corner Case if len(inverseC[0]) <= 1: return inverseC[0] # Inverse DFT next_ncol = 2 while next_ncol <= self.C_max_length: new_inverseC = [[] for i in range(next_ncol)] root = self.root ** (next_ncol // 2) current_root = 1 # First half of next step for j in range(self.C_max_length // next_ncol): for i in range(next_ncol // 2): # Even positions new_inverseC[i].append( ( inverseC[i][j] + inverseC[i][ j + self.C_max_length // next_ncol ] ) / 2 ) # Odd positions new_inverseC[i + next_ncol // 2].append( ( inverseC[i][j] - inverseC[i][ j + self.C_max_length // next_ncol ] ) / (2 * current_root) ) current_root *= root # Update inverseC = new_inverseC next_ncol *= 2 # Unpack inverseC = [ round(x[0].real, 8) + round(x[0].imag, 8) * 1j for x in inverseC ] # Remove leading 0's while inverseC[-1] == 0: inverseC.pop() return inverseC # Overwrite __str__ for print(); Shows A, B and A*B def __str__(self): A = "A = " + " + ".join( f"{coef}*x^{i}" for coef, i in enumerate( self.polyA[: self.len_A] ) ) B = "B = " + " + ".join( f"{coef}*x^{i}" for coef, i in enumerate( self.polyB[: self.len_B] ) ) C = "A*B = " + " + ".join( f"{coef}*x^{i}" for coef, i in enumerate(self.product) ) return "\n".join((A, B, C)) # Unit tests if __name__ == "__main__": import doctest doctest.testmod()
[]
[]
[]
archives/1098994933_python.zip
maths/segmented_sieve.py
"""Segmented Sieve.""" import math def sieve(n): """Segmented Sieve.""" in_prime = [] start = 2 end = int(math.sqrt(n)) # Size of every segment temp = [True] * (end + 1) prime = [] while start <= end: if temp[start] is True: in_prime.append(start) for i in range(start * start, end + 1, start): if temp[i] is True: temp[i] = False start += 1 prime += in_prime low = end + 1 high = low + end - 1 if high > n: high = n while low <= n: temp = [True] * (high - low + 1) for each in in_prime: t = math.floor(low / each) * each if t < low: t += each for j in range(t, high + 1, each): temp[j - low] = False for j in range(len(temp)): if temp[j] is True: prime.append(j + low) low = high + 1 high = low + end - 1 if high > n: high = n return prime print(sieve(10**6))
[]
[]
[]
archives/1098994933_python.zip
maths/sieve_of_eratosthenes.py
# -*- coding: utf-8 -*- """ Sieve of Eratosthones The sieve of Eratosthenes is an algorithm used to find prime numbers, less than or equal to a given value. Illustration: https://upload.wikimedia.org/wikipedia/commons/b/b9/Sieve_of_Eratosthenes_animation.gif Reference: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes doctest provider: Bruno Simas Hadlich (https://github.com/brunohadlich) Also thanks Dmitry (https://github.com/LizardWizzard) for finding the problem """ import math def sieve(n): """ Returns a list with all prime numbers up to n. >>> sieve(50) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] >>> sieve(25) [2, 3, 5, 7, 11, 13, 17, 19, 23] >>> sieve(10) [2, 3, 5, 7] >>> sieve(9) [2, 3, 5, 7] >>> sieve(2) [2] >>> sieve(1) [] """ l = [True] * (n + 1) prime = [] start = 2 end = int(math.sqrt(n)) while start <= end: # If start is a prime if l[start] is True: prime.append(start) # Set multiples of start be False for i in range(start * start, n + 1, start): if l[i] is True: l[i] = False start += 1 for j in range(end + 1, n + 1): if l[j] is True: prime.append(j) return prime if __name__ == "__main__": print(sieve(int(input("Enter n: ").strip())))
[]
[]
[]
archives/1098994933_python.zip
maths/simpson_rule.py
""" Numerical integration or quadrature for a smooth function f with known values at x_i This method is the classical approch of suming 'Equally Spaced Abscissas' method 2: "Simpson Rule" """ def method_2(boundary, steps): # "Simpson Rule" # int(f) = delta_x/2 * (b-a)/3*(f1 + 4f2 + 2f_3 + ... + fn) h = (boundary[1] - boundary[0]) / steps a = boundary[0] b = boundary[1] x_i = make_points(a,b,h) y = 0.0 y += (h/3.0)*f(a) cnt = 2 for i in x_i: y += (h/3)*(4-2*(cnt%2))*f(i) cnt += 1 y += (h/3.0)*f(b) return y def make_points(a,b,h): x = a + h while x < (b-h): yield x x = x + h def f(x): #enter your function here y = (x-0)*(x-0) return y def main(): a = 0.0 #Lower bound of integration b = 1.0 #Upper bound of integration steps = 10.0 #define number of steps or resolution boundary = [a, b] #define boundary of integration y = method_2(boundary, steps) print('y = {0}'.format(y)) if __name__ == '__main__': main()
[]
[]
[]
archives/1098994933_python.zip
maths/test_prime_check.py
""" Minimalist file that allows pytest to find and run the Test unittest. For details, see: http://doc.pytest.org/en/latest/goodpractices.html#conventions-for-python-test-discovery """ from .prime_check import Test Test()
[]
[]
[]
archives/1098994933_python.zip
maths/trapezoidal_rule.py
""" Numerical integration or quadrature for a smooth function f with known values at x_i This method is the classical approch of suming 'Equally Spaced Abscissas' method 1: "extended trapezoidal rule" """ def method_1(boundary, steps): # "extended trapezoidal rule" # int(f) = dx/2 * (f1 + 2f2 + ... + fn) h = (boundary[1] - boundary[0]) / steps a = boundary[0] b = boundary[1] x_i = make_points(a,b,h) y = 0.0 y += (h/2.0)*f(a) for i in x_i: #print(i) y += h*f(i) y += (h/2.0)*f(b) return y def make_points(a,b,h): x = a + h while x < (b-h): yield x x = x + h def f(x): #enter your function here y = (x-0)*(x-0) return y def main(): a = 0.0 #Lower bound of integration b = 1.0 #Upper bound of integration steps = 10.0 #define number of steps or resolution boundary = [a, b] #define boundary of integration y = method_1(boundary, steps) print('y = {0}'.format(y)) if __name__ == '__main__': main()
[]
[]
[]
archives/1098994933_python.zip
maths/volume.py
""" Find Volumes of Various Shapes. Wikipedia reference: https://en.wikipedia.org/wiki/Volume """ from math import pi def vol_cube(side_length): """Calculate the Volume of a Cube.""" # Cube side_length. return float(side_length ** 3) def vol_cuboid(width, height, length): """Calculate the Volume of a Cuboid.""" # Multiply lengths together. return float(width * height * length) def vol_cone(area_of_base, height): """ Calculate the Volume of a Cone. Wikipedia reference: https://en.wikipedia.org/wiki/Cone volume = (1/3) * area_of_base * height """ return (float(1) / 3) * area_of_base * height def vol_right_circ_cone(radius, height): """ Calculate the Volume of a Right Circular Cone. Wikipedia reference: https://en.wikipedia.org/wiki/Cone volume = (1/3) * pi * radius^2 * height """ return (float(1) / 3) * pi * (radius ** 2) * height def vol_prism(area_of_base, height): """ Calculate the Volume of a Prism. V = Bh Wikipedia reference: https://en.wikipedia.org/wiki/Prism_(geometry) """ return float(area_of_base * height) def vol_pyramid(area_of_base, height): """ Calculate the Volume of a Prism. V = (1/3) * Bh Wikipedia reference: https://en.wikipedia.org/wiki/Pyramid_(geometry) """ return (float(1) / 3) * area_of_base * height def vol_sphere(radius): """ Calculate the Volume of a Sphere. V = (4/3) * pi * r^3 Wikipedia reference: https://en.wikipedia.org/wiki/Sphere """ return (float(4) / 3) * pi * radius ** 3 def vol_circular_cylinder(radius, height): """Calculate the Volume of a Circular Cylinder. Wikipedia reference: https://en.wikipedia.org/wiki/Cylinder volume = pi * radius^2 * height """ return pi * radius ** 2 * height def main(): """Print the Results of Various Volume Calculations.""" print("Volumes:") print("Cube: " + str(vol_cube(2))) # = 8 print("Cuboid: " + str(vol_cuboid(2, 2, 2))) # = 8 print("Cone: " + str(vol_cone(2, 2))) # ~= 1.33 print("Right Circular Cone: " + str(vol_right_circ_cone(2, 2))) # ~= 8.38 print("Prism: " + str(vol_prism(2, 2))) # = 4 print("Pyramid: " + str(vol_pyramid(2, 2))) # ~= 1.33 print("Sphere: " + str(vol_sphere(2))) # ~= 33.5 print("Circular Cylinder: " + str(vol_circular_cylinder(2, 2))) # ~= 25.1 if __name__ == "__main__": main()
[]
[]
[]
archives/1098994933_python.zip
maths/zellers_congruence.py
import datetime import argparse def zeller(date_input: str) -> str: """ Zellers Congruence Algorithm Find the day of the week for nearly any Gregorian or Julian calendar date >>> zeller('01-31-2010') 'Your date 01-31-2010, is a Sunday!' Validate out of range month >>> zeller('13-31-2010') Traceback (most recent call last): ... ValueError: Month must be between 1 - 12 >>> zeller('.2-31-2010') Traceback (most recent call last): ... ValueError: invalid literal for int() with base 10: '.2' Validate out of range date: >>> zeller('01-33-2010') Traceback (most recent call last): ... ValueError: Date must be between 1 - 31 >>> zeller('01-.4-2010') Traceback (most recent call last): ... ValueError: invalid literal for int() with base 10: '.4' Validate second seperator: >>> zeller('01-31*2010') Traceback (most recent call last): ... ValueError: Date seperator must be '-' or '/' Validate first seperator: >>> zeller('01^31-2010') Traceback (most recent call last): ... ValueError: Date seperator must be '-' or '/' Validate out of range year: >>> zeller('01-31-8999') Traceback (most recent call last): ... ValueError: Year out of range. There has to be some sort of limit...right? Test null input: >>> zeller() Traceback (most recent call last): ... TypeError: zeller() missing 1 required positional argument: 'date_input' Test length fo date_input: >>> zeller('') Traceback (most recent call last): ... ValueError: Must be 10 characters long >>> zeller('01-31-19082939') Traceback (most recent call last): ... ValueError: Must be 10 characters long """ # Days of the week for response days = { '0': 'Sunday', '1': 'Monday', '2': 'Tuesday', '3': 'Wednesday', '4': 'Thursday', '5': 'Friday', '6': 'Saturday' } convert_datetime_days = { 0:1, 1:2, 2:3, 3:4, 4:5, 5:6, 6:0 } # Validate if not 0 < len(date_input) < 11: raise ValueError("Must be 10 characters long") # Get month m: int = int(date_input[0] + date_input[1]) # Validate if not 0 < m < 13: raise ValueError("Month must be between 1 - 12") sep_1:str = date_input[2] # Validate if sep_1 not in ["-","/"]: raise ValueError("Date seperator must be '-' or '/'") # Get day d: int = int(date_input[3] + date_input[4]) # Validate if not 0 < d < 32: raise ValueError("Date must be between 1 - 31") # Get second seperator sep_2: str = date_input[5] # Validate if sep_2 not in ["-","/"]: raise ValueError("Date seperator must be '-' or '/'") # Get year y: int = int(date_input[6] + date_input[7] + date_input[8] + date_input[9]) # Arbitrary year range if not 45 < y < 8500: raise ValueError("Year out of range. There has to be some sort of limit...right?") # Get datetime obj for validation dt_ck = datetime.date(int(y), int(m), int(d)) # Start math if m <= 2: y = y - 1 m = m + 12 # maths var c: int = int(str(y)[:2]) k: int = int(str(y)[2:]) t: int = int(2.6*m - 5.39) u: int = int(c / 4) v: int = int(k / 4) x: int = int(d + k) z: int = int(t + u + v + x) w: int = int(z - (2 * c)) f: int = round(w%7) # End math # Validate math if f != convert_datetime_days[dt_ck.weekday()]: raise AssertionError("The date was evaluated incorrectly. Contact developer.") # Response response: str = f"Your date {date_input}, is a {days[str(f)]}!" return response if __name__ == '__main__': import doctest doctest.testmod() parser = argparse.ArgumentParser(description='Find out what day of the week nearly any date is or was. Enter date as a string in the mm-dd-yyyy or mm/dd/yyyy format') parser.add_argument('date_input', type=str, help='Date as a string (mm-dd-yyyy or mm/dd/yyyy)') args = parser.parse_args() zeller(args.date_input)
[ "str" ]
[ 57 ]
[ 60 ]
archives/1098994933_python.zip
matrix/matrix_class.py
# An OOP aproach to representing and manipulating matrices class Matrix: """ Matrix object generated from a 2D array where each element is an array representing a row. Rows can contain type int or float. Common operations and information available. >>> rows = [ ... [1, 2, 3], ... [4, 5, 6], ... [7, 8, 9] ... ] >>> matrix = Matrix(rows) >>> print(matrix) [[1. 2. 3.] [4. 5. 6.] [7. 8. 9.]] Matrix rows and columns are available as 2D arrays >>> print(matrix.rows) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> print(matrix.columns()) [[1, 4, 7], [2, 5, 8], [3, 6, 9]] Order is returned as a tuple >>> matrix.order (3, 3) Squareness and invertability are represented as bool >>> matrix.is_square True >>> matrix.is_invertable() False Identity, Minors, Cofactors and Adjugate are returned as Matrices. Inverse can be a Matrix or Nonetype >>> print(matrix.identity()) [[1. 0. 0.] [0. 1. 0.] [0. 0. 1.]] >>> print(matrix.minors()) [[-3. -6. -3.] [-6. -12. -6.] [-3. -6. -3.]] >>> print(matrix.cofactors()) [[-3. 6. -3.] [6. -12. 6.] [-3. 6. -3.]] >>> print(matrix.adjugate()) # won't be apparent due to the nature of the cofactor matrix [[-3. 6. -3.] [6. -12. 6.] [-3. 6. -3.]] >>> print(matrix.inverse()) None Determinant is an int, float, or Nonetype >>> matrix.determinant() 0 Negation, scalar multiplication, addition, subtraction, multiplication and exponentiation are available and all return a Matrix >>> print(-matrix) [[-1. -2. -3.] [-4. -5. -6.] [-7. -8. -9.]] >>> matrix2 = matrix * 3 >>> print(matrix2) [[3. 6. 9.] [12. 15. 18.] [21. 24. 27.]] >>> print(matrix + matrix2) [[4. 8. 12.] [16. 20. 24.] [28. 32. 36.]] >>> print(matrix - matrix2) [[-2. -4. -6.] [-8. -10. -12.] [-14. -16. -18.]] >>> print(matrix ** 3) [[468. 576. 684.] [1062. 1305. 1548.] [1656. 2034. 2412.]] Matrices can also be modified >>> matrix.add_row([10, 11, 12]) >>> print(matrix) [[1. 2. 3.] [4. 5. 6.] [7. 8. 9.] [10. 11. 12.]] >>> matrix2.add_column([8, 16, 32]) >>> print(matrix2) [[3. 6. 9. 8.] [12. 15. 18. 16.] [21. 24. 27. 32.]] >>> print(matrix * matrix2) [[90. 108. 126. 136.] [198. 243. 288. 304.] [306. 378. 450. 472.] [414. 513. 612. 640.]] """ def __init__(self, rows): error = TypeError( "Matrices must be formed from a list of zero or more lists containing at least one and the same number of values, \ each of which must be of type int or float" ) if len(rows) != 0: cols = len(rows[0]) if cols == 0: raise error for row in rows: if not len(row) == cols: raise error for value in row: if not isinstance(value, (int, float)): raise error self.rows = rows else: self.rows = [] # MATRIX INFORMATION def columns(self): return [[row[i] for row in self.rows] for i in range(len(self.rows[0]))] @property def num_rows(self): return len(self.rows) @property def num_columns(self): return len(self.rows[0]) @property def order(self): return (self.num_rows, self.num_columns) @property def is_square(self): if self.order[0] == self.order[1]: return True return False def identity(self): values = [ [0 if column_num != row_num else 1 for column_num in range(self.num_rows)] for row_num in range(self.num_rows) ] return Matrix(values) def determinant(self): if not self.is_square: return None if self.order == (0, 0): return 1 if self.order == (1, 1): return self.rows[0][0] if self.order == (2, 2): return (self.rows[0][0] * self.rows[1][1]) - ( self.rows[0][1] * self.rows[1][0] ) else: return sum( [ self.rows[0][column] * self.cofactors().rows[0][column] for column in range(self.num_columns) ] ) def is_invertable(self): if self.determinant(): return True return False def get_minor(self, row, column): values = [ [ self.rows[other_row][other_column] for other_column in range(self.num_columns) if other_column != column ] for other_row in range(self.num_rows) if other_row != row ] return Matrix(values).determinant() def get_cofactor(self, row, column): if (row + column) % 2 == 0: return self.get_minor(row, column) return -1 * self.get_minor(row, column) def minors(self): return Matrix( [ [self.get_minor(row, column) for column in range(self.num_columns)] for row in range(self.num_rows) ] ) def cofactors(self): return Matrix( [ [ self.minors().rows[row][column] if (row + column) % 2 == 0 else self.minors().rows[row][column] * -1 for column in range(self.minors().num_columns) ] for row in range(self.minors().num_rows) ] ) def adjugate(self): values = [ [self.cofactors().rows[column][row] for column in range(self.num_columns)] for row in range(self.num_rows) ] return Matrix(values) def inverse(self): if not self.is_invertable(): return None return self.adjugate() * (1 / self.determinant()) def __repr__(self): return str(self.rows) def __str__(self): if self.num_rows == 0: return "[]" if self.num_rows == 1: return "[[" + ". ".join(self.rows[0]) + "]]" return ( "[" + "\n ".join( [ "[" + ". ".join([str(value) for value in row]) + ".]" for row in self.rows ] ) + "]" ) # MATRIX MANIPULATION def add_row(self, row, position=None): type_error = TypeError("Row must be a list containing all ints and/or floats") if not isinstance(row, list): raise type_error for value in row: if not isinstance(value, (int, float)): raise type_error if len(row) != self.num_columns: raise ValueError( "Row must be equal in length to the other rows in the matrix" ) if position is None: self.rows.append(row) else: self.rows = self.rows[0:position] + [row] + self.rows[position:] def add_column(self, column, position=None): type_error = TypeError( "Column must be a list containing all ints and/or floats" ) if not isinstance(column, list): raise type_error for value in column: if not isinstance(value, (int, float)): raise type_error if len(column) != self.num_rows: raise ValueError( "Column must be equal in length to the other columns in the matrix" ) if position is None: self.rows = [self.rows[i] + [column[i]] for i in range(self.num_rows)] else: self.rows = [ self.rows[i][0:position] + [column[i]] + self.rows[i][position:] for i in range(self.num_rows) ] # MATRIX OPERATIONS def __eq__(self, other): if not isinstance(other, Matrix): raise TypeError("A Matrix can only be compared with another Matrix") if self.rows == other.rows: return True return False def __ne__(self, other): if self == other: return False return True def __neg__(self): return self * -1 def __add__(self, other): if self.order != other.order: raise ValueError("Addition requires matrices of the same order") return Matrix( [ [self.rows[i][j] + other.rows[i][j] for j in range(self.num_columns)] for i in range(self.num_rows) ] ) def __sub__(self, other): if self.order != other.order: raise ValueError("Subtraction requires matrices of the same order") return Matrix( [ [self.rows[i][j] - other.rows[i][j] for j in range(self.num_columns)] for i in range(self.num_rows) ] ) def __mul__(self, other): if not isinstance(other, (int, float, Matrix)): raise TypeError( "A Matrix can only be multiplied by an int, float, or another matrix" ) if type(other) in (int, float): return Matrix([[element * other for element in row] for row in self.rows]) if type(other) is Matrix: if self.num_columns != other.num_rows: raise ValueError( "The number of columns in the first matrix must be equal to the number of rows in the second" ) return Matrix( [ [Matrix.dot_product(row, column) for column in other.columns()] for row in self.rows ] ) def __pow__(self, other): if not isinstance(other, int): raise TypeError("A Matrix can only be raised to the power of an int") if not self.is_square: raise ValueError("Only square matrices can be raised to a power") if other == 0: return self.identity() if other < 0: if self.is_invertable: return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ) result = self for i in range(other - 1): result *= self return result @classmethod def dot_product(cls, row, column): return sum([row[i] * column[i] for i in range(len(row))]) if __name__ == "__main__": import doctest test = doctest.testmod() print(test)
[]
[]
[]
archives/1098994933_python.zip
matrix/matrix_operation.py
""" function based version of matrix operations, which are just 2D arrays """ def add(matrix_a, matrix_b): if _check_not_integer(matrix_a) and _check_not_integer(matrix_b): rows, cols = _verify_matrix_sizes(matrix_a, matrix_b) matrix_c = [] for i in range(rows[0]): list_1 = [] for j in range(cols[0]): val = matrix_a[i][j] + matrix_b[i][j] list_1.append(val) matrix_c.append(list_1) return matrix_c def subtract(matrix_a, matrix_b): if _check_not_integer(matrix_a) and _check_not_integer(matrix_b): rows, cols = _verify_matrix_sizes(matrix_a, matrix_b) matrix_c = [] for i in range(rows[0]): list_1 = [] for j in range(cols[0]): val = matrix_a[i][j] - matrix_b[i][j] list_1.append(val) matrix_c.append(list_1) return matrix_c def scalar_multiply(matrix, n): return [[x * n for x in row] for row in matrix] def multiply(matrix_a, matrix_b): if _check_not_integer(matrix_a) and _check_not_integer(matrix_b): matrix_c = [] rows, cols = _verify_matrix_sizes(matrix_a, matrix_b) if cols[0] != rows[1]: raise ValueError(f'Cannot multiply matrix of dimensions ({rows[0]},{cols[0]}) ' f'and ({rows[1]},{cols[1]})') for i in range(rows[0]): list_1 = [] for j in range(cols[1]): val = 0 for k in range(cols[1]): val = val + matrix_a[i][k] * matrix_b[k][j] list_1.append(val) matrix_c.append(list_1) return matrix_c def identity(n): """ :param n: dimension for nxn matrix :type n: int :return: Identity matrix of shape [n, n] """ n = int(n) return [[int(row == column) for column in range(n)] for row in range(n)] def transpose(matrix, return_map=True): if _check_not_integer(matrix): if return_map: return map(list, zip(*matrix)) else: # mt = [] # for i in range(len(matrix[0])): # mt.append([row[i] for row in matrix]) # return mt return [[row[i] for row in matrix] for i in range(len(matrix[0]))] def minor(matrix, row, column): minor = matrix[:row] + matrix[row + 1:] minor = [row[:column] + row[column + 1:] for row in minor] return minor def determinant(matrix): if len(matrix) == 1: return matrix[0][0] res = 0 for x in range(len(matrix)): res += matrix[0][x] * determinant(minor(matrix, 0, x)) * (-1) ** x return res def inverse(matrix): det = determinant(matrix) if det == 0: return None matrix_minor = [[] for _ in range(len(matrix))] for i in range(len(matrix)): for j in range(len(matrix)): matrix_minor[i].append(determinant(minor(matrix, i, j))) cofactors = [[x * (-1) ** (row + col) for col, x in enumerate(matrix_minor[row])] for row in range(len(matrix))] adjugate = transpose(cofactors) return scalar_multiply(adjugate, 1/det) def _check_not_integer(matrix): try: rows = len(matrix) cols = len(matrix[0]) return True except TypeError: raise TypeError("Cannot input an integer value, it must be a matrix") def _shape(matrix): return list((len(matrix), len(matrix[0]))) def _verify_matrix_sizes(matrix_a, matrix_b): shape = _shape(matrix_a) shape += _shape(matrix_b) if shape[0] != shape[2] or shape[1] != shape[3]: raise ValueError(f"operands could not be broadcast together with shape " f"({shape[0], shape[1]}), ({shape[2], shape[3]})") return [shape[0], shape[2]], [shape[1], shape[3]] def main(): matrix_a = [[12, 10], [3, 9]] matrix_b = [[3, 4], [7, 4]] matrix_c = [[11, 12, 13, 14], [21, 22, 23, 24], [31, 32, 33, 34], [41, 42, 43, 44]] matrix_d = [[3, 0, 2], [2, 0, -2], [0, 1, 1]] print('Add Operation, %s + %s = %s \n' %(matrix_a, matrix_b, (add(matrix_a, matrix_b)))) print('Multiply Operation, %s * %s = %s \n' %(matrix_a, matrix_b, multiply(matrix_a, matrix_b))) print('Identity: %s \n' %identity(5)) print('Minor of %s = %s \n' %(matrix_c, minor(matrix_c, 1, 2))) print('Determinant of %s = %s \n' %(matrix_b, determinant(matrix_b))) print('Inverse of %s = %s\n'%(matrix_d, inverse(matrix_d))) if __name__ == '__main__': main()
[]
[]
[]
archives/1098994933_python.zip
matrix/nth_fibonacci_using_matrix_exponentiation.py
""" Implementation of finding nth fibonacci number using matrix exponentiation. Time Complexity is about O(log(n)*8), where 8 is the complexity of matrix multiplication of size 2 by 2. And on the other hand complexity of bruteforce solution is O(n). As we know f[n] = f[n-1] + f[n-1] Converting to matrix, [f(n),f(n-1)] = [[1,1],[1,0]] * [f(n-1),f(n-2)] -> [f(n),f(n-1)] = [[1,1],[1,0]]^2 * [f(n-2),f(n-3)] ... ... -> [f(n),f(n-1)] = [[1,1],[1,0]]^(n-1) * [f(1),f(0)] So we just need the n times multiplication of the matrix [1,1],[1,0]]. We can decrease the n times multiplication by following the divide and conquer approach. """ def multiply(matrix_a, matrix_b): matrix_c = [] n = len(matrix_a) for i in range(n): list_1 = [] for j in range(n): val = 0 for k in range(n): val = val + matrix_a[i][k] * matrix_b[k][j] list_1.append(val) matrix_c.append(list_1) return matrix_c def identity(n): return [[int(row == column) for column in range(n)] for row in range(n)] def nth_fibonacci_matrix(n): """ >>> nth_fibonacci_matrix(100) 354224848179261915075 >>> nth_fibonacci_matrix(-100) -100 """ if n <= 1: return n res_matrix = identity(2) fibonacci_matrix = [[1, 1], [1, 0]] n = n - 1 while n > 0: if n % 2 == 1: res_matrix = multiply(res_matrix, fibonacci_matrix) fibonacci_matrix = multiply(fibonacci_matrix, fibonacci_matrix) n = int(n / 2) return res_matrix[0][0] def nth_fibonacci_bruteforce(n): """ >>> nth_fibonacci_bruteforce(100) 354224848179261915075 >>> nth_fibonacci_bruteforce(-100) -100 """ if n <= 1: return n fib0 = 0 fib1 = 1 for i in range(2, n + 1): fib0, fib1 = fib1, fib0 + fib1 return fib1 def main(): fmt = "{} fibonacci number using matrix exponentiation is {} and using bruteforce is {}\n" for ordinal in "0th 1st 2nd 3rd 10th 100th 1000th".split(): n = int("".join(c for c in ordinal if c in "0123456789")) # 1000th --> 1000 print(fmt.format(ordinal, nth_fibonacci_matrix(n), nth_fibonacci_bruteforce(n))) # from timeit import timeit # print(timeit("nth_fibonacci_matrix(1000000)", # "from main import nth_fibonacci_matrix", number=5)) # print(timeit("nth_fibonacci_bruteforce(1000000)", # "from main import nth_fibonacci_bruteforce", number=5)) # 2.3342058970001744 # 57.256506615000035 if __name__ == "__main__": main()
[]
[]
[]
archives/1098994933_python.zip
matrix/rotate_matrix.py
# -*- coding: utf-8 -*- """ In this problem, we want to rotate the matrix elements by 90, 180, 270 (counterclockwise) Discussion in stackoverflow: https://stackoverflow.com/questions/42519/how-do-you-rotate-a-two-dimensional-array """ def make_matrix(row_size: int = 4) -> [[int]]: """ >>> make_matrix() [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] >>> make_matrix(1) [[1]] >>> make_matrix(-2) [[1, 2], [3, 4]] >>> make_matrix(3) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> make_matrix() == make_matrix(4) True """ row_size = abs(row_size) or 4 return [[1 + x + y * row_size for x in range(row_size)] for y in range(row_size)] def rotate_90(matrix: [[]]) -> [[]]: """ >>> rotate_90(make_matrix()) [[4, 8, 12, 16], [3, 7, 11, 15], [2, 6, 10, 14], [1, 5, 9, 13]] >>> rotate_90(make_matrix()) == transpose(reverse_column(make_matrix())) True """ return reverse_row(transpose(matrix)) # OR.. transpose(reverse_column(matrix)) def rotate_180(matrix: [[]]) -> [[]]: """ >>> rotate_180(make_matrix()) [[16, 15, 14, 13], [12, 11, 10, 9], [8, 7, 6, 5], [4, 3, 2, 1]] >>> rotate_180(make_matrix()) == reverse_column(reverse_row(make_matrix())) True """ return reverse_row(reverse_column(matrix)) # OR.. reverse_column(reverse_row(matrix)) def rotate_270(matrix: [[]]) -> [[]]: """ >>> rotate_270(make_matrix()) [[13, 9, 5, 1], [14, 10, 6, 2], [15, 11, 7, 3], [16, 12, 8, 4]] >>> rotate_270(make_matrix()) == transpose(reverse_row(make_matrix())) True """ return reverse_column(transpose(matrix)) # OR.. transpose(reverse_row(matrix)) def transpose(matrix: [[]]) -> [[]]: matrix[:] = [list(x) for x in zip(*matrix)] return matrix def reverse_row(matrix: [[]]) -> [[]]: matrix[:] = matrix[::-1] return matrix def reverse_column(matrix: [[]]) -> [[]]: matrix[:] = [x[::-1] for x in matrix] return matrix def print_matrix(matrix: [[]]) -> [[]]: for i in matrix: print(*i) if __name__ == "__main__": matrix = make_matrix() print("\norigin:\n") print_matrix(matrix) print("\nrotate 90 counterclockwise:\n") print_matrix(rotate_90(matrix)) matrix = make_matrix() print("\norigin:\n") print_matrix(matrix) print("\nrotate 180:\n") print_matrix(rotate_180(matrix)) matrix = make_matrix() print("\norigin:\n") print_matrix(matrix) print("\nrotate 270 counterclockwise:\n") print_matrix(rotate_270(matrix))
[ "[[]]", "[[]]", "[[]]", "[[]]", "[[]]", "[[]]", "[[]]" ]
[ 723, 1054, 1396, 1725, 1832, 1923, 2025 ]
[ 727, 1058, 1400, 1729, 1836, 1927, 2029 ]
archives/1098994933_python.zip
matrix/searching_in_sorted_matrix.py
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] ] x = int(input("Enter the element to be searched:")) print(mat) search_in_a_sorted_matrix(mat, len(mat), len(mat[0]), x) if __name__ == '__main__': main()
[]
[]
[]
archives/1098994933_python.zip
matrix/sherman_morrison.py
class Matrix: """ <class Matrix> Matrix structure. """ def __init__(self, row: int, column: int, default_value: float = 0): """ <method Matrix.__init__> Initialize matrix with given size and default value. Example: >>> a = Matrix(2, 3, 1) >>> a Matrix consist of 2 rows and 3 columns [1, 1, 1] [1, 1, 1] """ self.row, self.column = row, column self.array = [[default_value for c in range(column)] for r in range(row)] def __str__(self): """ <method Matrix.__str__> Return string representation of this matrix. """ # Prefix s = "Matrix consist of %d rows and %d columns\n" % (self.row, self.column) # Make string identifier max_element_length = 0 for row_vector in self.array: for obj in row_vector: max_element_length = max(max_element_length, len(str(obj))) string_format_identifier = "%%%ds" % (max_element_length,) # Make string and return def single_line(row_vector): nonlocal string_format_identifier line = "[" line += ", ".join(string_format_identifier % (obj,) for obj in row_vector) line += "]" return line s += "\n".join(single_line(row_vector) for row_vector in self.array) return s def __repr__(self): return str(self) def validateIndices(self, loc: tuple): """ <method Matrix.validateIndices> Check if given indices are valid to pick element from matrix. Example: >>> a = Matrix(2, 6, 0) >>> a.validateIndices((2, 7)) False >>> a.validateIndices((0, 0)) True """ if not(isinstance(loc, (list, tuple)) and len(loc) == 2): return False elif not(0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False else: return True def __getitem__(self, loc: tuple): """ <method Matrix.__getitem__> Return array[row][column] where loc = (row, column). Example: >>> a = Matrix(3, 2, 7) >>> a[1, 0] 7 """ assert self.validateIndices(loc) return self.array[loc[0]][loc[1]] def __setitem__(self, loc: tuple, value: float): """ <method Matrix.__setitem__> Set array[row][column] = value where loc = (row, column). Example: >>> a = Matrix(2, 3, 1) >>> a[1, 2] = 51 >>> a Matrix consist of 2 rows and 3 columns [ 1, 1, 1] [ 1, 1, 51] """ assert self.validateIndices(loc) self.array[loc[0]][loc[1]] = value def __add__(self, another): """ <method Matrix.__add__> Return self + another. Example: >>> a = Matrix(2, 1, -4) >>> b = Matrix(2, 1, 3) >>> a+b Matrix consist of 2 rows and 1 columns [-1] [-1] """ # Validation assert isinstance(another, Matrix) assert self.row == another.row and self.column == another.column # Add result = Matrix(self.row, self.column) for r in range(self.row): for c in range(self.column): result[r,c] = self[r,c] + another[r,c] return result def __neg__(self): """ <method Matrix.__neg__> Return -self. Example: >>> a = Matrix(2, 2, 3) >>> a[0, 1] = a[1, 0] = -2 >>> -a Matrix consist of 2 rows and 2 columns [-3, 2] [ 2, -3] """ result = Matrix(self.row, self.column) for r in range(self.row): for c in range(self.column): result[r,c] = -self[r,c] return result def __sub__(self, another): return self + (-another) def __mul__(self, another): """ <method Matrix.__mul__> Return self * another. Example: >>> a = Matrix(2, 3, 1) >>> a[0,2] = a[1,2] = 3 >>> a * -2 Matrix consist of 2 rows and 3 columns [-2, -2, -6] [-2, -2, -6] """ if isinstance(another, (int, float)): # Scalar multiplication result = Matrix(self.row, self.column) for r in range(self.row): for c in range(self.column): result[r,c] = self[r,c] * another return result elif isinstance(another, Matrix): # Matrix multiplication assert(self.column == another.row) result = Matrix(self.row, another.column) for r in range(self.row): for c in range(another.column): for i in range(self.column): result[r,c] += self[r,i] * another[i,c] return result else: raise TypeError("Unsupported type given for another (%s)" % (type(another),)) def transpose(self): """ <method Matrix.transpose> Return self^T. Example: >>> a = Matrix(2, 3) >>> for r in range(2): ... for c in range(3): ... a[r,c] = r*c ... >>> a.transpose() Matrix consist of 3 rows and 2 columns [0, 0] [0, 1] [0, 2] """ result = Matrix(self.column, self.row) for r in range(self.row): for c in range(self.column): result[c,r] = self[r,c] return result def ShermanMorrison(self, u, v): """ <method Matrix.ShermanMorrison> Apply Sherman-Morrison formula in O(n^2). To learn this formula, please look this: https://en.wikipedia.org/wiki/Sherman%E2%80%93Morrison_formula This method returns (A + uv^T)^(-1) where A^(-1) is self. Returns None if it's impossible to calculate. Warning: This method doesn't check if self is invertible. Make sure self is invertible before execute this method. Example: >>> ainv = Matrix(3, 3, 0) >>> for i in range(3): ainv[i,i] = 1 ... >>> u = Matrix(3, 1, 0) >>> u[0,0], u[1,0], u[2,0] = 1, 2, -3 >>> v = Matrix(3, 1, 0) >>> v[0,0], v[1,0], v[2,0] = 4, -2, 5 >>> ainv.ShermanMorrison(u, v) Matrix consist of 3 rows and 3 columns [ 1.2857142857142856, -0.14285714285714285, 0.3571428571428571] [ 0.5714285714285714, 0.7142857142857143, 0.7142857142857142] [ -0.8571428571428571, 0.42857142857142855, -0.0714285714285714] """ # Size validation assert isinstance(u, Matrix) and isinstance(v, Matrix) assert self.row == self.column == u.row == v.row # u, v should be column vector assert u.column == v.column == 1 # u, v should be column vector # Calculate vT = v.transpose() numerator_factor = (vT * self * u)[0, 0] + 1 if numerator_factor == 0: return None # It's not invertable return self - ((self * u) * (vT * self) * (1.0 / numerator_factor)) # Testing if __name__ == "__main__": def test1(): # a^(-1) ainv = Matrix(3, 3, 0) for i in range(3): ainv[i,i] = 1 print("a^(-1) is %s" % (ainv,)) # u, v u = Matrix(3, 1, 0) u[0,0], u[1,0], u[2,0] = 1, 2, -3 v = Matrix(3, 1, 0) v[0,0], v[1,0], v[2,0] = 4, -2, 5 print("u is %s" % (u,)) print("v is %s" % (v,)) print("uv^T is %s" % (u * v.transpose())) # Sherman Morrison print("(a + uv^T)^(-1) is %s" % (ainv.ShermanMorrison(u, v),)) def test2(): import doctest doctest.testmod() test2()
[ "int", "int", "tuple", "tuple", "tuple", "float" ]
[ 100, 113, 1509, 2026, 2350, 2364 ]
[ 103, 116, 1514, 2031, 2355, 2369 ]
archives/1098994933_python.zip
matrix/spiral_print.py
""" This program print the matix in spiral form. This problem has been solved through recursive way. Matrix must satisfy below conditions i) matrix should be only one or two dimensional ii)column of all the row should be equal """ def checkMatrix(a): # must be if type(a) == list and len(a) > 0: if type(a[0]) == list: prevLen = 0 for i in a: if prevLen == 0: prevLen = len(i) result = True elif prevLen == len(i): result = True else: result = False else: result = True else: result = False return result def spiralPrint(a): if checkMatrix(a) and len(a) > 0: matRow = len(a) if type(a[0]) == list: matCol = len(a[0]) else: for dat in a: print(dat), return # horizotal printing increasing for i in range(0, matCol): print(a[0][i]), # vertical printing down for i in range(1, matRow): print(a[i][matCol - 1]), # horizotal printing decreasing if matRow > 1: for i in range(matCol - 2, -1, -1): print(a[matRow - 1][i]), # vertical printing up for i in range(matRow - 2, 0, -1): print(a[i][0]), remainMat = [row[1:matCol - 1] for row in a[1:matRow - 1]] if len(remainMat) > 0: spiralPrint(remainMat) else: return else: print("Not a valid matrix") return # driver code a = [[1 , 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12]] spiralPrint(a)
[]
[]
[]