| {"blob_id": "b7b944e5d5dd1cd1b41952c55bc13c348f905024", "repo_name": "Oyekunle-Mark/Graphs", "path": "/projects/ancestor/ancestor.py", "length_bytes": 1360, "score": 3.671875, "int_score": 4, "content": "from graph import Graph\nfrom util import Stack\n\n\ndef earliest_ancestor(ancestors, starting_node):\n # FIRST REPRESENT THE INPUT ANCESTORS AS A GRAPH\n # create a graph instance\n graph = Graph()\n\n # loop through ancestors and add every number as a vertex\n for parent, child in ancestors:\n # add the parent as a vertex\n graph.add_vertex(parent)\n # add the child as a vertex as well\n graph.add_vertex(child)\n\n # # loop through ancestors and build the connections\n for parent, child in ancestors:\n # connect the parent to the child\n # the connection is reversed because dft transverses downward\n graph.add_edge(child, parent)\n\n # if starting node has no child\n if not graph.vertices[starting_node]:\n # return -1\n return -1\n\n # create a stack to hold the vertices\n s = Stack()\n # add the starting_node to the stack\n s.push(starting_node)\n # set earliest_anc to -1\n earliest_anc = -1\n\n # loop while stack is not empty\n while s.size() > 0:\n # pop the stack\n vertex = s.pop()\n\n # set the earliest_anc to vertex\n earliest_anc = vertex\n\n # add all its connected vertices to the queue\n # sort the vertices maintain order\n for v in sorted(graph.vertices[vertex]):\n s.push(v)\n\n return earliest_anc\n"} | |
| {"blob_id": "150d0efefb3c712edc14a5ff039ef2082c43152b", "repo_name": "syurskyi/Python_Topics", "path": "/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/111_Minimum_Depth_of_Binary_Tree.py", "length_bytes": 1281, "score": 4.03125, "int_score": 4, "content": "# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nc_ Solution o..\n # def minDepth(self, root):\n # \"\"\"\n # :type root: TreeNode\n # :rtype: int\n # \"\"\"\n # # Recursion\n # if root is None:\n # return 0\n # ld = self.minDepth(root.left)\n # rd = self.minDepth(root.right)\n # if ld != 0 and rd != 0:\n # # handle 0 case!\n # return 1 + min(ld, rd)\n # return 1 + ld +rd\n\n ___ minDepth root\n # BFS\n __ root is N..:\n r_ 0\n queue = [root]\n depth, rightMost = 1, root\n w.. l.. queue) > 0:\n node = queue.pop(0)\n __ node.left is N.. a.. node.right is N..:\n ______\n __ node.left is n.. N..:\n queue.a.. node.left)\n __ node.right is n.. N..:\n queue.a.. node.right)\n __ node __ rightMost:\n # reach the current level end\n depth += 1\n __ node.right is n.. N..:\n rightMost = node.right\n ____\n rightMost = node.left\n r_ depth\n\n"} | |
| {"blob_id": "039dd3727cdd229548d94108ee220efa4a5b4838", "repo_name": "mertdemirlicakmak/project_euler", "path": "/problem_5.py", "length_bytes": 1144, "score": 4.0625, "int_score": 4, "content": "\"\"\"\"2520 is the smallest number that can be divided by each of the numbers\nfrom 1 to 10 without any remainder.\nWhat is the smallest positive number that is evenly\ndivisible by all of the numbers from 1 to 20?\"\"\"\n\n\n# This function returns the smallest number that is divisible to\n# 1 to num\ndef find_smallest_divisible(num):\n multi_list = []\n result_dict = {}\n result = 1\n multi_list.extend(range(2, num + 1))\n for num in multi_list:\n prime_list = find_prime_factors(num)\n for prime in prime_list:\n if not (prime in result_dict):\n result_dict[prime] = 0\n if result_dict[prime] < prime_list.count(prime):\n result_dict[prime] += 1\n result *= prime\n return result\n\n# This functions returns the prime factors of num\ndef find_prime_factors(num):\n temp = num\n result = []\n while temp > 1:\n for number in range(2, temp + 1):\n if temp % number == 0:\n result.append(number)\n temp //= number\n break\n return result\n\nif __name__ == '__main__':\n print(find_smallest_divisible(20))\n"} | |
| {"blob_id": "0437daed01bce0f5a3046616917a2c29a1ed15d0", "repo_name": "zhouyuhangnju/freshLeetcode", "path": "/Combination Sum.py", "length_bytes": 1252, "score": 3.71875, "int_score": 4, "content": "def combinationSum(candidates, target):\n \"\"\"\n :type candidates: List[int]\n :type target: int\n :rtype: List[List[int]]\n \"\"\"\n\n res = []\n\n candidates = sorted(candidates)\n\n def combinationRemain(remain, curr_res):\n\n if remain == 0:\n res.append(curr_res)\n return\n\n for c in candidates:\n if c > remain:\n break\n if curr_res and c < curr_res[-1]:\n continue\n combinationRemain(remain - c, curr_res + [c])\n\n combinationRemain(target, [])\n\n return res\n\n\ndef combinationSum2(candidates, target):\n \"\"\"\n :type candidates: List[int]\n :type target: int\n :rtype: List[List[int]]\n \"\"\"\n\n res = []\n\n candidates = sorted(candidates)\n\n def combinationRemain(remain, curr_res, curr_idx):\n\n if remain == 0:\n res.append(curr_res)\n return\n\n if remain < 0 or curr_idx >= len(candidates):\n return\n\n combinationRemain(remain-candidates[curr_idx], curr_res+[candidates[curr_idx]], curr_idx)\n combinationRemain(remain, curr_res, curr_idx + 1)\n\n combinationRemain(target, [], 0)\n\n return res\n\n\nif __name__ == '__main__':\n print combinationSum2([2, 3, 6, 7], 7)"} | |
| {"blob_id": "246130cc6d8d3b7c3fee372774aa2f93018f4e35", "repo_name": "alexleversen/AdventOfCode", "path": "/2020/08-2/main.py", "length_bytes": 1119, "score": 3.625, "int_score": 4, "content": "import re\n\nfile = open('input.txt', 'r')\nlines = list(file.readlines())\n\ndef testTermination(swapLine):\n if(lines[swapLine][0:3] == 'acc'):\n return False\n instructionIndex = 0\n instructionsVisited = []\n acc = 0\n\n while(True):\n if(instructionIndex == len(lines)):\n return acc\n if(instructionIndex in instructionsVisited):\n return False\n instructionsVisited.append(instructionIndex)\n match = re.match('(\\w{3}) ([+-]\\d+)', lines[instructionIndex])\n instruction, value = match.group(1, 2)\n if(instructionIndex == swapLine):\n if(instruction == 'jmp'):\n instruction = 'nop'\n elif(instruction == 'nop'):\n instruction = 'jmp'\n if(instruction == 'acc'):\n acc += int(value)\n instructionIndex += 1\n elif(instruction == 'jmp'):\n instructionIndex += int(value)\n else:\n instructionIndex += 1\n\nfor i in range(len(lines)):\n terminationValue = testTermination(i)\n if(terminationValue != False):\n print(terminationValue)\n"} | |
| {"blob_id": "f9af5624fe12b3c6bd0c359e5162b7f9f48234e7", "repo_name": "Yarin78/yal", "path": "/python/yal/fenwick.py", "length_bytes": 1025, "score": 3.765625, "int_score": 4, "content": "# Datastructure for storing and updating integer values in an array in log(n) time\n# and answering queries \"what is the sum of all value in the array between 0 and x?\" in log(n) time\n#\n# Also called Binary Indexed Tree (BIT). See http://codeforces.com/blog/entry/619\n\nclass FenwickTree:\n\n def __init__(self, exp):\n '''Creates a FenwickTree with range 0..(2^exp)-1'''\n self.exp = exp\n self.t = [0] * 2 ** (exp+1)\n\n def query_range(self, x, y):\n '''Gets the sum of the values in the range [x, y)'''\n return self.query(y) - self.query(x)\n\n def query(self, x, i=-1):\n '''Gets the sum of the values in the range [0, x).'''\n if i < 0:\n i = self.exp\n return (x&1) * self.t[(1<<i)+x-1] + self.query(x//2, i-1) if x else 0\n\n def insert(self, x, v, i=-1):\n '''Adds the value v to the position x'''\n if i < 0:\n i = self.exp\n self.t[(1<<i)+x] += v\n return self.t[(1<<i)+x] + (self.insert(x//2, v, i-1) if i > 0 else 0)\n"} | |
| {"blob_id": "25ce186e86fc56201f52b12615caa13f98044d99", "repo_name": "travisoneill/project-euler", "path": "/python/007.py", "length_bytes": 327, "score": 3.953125, "int_score": 4, "content": "from math import sqrt\n\ndef is_prime(n):\n if n < 2: return False\n for i in range(2, int(sqrt(n)) + 1):\n if n % i == 0:\n return False\n return True\n\ndef nth_prime(n):\n count = 2\n i = 3\n while count < n:\n i+=2\n if is_prime(i):\n count += 1\n print(i)\n\nnth_prime(10001)\n"} | |
| {"blob_id": "5bb4299f898d7a3957d4a0fd1ed4eb151ab44b47", "repo_name": "efeacer/EPFL_ML_Labs", "path": "/Lab04/template/least_squares.py", "length_bytes": 482, "score": 3.5625, "int_score": 4, "content": "# -*- coding: utf-8 -*-\n\"\"\"Exercise 3.\n\nLeast Square\n\"\"\"\n\nimport numpy as np\n\ndef compute_error_vector(y, tx, w):\n return y - tx.dot(w)\n \ndef compute_mse(error_vector):\n return np.mean(error_vector ** 2) / 2\n\ndef least_squares(y, tx):\n coefficient_matrix = tx.T.dot(tx)\n constant_vector = tx.T.dot(y)\n w = np.linalg.solve(coefficient_matrix, constant_vector)\n error_vector = compute_error_vector(y, tx, w)\n loss = compute_mse(error_vector)\n return w, loss"} | |
| {"blob_id": "0a186e9f92527a8509f7082f2f4065d3b366e957", "repo_name": "vinnyatanasov/naive-bayes-classifier", "path": "/nb.py", "length_bytes": 3403, "score": 3.6875, "int_score": 4, "content": "\"\"\"\nNaive Bayes classifier\n\n- gets reviews as input\n- counts how many times words appear in pos/neg\n- adds one to each (to not have 0 probabilities)\n- computes likelihood and multiply by prior (of review being pos/neg) to get the posterior probability\n- in a balanced dataset, prior is the same for both, so we ignore it here\n- chooses highest probability to be prediction\n\"\"\"\n\nimport math\n\n\ndef test(words, probs, priors, file_name):\n label = 1 if \"pos\" in file_name else -1\n count = 0\n correct = 0\n with open(file_name) as file:\n for line in file:\n # begin with prior (simply how likely it is to be pos/neg before evidence)\n pos = priors[0]\n neg = priors[1]\n # compute likelihood\n # sum logs, better than multiplying very small numbers\n for w in line.strip().split():\n # if word wasn't in train data, then we have to ignore it\n # same effect if we add test words into corpus and gave small probability\n if w in words:\n pos += math.log(probs[w][0])\n neg += math.log(probs[w][1])\n \n # say it's positive if pos >= neg\n pred = 1 if pos >= neg else -1\n \n # increment counters\n count += 1\n if pred == label:\n correct += 1\n \n # return results\n return 100*(correct/float(count))\n\n\ndef main():\n # count number of occurances of each word in pos/neg reviews\n # we'll use a dict containing a two item list [pos count, neg count]\n words = {}\n w_count = 0 # words\n p_count = 0 # positive instances\n n_count = 0 # negative instances\n \n # count positive occurrences\n with open(\"data/train.positive\") as file:\n for line in file:\n for word in line.strip().split():\n try:\n words[word][0] += 1\n except:\n words[word] = [1, 0]\n w_count += 1\n p_count += 1\n \n # count negative occurrences\n with open(\"data/train.negative\") as file:\n for line in file:\n for word in line.strip().split():\n try:\n words[word][1] += 1\n except:\n words[word] = [0, 1]\n w_count += 1\n n_count += 1\n \n # calculate probabilities of each word\n corpus = len(words)\n probs = {}\n for key, value in words.iteritems():\n # smooth values (add one to each)\n value[0]+=1\n value[1]+=1\n # prob = count / total count + number of words (for smoothing)\n p_pos = value[0] / float(w_count + corpus)\n p_neg = value[1] / float(w_count + corpus)\n probs[key] = [p_pos, p_neg]\n \n # compute priors based on frequency of reviews\n priors = []\n priors.append(math.log(p_count / float(p_count + n_count)))\n priors.append(math.log(n_count / float(p_count + n_count)))\n \n # test naive bayes\n pos_result = test(words, probs, priors, \"data/test.positive\")\n neg_result = test(words, probs, priors, \"data/test.negative\")\n \n print \"Accuracy(%)\"\n print \"Positive:\", pos_result\n print \"Negative:\", neg_result\n print \"Combined:\", (pos_result+neg_result)/float(2)\n\n\nif __name__ == \"__main__\":\n print \"-- Naive Bayes classifier --\\n\"\n \n main()\n "} | |
| {"blob_id": "ceca83f8d1a6d0dbc027ad04a7632bb8853bc17f", "repo_name": "harshablast/numpy_NN", "path": "/nn.py", "length_bytes": 2183, "score": 3.734375, "int_score": 4, "content": "import numpy as np\n\n\ndef sigmoid(x):\n return 1 / (1 + np.exp(-x))\n\n\ndef d_sigmoid(x):\n return x * (1 - x)\n\n\ndef relu(x):\n return x * (x > 0)\n\n\ndef d_relu(x):\n return 1 * (x > 0)\n\n\nclass neural_network:\n\n def __init__(self, nodes):\n self.input_dim = nodes[0]\n self.HL01_dim = nodes[1]\n self.HL02_dim = nodes[2]\n self.output_dim = nodes[3]\n\n self.W1 = 2 * (np.random.rand(self.input_dim, self.HL01_dim) -1)\n self.W2 = 2 * (np.random.rand(self.HL01_dim, self.HL02_dim) -1)\n self.W3 = 2 * (np.random.rand(self.HL02_dim, self.output_dim) -1)\n\n self.B1 = 2 * (np.random.rand(1, self.HL01_dim))\n self.B2 = 2 * (np.random.rand(1, self.HL02_dim))\n self.B3 = 2 * (np.random.rand(1, self.output_dim))\n\n def forward_pass(self, input):\n self.HL01_out = sigmoid(np.add(np.matmul(input, self.W1), self.B1))\n self.HL02_out = sigmoid(np.add(np.matmul(self.HL01_out, self.W2), self.B2))\n self.output = sigmoid(np.add(np.matmul(self.HL02_out, self.W3), self.B3))\n\n return self.output\n\n def backward_pass(self, train_data_X, train_data_Y, iterations, learning_rate):\n for j in range(iterations):\n self.forward_pass(train_data_X)\n\n error = np.sum(np.square(self.output - train_data_Y))\n print(error)\n\n output_error = self.output - train_data_Y\n output_deltas = output_error * d_sigmoid(self.output)\n\n self.W3 -= np.dot(self.HL02_out.T, output_deltas) * learning_rate\n self.B3 -= np.sum(output_deltas, axis=0, keepdims=True) * learning_rate\n\n HL02_error = np.dot(output_deltas, self.W3.T)\n HL02_deltas = HL02_error * d_sigmoid(self.HL02_out)\n\n self.W2 -= np.dot(self.HL01_out.T, HL02_deltas) * learning_rate\n self.B2 -= np.sum(HL02_deltas, axis=0, keepdims=True) * learning_rate\n\n HL01_error = np.dot(HL02_deltas, self.W2.T)\n HL01_deltas = HL01_error * d_sigmoid(self.HL01_out)\n\n self.W1 -= np.dot(train_data_X.T, HL01_deltas) * learning_rate\n self.B1 -= np.sum(HL01_deltas, axis=0, keepdims=True) * learning_rate\n"} | |
| {"blob_id": "235fee728f7853aa65b05a101deeb1dfeb5ebf8f", "repo_name": "syurskyi/Python_Topics", "path": "/125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/DynamicProgramming/198_HouseRobber.py", "length_bytes": 469, "score": 3.609375, "int_score": 4, "content": "#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\nclass Solution(object):\n # Dynamic Programming\n def rob(self, nums):\n if not nums:\n return 0\n pre_rob = 0\n pre_not_rob = 0\n for num in nums:\n cur_rob = pre_not_rob + num\n cur_not_rob = max(pre_rob, pre_not_rob)\n pre_rob = cur_rob\n pre_not_rob = cur_not_rob\n return max(pre_rob, pre_not_rob)\n\n\"\"\"\n[]\n[1,2]\n[12, 1,1,12,1]\n\"\"\"\n"} | |
| {"blob_id": "0d0892bf443e39c3c5ef078f2cb846370b7852e9", "repo_name": "JakobLybarger/Graph-Pathfinding-Algorithms", "path": "/dijkstras.py", "length_bytes": 1297, "score": 4.15625, "int_score": 4, "content": "import math\nimport heapq\n\n\ndef dijkstras(graph, start):\n distances = {} # Dictionary to keep track of the shortest distance to each vertex in the graph\n\n # The distance to each vertex is not known so we will just assume each vertex is infinitely far away\n for vertex in graph:\n distances[vertex] = math.inf\n\n distances[start] = 0 # Distance from the first point to the first point is 0\n vertices_to_explore = [(0, start)]\n\n # Continue while heap is not empty\n while vertices_to_explore:\n distance, vertex = heapq.heappop(vertices_to_explore) # Pop the minimum distance vertex off of the heap\n\n for neighbor, e_weight in graph[vertex]:\n new_distance = distance + e_weight\n\n # If the new distance is less than the current distance set the current distance as new distance\n if new_distance < distances[neighbor]:\n distances[neighbor] = new_distance\n heapq.heappush(vertices_to_explore, (new_distance, neighbor))\n\n return distances # The dictionary of minimum distances from start to each vertex\n\n\ngraph = {\n 'A': [('B', 10), ('C', 3)],\n 'C': [('D', 2)],\n 'D': [('E', 10)],\n 'E': [('A', 7)],\n 'B': [('C', 3), ('D', 2)]\n }\n\nprint(dijkstras(graph, \"A\"))"} | |
| {"blob_id": "c3626ea1efb1c930337e261be165d048d842d15a", "repo_name": "Razorro/Leetcode", "path": "/72. Edit Distance.py", "length_bytes": 3999, "score": 3.515625, "int_score": 4, "content": "\"\"\"\nGiven two words word1 and word2, find the minimum number of operations required to convert word1 to word2.\n\nYou have the following 3 operations permitted on a word:\n\nInsert a character\nDelete a character\nReplace a character\nExample 1:\n\nInput: word1 = \"horse\", word2 = \"ros\"\nOutput: 3\nExplanation:\nhorse -> rorse (replace 'h' with 'r')\nrorse -> rose (remove 'r')\nrose -> ros (remove 'e')\nExample 2:\n\nInput: word1 = \"intention\", word2 = \"execution\"\nOutput: 5\nExplanation:\nintention -> inention (remove 't')\ninention -> enention (replace 'i' with 'e')\nenention -> exention (replace 'n' with 'x')\nexention -> exection (replace 'n' with 'c')\nexection -> execution (insert 'u')\n\nA good question! I thought it was similiar with the dynamic programming example in CLRS,\nit turns out the skeleton may has a little similiarity, but the core idea can't be extracted\nwith the situation of this question.\n\nIt was called Levenshtein distance.\nMathematically, the Levenshtein distance between two strings {\\displaystyle a,b} a,b (of length {\\displaystyle |a|} |a| and {\\displaystyle |b|} |b| respectively) is given by {\\displaystyle \\operatorname\n{lev} _{a,b}(|a|,|b|)} \\operatorname{lev}_{a,b}(|a|,|b|) where\n | --- max(i, j) if min(i, j) = 0\nlev(i, j) = | min --- lev(i-1, j) + 1\n | --- lev(i, j-1) + 1\n | --- lev(i-1, j-1) + 1\n\n\nComputing the Levenshtein distance is based on the observation that if we reserve a matrix to hold the Levenshtein distances\nbetween all prefixes of the first string and all prefixes of the second, then we can compute the values in the matrix in\na dynamic programming fashion, and thus find the distance between the two full strings as the last value computed.\n\nThis algorithm, an example of bottom-up dynamic programming, is discussed, with variants, in the 1974 article The\nString-to-string correction problem by Robert A. Wagner and Michael J. Fischer.[4]\n\"\"\"\n\n\nclass Solution:\n def minDistance(self, word1: 'str', word2: 'str') -> 'int':\n points = self.findBiggestCommon(word1, word2)\n\n def findBiggestCommon(self, source, target):\n path = [0] * len(source)\n directions = []\n for i in range(len(target)):\n current = [0] * len(source)\n d = []\n for j in range(len(source)):\n if target[i] == source[j]:\n current[j] = path[j-1] + 1 if j-1 >= 0 else 1\n d.append('=')\n else:\n left = current[j-1] if j-1 >= 0 else 0\n if left > path[j]:\n d.append('l')\n else:\n d.append('u')\n current[j] = max(left, path[j])\n path = current\n directions.append(d)\n\n x_y = []\n row, col = len(target)-1, len(source)-1\n while row >= 0 and col >=0:\n if directions[row][col] == '=':\n x_y.append((row, col))\n row -= 1\n col -= 1\n elif directions[row][col] == 'u':\n row -= 1\n else:\n col -= 1\n return x_y\n\n def standardAnswer(self, word1, word2):\n m = len(word1) + 1\n n = len(word2) + 1\n det = [[0 for _ in range(n)] for _ in range(m)]\n for i in range(m):\n det[i][0] = i\n for i in range(n):\n det[0][i] = i\n for i in range(1, m):\n for j in range(1, n):\n det[i][j] = min(det[i][j - 1] + 1, det[i - 1][j] + 1, det[i - 1][j - 1] +\n 0 if word1[i - 1] == word2[j - 1] else 1)\n return det[m - 1][n - 1]\n\n\nif __name__ == '__main__':\n s = Solution()\n distance = s.findBiggestCommon('horse', 'ros')\n distance = sorted(distance, key=lambda e: e[1])\n c = 0\n trans = 0\n for left, right in distance:\n trans += abs(right - left) + left-c\n c = left + 1\n print(s.findBiggestCommon('horse', 'ros'))"} | |
| {"blob_id": "b3a6e632568dd13f128eda2cba96293e2bd0d3cd", "repo_name": "sniperswang/dev", "path": "/leetcode/L265/test.py", "length_bytes": 1452, "score": 3.640625, "int_score": 4, "content": "\"\"\"\nThere are a row of n houses, each house can be painted with one of the k colors. \nThe cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color.\n\nThe cost of painting each house with a certain color is represented by a n x k cost matrix. \nFor example, costs[0][0] is the cost of painting house 0 with color 0; costs[1][2] is the cost of painting house 1 with color 2, and so on... Find the minimum cost to paint all houses.\n\nNote:\nAll costs are positive integers.\n\nFollow up:\nCould you solve it in O(nk) runtime?\n\n\"\"\"\n\nclass Solution(object):\n def minCostII(self, costs):\n \"\"\"\n :type costs: List[List[int]]\n :rtype: int\n \"\"\"\n if len(costs) == 0:\n return 0\n\n m = len(costs)\n n = len(costs[0])\n\n for i in range (1, m):\n preMin = {}\n preMin[0] = min(costs[i-1][1:])\n costs[i][0] = costs[i][0] + preMin[0] \n\n if ( n > 1):\n preMin[n-1] = min(costs[i-1][:n-1])\n costs[i][n-1] = costs[i][n-1] + preMin[n-1] \n\n for j in range (1, n-1):\n preMin[j] = min( min(costs[i-1][:j]), min(costs[i-1][j+1:]) )\n costs[i][j] = costs[i][j] + preMin[j] \n\n\n return min(costs[len(costs)-1])\n\ncosta = [1,2,4]\ncostb = [3,1,0]\ncostc = [1,2,1]\n\ncosts = []\ncosts.append(costa)\ncosts.append(costb)\ncosts.append(costc)\n\n\ns = Solution()\n\nprint s.minCostII(costs)\n\n\n\n"} | |
| {"blob_id": "a1b41adcda2d3b3522744e954cf8ae2f901c6b01", "repo_name": "drunkwater/leetcode", "path": "/medium/python3/c0099_209_minimum-size-subarray-sum/00_leetcode_0099.py", "length_bytes": 798, "score": 3.546875, "int_score": 4, "content": "# DRUNKWATER TEMPLATE(add description and prototypes)\n# Question Title and Description on leetcode.com\n# Function Declaration and Function Prototypes on leetcode.com\n#209. Minimum Size Subarray Sum\n#Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum \u2265 s. If there isn't one, return 0 instead.\n#For example, given the array [2,3,1,2,4,3] and s = 7,\n#the subarray [4,3] has the minimal length under the problem constraint.\n#click to show more practice.\n#Credits:\n#Special thanks to @Freezen for adding this problem and creating all test cases.\n#class Solution:\n# def minSubArrayLen(self, s, nums):\n# \"\"\"\n# :type s: int\n# :type nums: List[int]\n# :rtype: int\n# \"\"\"\n\n\n\n# Time Is Money"} | |
| {"blob_id": "40a908c9b3cf99674e66b75f56809d485f0a81f9", "repo_name": "Gborgman05/algs", "path": "/py/populate_right_pointers.py", "length_bytes": 1019, "score": 3.859375, "int_score": 4, "content": "\"\"\"\n# Definition for a Node.\nclass Node:\n def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):\n self.val = val\n self.left = left\n self.right = right\n self.next = next\n\"\"\"\n\nclass Solution:\n def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':\n saved = root\n levels = []\n l = [root]\n n = []\n while l:\n n = []\n for node in l:\n if node:\n if node.left:\n n.append(node.left)\n if node.right:\n n.append(node.right)\n levels.append(l)\n l = n\n for level in levels:\n for i in range(len(level)):\n if level[i] == None:\n continue\n if i < len(level) - 1:\n level[i].next = level[i+1]\n else:\n level[i].next = None\n return root\n "} | |
| {"blob_id": "c2f622f51bbddc54b0199c4e0e2982bc2ebfa030", "repo_name": "qdm12/courses", "path": "/Fundamental Algorithms/Lesson-03/algorithms.py", "length_bytes": 2479, "score": 3.875, "int_score": 4, "content": "from operator import itemgetter\nfrom math import floor\n \ndef radix_sort_alpha(words):\n l = len(words[0])\n for w in words:\n if len(w) != l:\n raise Exception(\"All words should be of same length\")\n for i in range(l, 0, -1):\n words = sorted(words, key=itemgetter(i - 1))\n words_str = str([''.join(w) for w in words])\n print \"PASS \"+str(l - i + 1)+\": \"+words_str\n return words_str\n \ndef bucket_sort(A):\n print \"Initial input array A: \"+str(A)\n n = len(A)\n for i in range(n):\n assert(A[i] >= 0 and A[i] < 1)\n B = [[] for _ in range(n)]\n print \"Initial output buckets array B: \"+str(B)\n for i in range(n):\n place = int(floor(A[i] * n))\n B[place].append(A[i])\n print \"Output buckets array B with elements in buckets: \"+str(B)\n for j in range(n):\n B[j].sort()\n print \"Output buckets array B with elements sorted in buckets: \"+str(B)\n B_final = []\n for bucket in B:\n B_final += bucket\n print \"Final output array B: \"+str(B_final)\n return B_final\n \nclass MergeSort(object):\n def merge(self, A, l, q, r):\n n1 = q - l + 1\n n2 = r - q\n L = [A[l + i] for i in range(n1)]\n R = [A[q + 1 + i] for i in range(n2)]\n i = j = 0 # Initial index of first and second subarrays\n k = l # Initial index of merged subarray\n while i < n1 and j < n2:\n if L[i] <= R[j]:\n A[k] = L[i]\n i += 1\n else:\n A[k] = R[j]\n j += 1\n k += 1\n # Copy the remaining elements of L[], if there are any\n while i < n1:\n A[k] = L[i]\n i += 1\n k += 1\n # Copy the remaining elements of R[], if there are any\n while j < n2:\n A[k] = R[j]\n j += 1\n k += 1\n\n def mergeSort(self, A, l, r):\n if l < r:\n q = int(floor((l+r)/2))\n self.mergeSort(A, l, q)\n self.mergeSort(A, q+1, r)\n self.merge(A, l, q, r)\n \n def run(self):\n A = [54,26,93,17,77,31,44,55,20]\n self.mergeSort(A, 0, len(A) - 1)\n print A\n\n \nif __name__ == \"__main__\":\n radix_sort_alpha([\"COW\", \"DOG\", \"SEA\", \"RUG\", \"ROW\", \"MOB\", \"BOX\", \"TAB\", \"BAR\", \"EAR\", \"TAR\", \"DIG\", \"BIG\", \"TEA\", \"NOW\", \"FOX\"])\n bucket_sort([.79,.13,.16,.64,.39,.20,.89,.53,.71,.43])\n m = MergeSort()\n m.run()"} | |
| {"blob_id": "baa6b0b8905dfc9e832125196f3503f271557273", "repo_name": "syurskyi/Python_Topics", "path": "/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/Array/SlidingWindowMaximum.py", "length_bytes": 2656, "score": 4.03125, "int_score": 4, "content": "\"\"\"\nGiven an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window.\n\nExample:\n\nInput: nums = [1,3,-1,-3,5,3,6,7], and k = 3\nOutput: [3,3,5,5,6,7] \nExplanation: \n\nWindow position Max\n--------------- -----\n[1 3 -1] -3 5 3 6 7 3\n 1 [3 -1 -3] 5 3 6 7 3\n 1 3 [-1 -3 5] 3 6 7 5\n 1 3 -1 [-3 5 3] 6 7 5\n 1 3 -1 -3 [5 3 6] 7 6\n 1 3 -1 -3 5 [3 6 7] 7\nNote: \nYou may assume k is always valid, 1 \u2264 k \u2264 input array's size for non-empty array.\n\nFollow up:\nCould you solve it in linear time?\n\n\u8fd9\u4e2a\u6211\u7684\u601d\u8def\u662f\uff1a\n\n1. \u5148\u628a\u524d k \u4e2a\u6570\u53d6\u51fa\u6765\uff0c\u7136\u540e\u6392\u5e8f\u4e00\u7ec4\uff0c\u4e0d\u6392\u5e8f\u4e00\u7ec4\u3002\n2. \u6392\u5e8f\u7684\u4e00\u7ec4\u4f5c\u4e3a\u67e5\u627e\u4f7f\u7528\u3002 \u4e0d\u6392\u5e8f\u7684\u4e00\u7ec4\u4f5c\u4e3a\u5220\u9664\u589e\u52a0\u4f1a\u7528\u3002\n3. \u8fd9\u91cc\u4e5f\u53ef\u4ee5\u4f7f\u7528\u5806\u4ee3\u66ff\u6392\u5e8f\uff0c\u7ea2\u9ed1\u6811\u5e94\u8be5\u6700\u597d\u4e0d\u8fc7\u4e86\u3002\n4. \u8fd9\u91cc\u4f7f\u7528\u6392\u5e8f\u8fc7\u7684\u5217\u8868\u662f\u4e3a\u4e86\u80fd\u591f\u4f7f\u7528\u4e8c\u5206\u6cd5\uff0c\u4ece\u800c\u8fbe\u5230 log n \u7ea7\u522b\u7684\u67e5\u627e\u548c\u540e\u7eed\u6dfb\u52a0\u3002\n \u4f46\u540c\u65f6\u56e0\u4e3a\u5373\u4f7f\u5728 log n\u7ea7\u522b\u67e5\u627e\u5230\u8981\u6dfb\u52a0\u5220\u9664\u7684\u4f4d\u7f6e\uff0c\u8fdb\u884c\u5217\u8868\u7684\u6dfb\u52a0\u548c\u5220\u9664\u4ecd\u7136\u662f\u4e00\u4e2a O(n) \u7ea7\u522b\u7684\u4e8b\u60c5...\n \u6240\u4ee5\u4f7f\u7528\u5806\u6216\u8005\u7ea2\u9ed1\u6811\u662f\u6700\u597d\u7684\uff0c\u6dfb\u52a0\u548c\u5220\u9664\u90fd\u662f log n \u7ea7\u522b\u7684\u3002\n\n5. sorted list \u4e3b\u8981\u662f\u8fdb\u884c\u83b7\u53d6\u6700\u5927\u4e0e\u5220\u9664\u5197\u4f59\uff0c\u8fd9\u91cc\u4f7f\u7528\u4e8c\u5206\u6cd5\u6765\u5220\u9664\u5197\u4f59\u3002\n6. unsorted list \u7528\u4e8e\u77e5\u9053\u8981\u5220\u9664\u548c\u6dfb\u52a0\u7684\u90fd\u662f\u54ea\u4e00\u4e2a\u3002\n\nbeat 31% 176ms.\n\n\u6d4b\u8bd5\u5730\u5740\uff1a\nhttps://leetcode.com/problems/sliding-window-maximum/description/\n\n\n\"\"\"\nfrom collections import deque\nimport bisect\n\nc.. Solution o..\n ___ find_bi nums, target\n lo = 0\n hi = l..(nums)\n \n _____ lo < hi:\n mid = (lo + hi) // 2\n \n __ nums[mid] __ target:\n r_ mid\n \n __ nums[mid] < target:\n lo = mid + 1\n ____\n hi = mid \n \n ___ maxSlidingWindow nums, k\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: List[int]\n \"\"\"\n __ n.. nums:\n r_ []\n \n x = nums[:k]\n y = s..(x)\n x = deque(x)\n \n maxes = m..(x)\n result = [maxes]\n \n ___ i __ nums[k:]:\n pop = x.popleft()\n x.a.. i)\n \n index = self.find_bi(y, pop)\n y.pop(index)\n \n bisect.insort_left(y, i)\n \n result.a.. y[-1])\n r_ result\n "} | |
| {"blob_id": "8496596aefa39873f8321a61d361bf209e54dcbd", "repo_name": "syurskyi/Python_Topics", "path": "/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/108_Convert_Sorted_Array_to_Binary_Search_Tree.py", "length_bytes": 977, "score": 3.859375, "int_score": 4, "content": "# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nc_ Solution o..\n # def sortedArrayToBST(self, nums):\n # \"\"\"\n # :type nums: List[int]\n # :rtype: TreeNode\n # \"\"\"\n # # Recursion with slicing\n # if not nums:\n # return None\n # mid = len(nums) / 2\n # root = TreeNode(nums[mid])\n # root.left = self.sortedArrayToBST(nums[:mid])\n # root.right = self.sortedArrayToBST(nums[mid + 1:])\n # return root\n\n ___ sortedArrayToBST nums\n # Recursion with index\n r_ getHelper(nums, 0, l.. nums) - 1)\n\n ___ getHelper nums, start, end\n __ start > end:\n r_ N..\n mid = (start + end) / 2\n node = TreeNode(nums[mid])\n node.left = getHelper(nums, start, mid - 1)\n node.right = getHelper(nums, mid + 1, end)\n r_ node"} | |
| {"blob_id": "0be537def5f8cc9ba9218267bf774b28ee44d4c7", "repo_name": "SoumyaMalgonde/AlgoBook", "path": "/python/graph_algorithms/Dijkstra's_Shortest_Path_Implementation_using_Adjacency_List.py", "length_bytes": 2933, "score": 3.921875, "int_score": 4, "content": "class Node_Distance :\n\n def __init__(self, name, dist) :\n self.name = name\n self.dist = dist\n\nclass Graph :\n\n def __init__(self, node_count) :\n self.adjlist = {}\n self.node_count = node_count\n\n def Add_Into_Adjlist(self, src, node_dist) :\n if src not in self.adjlist :\n self.adjlist[src] = []\n self.adjlist[src].append(node_dist)\n\n def Dijkstras_Shortest_Path(self, source) :\n\n # Initialize the distance of all the nodes from source to infinity\n distance = [999999999999] * self.node_count\n # Distance of source node to itself is 0\n distance[source] = 0\n\n # Create a dictionary of { node, distance_from_source }\n dict_node_length = {source: 0}\n\n while dict_node_length :\n\n # Get the key for the smallest value in the dictionary\n # i.e Get the node with the shortest distance from the source\n source_node = min(dict_node_length, key = lambda k: dict_node_length[k])\n del dict_node_length[source_node]\n\n for node_dist in self.adjlist[source_node] :\n adjnode = node_dist.name\n length_to_adjnode = node_dist.dist\n\n # Edge relaxation\n if distance[adjnode] > distance[source_node] + length_to_adjnode :\n distance[adjnode] = distance[source_node] + length_to_adjnode\n dict_node_length[adjnode] = distance[adjnode]\n\n for i in range(self.node_count) :\n print(\"Source Node (\"+str(source)+\") -> Destination Node(\" + str(i) + \") : \" + str(distance[i]))\n\ndef main() :\n\n g = Graph(6)\n\n # Node 0: <1,5> <2,1> <3,4>\n g.Add_Into_Adjlist(0, Node_Distance(1, 5))\n g.Add_Into_Adjlist(0, Node_Distance(2, 1))\n g.Add_Into_Adjlist(0, Node_Distance(3, 4))\n\n # Node 1: <0,5> <2,3> <4,8> \n g.Add_Into_Adjlist(1, Node_Distance(0, 5))\n g.Add_Into_Adjlist(1, Node_Distance(2, 3))\n g.Add_Into_Adjlist(1, Node_Distance(4, 8))\n\n # Node 2: <0,1> <1,3> <3,2> <4,1>\n g.Add_Into_Adjlist(2, Node_Distance(0, 1))\n g.Add_Into_Adjlist(2, Node_Distance(1, 3))\n g.Add_Into_Adjlist(2, Node_Distance(3, 2))\n g.Add_Into_Adjlist(2, Node_Distance(4, 1))\n\n # Node 3: <0,4> <2,2> <4,2> <5,1>\n g.Add_Into_Adjlist(3, Node_Distance(0, 4))\n g.Add_Into_Adjlist(3, Node_Distance(2, 2))\n g.Add_Into_Adjlist(3, Node_Distance(4, 2))\n g.Add_Into_Adjlist(3, Node_Distance(5, 1))\n\n # Node 4: <1,8> <2,1> <3,2> <5,3>\n g.Add_Into_Adjlist(4, Node_Distance(1, 8))\n g.Add_Into_Adjlist(4, Node_Distance(2, 1))\n g.Add_Into_Adjlist(4, Node_Distance(3, 2))\n g.Add_Into_Adjlist(4, Node_Distance(5, 3))\n\n # Node 5: <3,1> <4,3> \n g.Add_Into_Adjlist(5, Node_Distance(3, 1))\n g.Add_Into_Adjlist(5, Node_Distance(4, 3))\n\n g.Dijkstras_Shortest_Path(0)\n print(\"\\n\")\n g.Dijkstras_Shortest_Path(5)\n\nif __name__ == \"__main__\" :\n main()"} | |
| {"blob_id": "8130b1edf4df29a9ab76784289a22d5fb90863e7", "repo_name": "ridhishguhan/faceattractivenesslearner", "path": "/Classify.py", "length_bytes": 1158, "score": 3.6875, "int_score": 4, "content": "import numpy as np\nimport Utils\n\nclass Classifier:\n training = None\n train_arr = None\n classes = None\n\n def __init__(self, training, train_arr, CLASSES = 3):\n self.training = training\n self.train_arr = train_arr\n self.classes = CLASSES\n\n #KNN Classification method\n def OneNNClassify(self, test_set, K):\n # KNN Method\n # for each test sample t\n # for each training sample tr\n # compute norm |t - tr|\n # choose top norm\n # class which it belongs to is classification\n [tr,tc] = test_set.shape\n [trr,trc] = self.train_arr.shape\n result = np.array(np.zeros([tc]))\n i = 0\n #print \"KNN : with K = \",K\n while i < tc:\n x = test_set[:,i]\n xmat = np.tile(x,(1,trc))\n xmat = xmat - self.train_arr\n norms = Utils.ComputeNorm(xmat)\n closest_train = np.argmin(norms)\n which_train = self.training[closest_train]\n attr = which_train.attractiveness\n result[i] = attr\n #print \"Class : \",result[i]\n i += 1\n return result"} | |
| {"blob_id": "fa0a2e8e0ec8251c6d735b02dfa1d7a94e09c6b2", "repo_name": "paul0920/leetcode", "path": "/question_leetcode/1488_2.py", "length_bytes": 1538, "score": 3.984375, "int_score": 4, "content": "import collections\nimport heapq\n\nrains = [1, 2, 0, 0, 2, 1]\n\n# 0 1 2 3 4 5\nrains = [10, 20, 20, 0, 20, 10]\n\n\n# min heap to track the days when flooding would happen (if lake not dried)\nnearest = []\n\n# dict to store all rainy days\n# use case: to push the subsequent rainy days into the heap for wet lakes\nlocs = collections.defaultdict(collections.deque)\n\n# result - assume all days are rainy\nres = [-1] * len(rains)\n\n# pre-processing - {K: lake, V: list of rainy days}\nfor i, lake in enumerate(rains):\n locs[lake].append(i)\n\nfor i, lake in enumerate(rains):\n\n print \"nearest wet day:\", nearest\n # check whether the day, i, is a flooded day\n # the nearest lake got flooded (termination case)\n if nearest and nearest[0] == i:\n print []\n exit()\n\n # lake got wet\n if lake != 0:\n\n # pop the wet day. time complexity: O(1)\n locs[lake].popleft()\n\n # prioritize the next rainy day of this lake\n if locs[lake]:\n nxt = locs[lake][0]\n heapq.heappush(nearest, nxt)\n print \"nearest wet day:\", nearest\n\n # a dry day\n else:\n\n # no wet lake, append an arbitrary value\n if not nearest:\n res[i] = 1\n\n else:\n\n # dry the lake that has the highest priority\n # since that lake will be flooded in nearest future otherwise (greedy property)\n next_wet_day = heapq.heappop(nearest)\n wet_lake = rains[next_wet_day]\n res[i] = wet_lake\n\n print \"\"\n\nprint res\n"} | |
| {"blob_id": "ef0440b8ce5c5303d75b1d297e323a1d8b92d619", "repo_name": "AndreiBoris/sample-problems", "path": "/python/0200-numbers-of-islands/number-of-islands.py", "length_bytes": 5325, "score": 3.84375, "int_score": 4, "content": "from typing import List\n\nLAND = '1'\nWATER = '0'\n\n# TODO: Review a superior solutions\n\ndef overlaps(min1, max1, min2, max2):\n overlap = max(0, min(max1, max2) - max(min1, min2))\n if overlap > 0:\n return True\n if min1 == min2 or min1 == max2 or max1 == min2 or max1 == max2:\n return True\n if (min1 > min2 and max1 < max2) or (min2 > min1 and max2 < max1):\n return True\n return False\n\nprint(overlaps(0, 2, 1, 1))\n\n# Definition for a Bucket.\nclass Bucket:\n def __init__(self, identifiers: List[int]):\n self.destination = None\n self.identifiers = set(identifiers)\n \n def hasDestination(self) -> bool:\n return self.destination != None\n\n def getDestination(self):\n if not self.hasDestination():\n return self\n return self.destination.getDestination()\n\n def combine(self, bucket):\n otherDestination = bucket.getDestination()\n thisDestination = self.getDestination()\n uniqueIdentifiers = otherDestination.identifiers | thisDestination.identifiers\n newBucket = Bucket(uniqueIdentifiers)\n otherDestination.destination = newBucket\n thisDestination.destination = newBucket\n\n return newBucket\n\n def contains(self, identifier: int) -> bool:\n return identifier in self.getDestination().identifiers\n\nclass Solution:\n '''\n Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. \n An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. \n You may assume all four edges of the grid are all surrounded by water.\n\n \n '''\n def numIslands(self, grid: List[List[str]]) -> int:\n if len(grid) < 1:\n return 0\n \n nextRowIsland = 1\n rowIslands = {}\n currentRowIslandStart = None\n '''\n Here we are generating row islands that we will then be pairing with adjacent row islands to form\n groups that we will then combine into the true islands that are needed to get the correct answer\n '''\n for rowIndex, row in enumerate(grid):\n lastSpot = WATER\n lengthOfRow = len(row)\n rowIslands[rowIndex] = []\n for spotIndex, spot in enumerate(row):\n if lastSpot == WATER and spot == LAND:\n currentRowIslandStart = spotIndex\n\n if spotIndex + 1 >= lengthOfRow and spot == LAND:\n rowIslands[rowIndex].append((nextRowIsland, currentRowIslandStart, spotIndex))\n nextRowIsland += 1\n currentRowIslandStart = None\n elif spot == WATER and currentRowIslandStart != None:\n rowIslands[rowIndex].append((nextRowIsland, currentRowIslandStart, spotIndex - 1))\n nextRowIsland += 1\n\n if spot == WATER:\n currentRowIslandStart = None\n \n lastSpot = spot\n\n nextGroup = 1\n maxRowIndex = len(grid)\n rowIslandsToGroups = {}\n for rowNumber in [rowNumber for rowNumber in range(maxRowIndex)]:\n for rowIslandNumber, startIndex, endIndex in rowIslands[rowNumber]:\n rowIslandsToGroups[rowIslandNumber] = []\n if rowNumber == 0:\n rowIslandsToGroups[rowIslandNumber].append(nextGroup)\n nextGroup += 1\n continue\n for prevRowIslandNumber, prevStartIndex, prevEndIndex in rowIslands[rowNumber - 1]:\n if overlaps(prevStartIndex, prevEndIndex, startIndex, endIndex):\n for groupNumber in rowIslandsToGroups[prevRowIslandNumber]:\n rowIslandsToGroups[rowIslandNumber].append(groupNumber)\n if len(rowIslandsToGroups[rowIslandNumber]) == 0:\n rowIslandsToGroups[rowIslandNumber].append(nextGroup)\n nextGroup += 1\n\n groupBuckets = {}\n allBuckets = []\n for rowIslandNumber in range(1, nextRowIsland):\n relatedGroups = rowIslandsToGroups[rowIslandNumber]\n for group in relatedGroups:\n if (groupBuckets.get(group, None)) == None:\n newGroupBucket = Bucket([group])\n groupBuckets[group] = newGroupBucket\n allBuckets.append(newGroupBucket)\n relatedBuckets = [groupBuckets[group] for group in relatedGroups]\n firstBucket = relatedBuckets[0]\n for group in relatedGroups:\n if not firstBucket.contains(group):\n newCombinedBucket = firstBucket.combine(groupBuckets[group])\n allBuckets.append(newCombinedBucket)\n\n return len([resultBucket for resultBucket in allBuckets if not resultBucket.hasDestination()])\n \n \nsolver = Solution()\n\n# 1\n# inputGrid = [\n# '11110',\n# '11010',\n# '11000',\n# '00000',\n# ]\n\n# 3\n# inputGrid = [\n# '11000',\n# '11000',\n# '00100',\n# '00011',\n# ]\n\n# 1\n# inputGrid = [\n# '11011',\n# '10001',\n# '10001',\n# '11111',\n# ]\n\n# 5\n# inputGrid = [\n# '101',\n# '010',\n# '101',\n# ]\n\n# 1\ninputGrid = [\n '111',\n '010',\n '010',\n]\n\nprint(solver.numIslands(inputGrid))"} | |
| {"blob_id": "227925521077e04140edcb13d50808695efd39a5", "repo_name": "erikseulean/machine_learning", "path": "/python/linear_regression/multivariable.py", "length_bytes": 1042, "score": 3.671875, "int_score": 4, "content": "import numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\niterations = 35\nalpha = 0.1\n\ndef read_data():\n data = np.loadtxt('data/housing_prices.in', delimiter=',')\n X = data[:, [0,1]]\n y = data[:, 2]\n y.shape = (y.shape[0], 1)\n return X, y\n\ndef normalize(X):\n return (X - X.mean(0))/X.std(0)\n\ndef add_xzero(X):\n return np.hstack((np.ones((X.shape[0],1)), X))\n\ndef gradient_descent(X, y):\n theta = np.zeros((X.shape[1],1))\n m = X.shape[0]\n cost = []\n for _ in range(iterations):\n X_transpose = np.transpose(X)\n cost_deriv = (alpha/m) * np.dot(X_transpose, np.dot(X, theta) - y)\n theta = theta - cost_deriv\n\n cost_func = np.sum(np.square(np.dot(X, theta) - y))/(2 * m)\n cost.append(cost_func)\n \n return theta, cost\n\ndef plot_cost_function(cost):\n\n plt.plot(cost)\n plt.xlabel(\"Iterations\")\n plt.ylabel(\"Cost function\")\n\n plt.show()\n\nX, y = read_data()\nX = add_xzero(normalize(X))\ntheta, cost = gradient_descent(X, y)\nplot_cost_function(cost)\n\n"} | |
| {"blob_id": "c7b567bde9e143c404c3670793576644a26f6142", "repo_name": "AhmadQasim/Battleships-AI", "path": "/gym-battleship/gym_battleship/envs/battleship_env.py", "length_bytes": 4760, "score": 3.53125, "int_score": 4, "content": "import gym\nimport numpy as np\nfrom abc import ABC\nfrom gym import spaces\nfrom typing import Tuple\nfrom copy import deepcopy\nfrom collections import namedtuple\n\nShip = namedtuple('Ship', ['min_x', 'max_x', 'min_y', 'max_y'])\nAction = namedtuple('Action', ['x', 'y'])\n\n\n# Extension: Add info for when the ship is sunk\n\n\nclass BattleshipEnv(gym.Env, ABC):\n def __init__(self, board_size: Tuple = None, ship_sizes: dict = None, episode_steps: int = 100):\n self.ship_sizes = ship_sizes or {5: 1, 4: 1, 3: 2, 2: 1}\n self.board_size = board_size or (10, 10)\n\n self.board = None\n self.board_generated = None\n self.observation = None\n\n self.done = None\n self.step_count = None\n self.episode_steps = episode_steps\n\n self.action_space = spaces.Discrete(self.board_size[0] * self.board_size[1])\n\n # MultiBinary is a binary space array\n self.observation_space = spaces.MultiBinary([2, self.board_size[0], self.board_size[1]])\n\n # dict to save all the ship objects\n self.ship_dict = {}\n\n def step(self, raw_action: int) -> Tuple[np.ndarray, int, bool, dict]:\n assert (raw_action < self.board_size[0]*self.board_size[1]),\\\n \"Invalid action (Superior than size_board[0]*size_board[1])\"\n\n action = Action(x=raw_action // self.board_size[0], y=raw_action % self.board_size[1])\n self.step_count += 1\n if self.step_count >= self.episode_steps:\n self.done = True\n\n # it looks if there is a ship on the current cell\n # if there is a ship then the cell is 1 and 0 otherwise\n if self.board[action.x, action.y] != 0:\n\n # if the cell that we just hit is the last one from the respective ship\n # then add this info to the observation\n if self.board[self.board == self.board[action.x, action.y]].shape[0] == 1:\n ship = self.ship_dict[self.board[action.x, action.y]]\n self.observation[1, ship.min_x:ship.max_x, ship.min_y:ship.max_y] = 1\n\n self.board[action.x, action.y] = 0\n self.observation[0, action.x, action.y] = 1\n\n # if the whole board is already filled, no ships\n if not self.board.any():\n self.done = True\n return self.observation, 100, self.done, {}\n return self.observation, 1, self.done, {}\n\n # we end up here if we hit a cell that we had hit before already\n elif self.observation[0, action.x, action.y] == 1 or self.observation[1, action.x, action.y] == 1:\n return self.observation, -1, self.done, {}\n\n # we end up here if we hit a cell that has not been hit before and doesn't contain a ship\n else:\n self.observation[1, action.x, action.y] = 1\n return self.observation, 0, self.done, {}\n\n def reset(self):\n self.set_board()\n\n # maintain an original copy of the board generated in the start\n self.board_generated = deepcopy(self.board)\n self.observation = np.zeros((2, *self.board_size), dtype=np.float32)\n self.step_count = 0\n return self.observation\n\n def set_board(self):\n self.board = np.zeros(self.board_size, dtype=np.float32)\n k = 1\n for i, (ship_size, ship_count) in enumerate(self.ship_sizes.items()):\n for j in range(ship_count):\n self.place_ship(ship_size, k)\n k += 1\n\n def place_ship(self, ship_size, ship_index):\n can_place_ship = False\n while not can_place_ship:\n ship = self.get_ship(ship_size, self.board_size)\n can_place_ship = self.is_place_empty(ship)\n\n # set the ship cells to one\n self.board[ship.min_x:ship.max_x, ship.min_y:ship.max_y] = ship_index\n self.ship_dict.update({ship_index: ship})\n\n @staticmethod\n def get_ship(ship_size, board_size) -> Ship:\n if np.random.choice(('Horizontal', 'Vertical')) == 'Horizontal':\n # find the ship coordinates randomly\n min_x = np.random.randint(0, board_size[0] - 1 - ship_size)\n min_y = np.random.randint(0, board_size[1] - 1)\n return Ship(min_x=min_x, max_x=min_x + ship_size, min_y=min_y, max_y=min_y + 1)\n else:\n min_x = np.random.randint(0, board_size[0] - 1)\n min_y = np.random.randint(0, board_size[1] - 1 - ship_size)\n return Ship(min_x=min_x, max_x=min_x + 1, min_y=min_y, max_y=min_y + ship_size)\n\n def is_place_empty(self, ship):\n # make sure that there are no ships by simply summing the cell values\n return np.count_nonzero(self.board[ship.min_x:ship.max_x, ship.min_y:ship.max_y]) == 0\n\n def get_board(self):\n return self.board\n"} | |
| {"blob_id": "d818d77f017fb908113dbdffbbaafa2b301d5999", "repo_name": "dlaststark/machine-learning-projects", "path": "/Programming Language Detection/Experiment-2/Dataset/Train/Python/fibonacci-n-step-number-sequences-3.py", "length_bytes": 549, "score": 3.671875, "int_score": 4, "content": "from itertools import islice, cycle\n\ndef fiblike(tail):\n for x in tail:\n yield x\n for i in cycle(xrange(len(tail))):\n tail[i] = x = sum(tail)\n yield x\n\nfibo = fiblike([1, 1])\nprint list(islice(fibo, 10))\nlucas = fiblike([2, 1])\nprint list(islice(lucas, 10))\n\nsuffixes = \"fibo tribo tetra penta hexa hepta octo nona deca\"\nfor n, name in zip(xrange(2, 11), suffixes.split()):\n fib = fiblike([1] + [2 ** i for i in xrange(n - 1)])\n items = list(islice(fib, 15))\n print \"n=%2i, %5snacci -> %s ...\" % (n, name, items)\n"} | |
| {"blob_id": "d6ddba1536a4377251089a3df2ad91fb87b987b8", "repo_name": "jeremyyew/tech-prep-jeremy.io", "path": "/code/techniques/8-DFS/M341-flatten-nested-list-iterator.py", "length_bytes": 606, "score": 4.0, "int_score": 4, "content": "'''\n- Only pop and unpack what is necessary. \n- Pop and unpack when `hasNext` is called - it ensures there is a next available for `next`, if there really is a next. \n- At the end only need to check if stack is nonempty - stack nonempty and last element not integer is not possible.\n'''\n\nclass NestedIterator(object):\n\n\tdef __init__(self, nestedList):\n\t\tself.stack = nestedList[::-1]\n\n\n\tdef next(self):\n\t\treturn self.stack.pop().getInteger()\n\n\n\tdef hasNext(self):\n\t\twhile self.stack and not self.stack[-1].isInteger():\n\t\t\tnl = self.stack.pop()\n\t\t\tself.stack.extend(nl.getList()[::-1])\n\n\t\treturn self.stack"} | |
| {"blob_id": "eeb2068deeec87798355fe1bdd1e0f3508cbdcab", "repo_name": "jiqin/leetcode", "path": "/codes/212.py", "length_bytes": 2112, "score": 3.53125, "int_score": 4, "content": "class Solution(object):\n def findWords(self, board, words):\n \"\"\"\n :type board: List[List[str]]\n :type words: List[str]\n :rtype: List[str]\n \"\"\"\n word_map = {}\n for word in words:\n for i in range(len(word)):\n word_map[word[0:i+1]] = 0\n for word in words:\n word_map[word] = 1\n # print word_map\n\n results = []\n for i in range(len(board)):\n for j in range(len(board[0])):\n tmp_word = ''\n history_pos = []\n heap = [(i, j, 0)]\n\n while heap:\n x, y, l = heap.pop()\n if x < 0 or x >= len(board) or y < 0 or y >= len(board[0]):\n continue\n assert len(history_pos) >= l\n history_pos = history_pos[0:l]\n if (x, y) in history_pos:\n continue\n assert len(tmp_word) >= l\n tmp_word = tmp_word[0:l] + board[x][y]\n history_pos.append((x, y))\n # print x, y, tmp_word, heap, history_pos\n value = word_map.get(tmp_word)\n if value is None:\n continue\n if value == 1:\n results.append(tmp_word)\n\n heap.append((x - 1, y, l + 1))\n heap.append((x + 1, y, l + 1))\n heap.append((x, y - 1, l + 1))\n heap.append((x, y + 1, l + 1))\n\n return list(set(results))\n\n\nfor b, w in (\n # ([\n # ['o', 'a', 'a', 'n'],\n # ['e', 't', 'a', 'e'],\n # ['i', 'h', 'k', 'r'],\n # ['i', 'f', 'l', 'v']\n # ],\n # [\"oath\", \"pea\", \"eat\", \"rain\"]),\n # (['ab', 'cd'], ['acdb']),\n # ([\"ab\",\"cd\"], [\"ab\",\"cb\",\"ad\",\"bd\",\"ac\",\"ca\",\"da\",\"bc\",\"db\",\"adcb\",\"dabc\",\"abb\",\"acb\"]),\n ([\"abc\",\"aed\",\"afg\"], [\"abcdefg\",\"gfedcbaaa\",\"eaabcdgfa\",\"befa\",\"dgc\",\"ade\"]),\n):\n print Solution().findWords(b, w)\n"} | |
| {"blob_id": "5185d421330d59dc45577e6ed4e046a961461ae6", "repo_name": "m-hawke/codeeval", "path": "/moderate/17_sum_of_integers.py", "length_bytes": 970, "score": 3.703125, "int_score": 4, "content": "import sys\n\nfor line in open(sys.argv[1]):\n numbers = [int(x) for x in line.strip().split(',')]\n\n max_ = sum(numbers)\n for length in range(1, len(numbers), 2): # N.B increment by 2\n sum_ = sum(numbers[:length])\n max_ = sum_ if sum_ > max_ else max_\n for i in range(len(numbers)-length):\n # N.B. the following sum is also a sum of contiguous numbers\n # for length + 1. We need calculate this once only, and\n # therefore the length loop (see above) is incremented by 2\n # each time. */\n sum_ += numbers[i+length]\n max_ = sum_ if sum_ > max_ else max_\n sum_ -= numbers[i]\n max_ = sum_ if sum_ > max_ else max_\n\n print(max_)\n\n#for line in open(sys.argv[1]):\n# numbers = [int(x) for x in line.strip().split(',')]\n# print(max([sum(numbers[x:x+i])\n# for i in range(1,len(numbers)+1)\n# for x in range(len(numbers)-i+1)]))\n"} | |
| {"blob_id": "9d1ed42cd4a586df38bb7f2a122db69fbece314a", "repo_name": "aidank18/PythonProjects", "path": "/montyhall/MontyHall.py", "length_bytes": 1052, "score": 3.78125, "int_score": 4, "content": "from random import random\n\n\ndef game(stay):\n doors = makeDoors()\n choice = int(random() * 3)\n for i in range(0, 2):\n if (i != choice) and doors[i] == \"g\":\n doors[i] = \"r\"\n break\n if stay:\n return doors[choice]\n else:\n doors[choice] = \"r\"\n for door in doors:\n if door != \"r\":\n return door\n\ndef makeDoors():\n doors = [\"g\", \"g\", \"c\"]\n for i in range(0, 10):\n val1 = int(random() * 3)\n val2 = int(random() * 3)\n temp = doors[val1]\n doors[val1] = doors[val2]\n doors[val2] = temp\n return doors\n\n\ndef tests(stay):\n cars = 0\n for i in range(0, 10000):\n if game(stay) == \"c\":\n cars += 1\n probability = cars/10000\n if stay:\n print()\n print(\"The probability of picking the car by staying with the same door is\", probability)\n print()\n else:\n print()\n print(\"The probability of picking the car by switching doors is\", probability)\n print()\n\ntests(False)\n"} | |
| {"blob_id": "4b7ef56e7abace03cacb505daa6b34bdf90897b5", "repo_name": "sandrahelicka88/codingchallenges", "path": "/EveryDayChallenge/happyNumber.py", "length_bytes": 796, "score": 4.09375, "int_score": 4, "content": "import unittest\n'''Write an algorithm to determine if a number is \"happy\".\n\nA happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.'''\n\ndef isHappy(n):\n path = set()\n while n not in path and n!=1:\n path.add(n)\n nextSum = 0\n while n:\n nextSum+=(n%10)**2\n n = n//10\n n = nextSum\n return n==1\n\nclass Test(unittest.TestCase):\n def test_happyNumber(self):\n self.assertTrue(isHappy(19))\n\nif __name__ == '__main__':\n unittest.main()\n\n"} | |
| {"blob_id": "35f9a1fc4c45112660f9cd871d1514b348990ddf", "repo_name": "Jyun-Neng/LeetCode_Python", "path": "/103-binary-tree-zigzag-level-order.py", "length_bytes": 1644, "score": 4.09375, "int_score": 4, "content": "\"\"\"\nGiven a binary tree, return the zigzag level order traversal of its nodes' values. \n(ie, from left to right, then right to left for the next level and alternate between).\n\nFor example:\nGiven binary tree [3,9,20,null,null,15,7],\n 3\n / \\\n 9 20\n / \\\n 15 7\nreturn its zigzag level order traversal as:\n[\n [3],\n [20,9],\n [15,7]\n]\n\"\"\"\nimport collections\n\n\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution:\n def zigzagLevelOrder(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[List[int]]\n \"\"\"\n if not root:\n return []\n queue = collections.deque([])\n queue.append(root)\n reverse = False\n res = []\n # BFS\n while queue:\n size = len(queue)\n nodes = [0 for i in range(size)]\n for i in range(size):\n node = queue.popleft()\n idx = i if not reverse else size - 1 - i\n nodes[idx] = node.val\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n reverse = not reverse\n res.append(nodes)\n return res\n\n\nif __name__ == \"__main__\":\n vals = [3, 9, 20, None, None, 15, 7]\n root = TreeNode(vals[0])\n node = root\n node.left = TreeNode(vals[1])\n node.right = TreeNode(vals[2])\n node = node.right\n node.left = TreeNode(vals[5])\n node.right = TreeNode(vals[6])\n print(Solution().zigzagLevelOrder(root))\n"} | |
| {"blob_id": "eee031351c4115a1057b3b81293fe25a17ad8066", "repo_name": "jrinder42/Advent-of-Code-2020", "path": "/day15/day15.py", "length_bytes": 767, "score": 3.5, "int_score": 4, "content": "\n'''\n\nAdvent of Code 2020 - Day 15\n\n'''\n\nlookup = {0: [1],\n 3: [2],\n 1: [3],\n 6: [4],\n 7: [5],\n 5: [6]}\nturn = 7\nprev = 5\nwhile turn != 2020 + 1: # Part 1\n #while turn != 30_000_000 + 1: # Part 2\n if prev in lookup and len(lookup[prev]) == 1:\n prev = 0\n if prev in lookup:\n lookup[prev].append(turn)\n else:\n lookup[prev] = [turn]\n elif prev in lookup: # not unique\n prev = lookup[prev][-1] - lookup[prev][-2] # most recent - second most recent\n if prev in lookup:\n lookup[prev].append(turn)\n else:\n lookup[prev] = [turn]\n turn += 1\n\nprint('Advent of Code Day 15 Answer Part 1 / 2:', prev) # depends on while loop condition\n\n"} | |
| {"blob_id": "0838fcd3cd4ab10f7dffb318fdf9534e7db0e079", "repo_name": "rongduan-zhu/codejam2016", "path": "/1a/c/c.py", "length_bytes": 2061, "score": 3.578125, "int_score": 4, "content": "#!/usr/bin/env python\n\nimport sys\n\nclass Node:\n def __init__(self, outgoing, incoming):\n self.outgoing = outgoing\n self.incoming = incoming\n\ndef solve(fname):\n with open(fname) as f:\n tests = int(f.readline())\n\n for i in xrange(tests):\n f.readline()\n\n deps = map(int, f.readline().split(' '))\n two_node_cycles = []\n nodes = {}\n\n for j in xrange(1, len(deps) + 1):\n # setup outgoing nodes\n if j in nodes:\n nodes[j].outgoing = deps[j - 1]\n else:\n nodes[j] = Node(deps[j - 1], [])\n\n # setup incoming nodes\n if deps[j - 1] in nodes:\n nodes[deps[j - 1]].incoming.append(j)\n else:\n nodes[deps[j - 1]] = Node(None, incoming=[j])\n\n # setup two node cycles\n if nodes[j].outgoing in nodes and j == nodes[nodes[j].outgoing].outgoing:\n two_node_cycles.append((j, nodes[j].outgoing))\n\n print 'Case #{}: {}'.format(i + 1, traverse(nodes, two_node_cycles))\n\ndef traverse(nodes, two_node_cycles):\n bff_cycle = 0\n visited = {}\n\n for n1, n2 in two_node_cycles:\n visited[n1] = True\n visited[n2] = True\n bff_cycle += traverse_up(n1, nodes, visited, 1)\n bff_cycle += traverse_up(n2, nodes, visited, 1)\n\n for node in nodes:\n if node not in visited:\n visited_in_path = set()\n visited_in_path.add(node)\n\n start = node\n current = nodes[start].outgoing\n longest_cycle = 1\n\n while current not in visited_in_path:\n visited_in_path.add(current)\n current = nodes[current].outgoing\n longest_cycle += 1\n\n if start == current and longest_cycle > bff_cycle:\n bff_cycle = longest_cycle\n\n return bff_cycle\n\ndef traverse_up(node, nodes, visited, length):\n max_len = length\n for up_node in nodes[node].incoming:\n if up_node not in visited:\n visited[up_node] = True\n up_length = traverse_up(up_node, nodes, visited, length + 1)\n\n max_len = up_length if up_length > max_len else max_len\n return max_len\n\nif __name__ == '__main__':\n solve(sys.argv[1])\n"} | |
| {"blob_id": "d6c1dd48d0c1b6bdc9c5bd7ebd936b30201112e5", "repo_name": "febikamBU/string-matching", "path": "/bmh.py", "length_bytes": 2182, "score": 4.03125, "int_score": 4, "content": "from collections import defaultdict\nfrom sys import argv, exit\nfrom comparer import Comparer\n\n\ndef precalc(pattern):\n \"\"\"\n Create the precalculation table: a dictionary of the number of characters\n after the last occurrence of a given character. This provides the number of\n characters to shift by in the case of a mismatch. Defaults to the length of\n the string.\n \"\"\"\n table = defaultdict(lambda: len(pattern))\n for i in range(len(pattern) - 1):\n table[pattern[i]] = len(pattern) - i - 1\n return table\n\n\ndef run_bmh(table, text, pattern, compare):\n \"\"\"\n Using the precalculated table, yield every match of the pattern in the\n text, making comparisons with the provided compare function.\n \"\"\"\n \n # Currently attempted offset of the pattern in the text\n skip = 0\n\n # Keep going until the pattern overflows the text\n while skip + len(pattern) <= len(text):\n\n # Start matching from the end of the string\n i = len(pattern) - 1\n\n # Match each element in the pattern, from the end to the beginning\n while i >= 0 and compare(text, skip+i, pattern, i):\n i -= 1\n \n # If the start of the string has been reached (and so every comparison\n # was successful), then yield the position\n if i < 0:\n yield skip\n \n # Shift by the precalculated offset given by the character in the text\n # at the far right of the pattern, so that it lines up with an equal\n # character in the pattern, if posssible. Otherwise the pattern is\n # moved to after this position.\n skip += table[text[skip + len(pattern) - 1]]\n\n\nif __name__ == \"__main__\":\n try:\n pattern = argv[1]\n text = argv[2] \n except IndexError:\n print(\"usage: python3 bmh.py PATTERN TEXT\")\n exit()\n\n print(f'Searching for \"{pattern}\" in \"{text}\".')\n print()\n\n compare = Comparer()\n\n table = precalc(pattern)\n print(f'Precomputed shift table: {dict(table)}')\n print()\n\n for match in run_bmh(table, text, pattern, compare):\n print(f\"Match found at position {match}\")\n\n print(f\"{compare.count} comparisons\")\n"} | |
| {"blob_id": "ed83eebfc06efbb76af1baf6f9996f4389556824", "repo_name": "jhgdike/leetCode", "path": "/leetcode_python/1-100/43.py", "length_bytes": 686, "score": 3.578125, "int_score": 4, "content": "class Solution(object):\n\n \"\"\"\n Python can do it directly by str(int(num1)*int(num2))\n \"\"\"\n\n def multiply(self, num1, num2):\n \"\"\"\n :type num1: str\n :type num2: str\n :rtype: str\n \"\"\"\n res = [0] * (len(num1) + len(num2))\n lengh = len(res)\n for i, n1 in enumerate(reversed(num1)):\n for j, n2 in enumerate(reversed(num2)):\n res[i + j] += int(n1) * int(n2)\n res[i + j + 1] += res[i + j] / 10\n res[i + j] %= 10\n\n pt = lengh\n while pt > 0 and res[pt - 1] == 0:\n pt -= 1\n\n res = res[:pt]\n return ''.join(map(str, res[::-1] or [0]))\n"} | |
| {"blob_id": "db6be99a0fb8e2a18b0470e53a21557ef47a026a", "repo_name": "akaliutau/cs-problems-python", "path": "/problems/dp/Solution32.py", "length_bytes": 426, "score": 3.875, "int_score": 4, "content": "\"\"\" \n Given a string containing just the characters '(' and ')', find the length of\n the longest valid (well-formed) parentheses substring.\n \n \n \n Example 1:\n \n Input: s = \"(()\" Output: 2 Explanation: The longest valid parentheses\n substring is \"()\". Example 2:\n \n Input: s = \")()())\" Output: 4 Explanation: The longest valid parentheses\n substring is \"()()\".\n \n \n\"\"\"\n\nclass Solution32:\n pass\n"} | |
| {"blob_id": "f1d2f920c551650c468ce2db140b2a45bd44bbf7", "repo_name": "DayGitH/Python-Challenges", "path": "/DailyProgrammer/DP20141231B.py", "length_bytes": 1290, "score": 4.09375, "int_score": 4, "content": "\"\"\"\n[2014-12-31] Challenge #195 [Intermediate] Math Dice\n\nhttps://www.reddit.com/r/dailyprogrammer/comments/2qxrtk/20141231_challenge_195_intermediate_math_dice/\n\n#Description:\nMath Dice is a game where you use dice and number combinations to score. It's a neat way for kids to get mathematical\ndexterity. In the game, you first roll the 12-sided Target Die to get your target number, then roll the five 6-sided\nScoring Dice. Using addition and/or subtraction, combine the Scoring Dice to match the target number. The number of\ndice you used to achieve the target number is your score for that round. For more information, see the product page for\nthe game: (http://www.thinkfun.com/mathdice)\n#Input:\nYou'll be given the dimensions of the dice as NdX where N is the number of dice to roll and X is the size of the dice.\nIn standard Math Dice Jr you have 1d12 and 5d6.\n#Output:\nYou should emit the dice you rolled and then the equation with the dice combined. E.g.\n 9, 1 3 1 3 5\n 3 + 3 + 5 - 1 - 1 = 9\n#Challenge Inputs:\n 1d12 5d6\n 1d20 10d6\n 1d100 50d6\n#Challenge Credit:\nThanks to /u/jnazario for his idea -- posted in /r/dailyprogrammer_ideas\n#New year:\nHappy New Year to everyone!! Welcome to Y2k+15\n\"\"\"\n\n\ndef main():\n pass\n\n\nif __name__ == \"__main__\":\n main()\n"} | |
| {"blob_id": "4b2eb7f54b2898ce241dddfc0cc7966971ac4589", "repo_name": "Keshav1506/competitive_programming", "path": "/Hashing/006_geeksforgeeks_Swapping_Pairs_Make_Sum_Equal/Solution.py", "length_bytes": 3297, "score": 4.03125, "int_score": 4, "content": "#\n# Time : O(N^3); Space: O(N)\n# @tag : Hashing\n# @by : Shaikat Majumdar\n# @date: Aug 27, 2020\n# **************************************************************************\n# GeeksForGeeks - Swapping pairs make sum equal\n#\n# Description:\n#\n# Given two arrays of integers A[] and B[] of size N and M, the task is to check if a pair of values (one value from each array) exists such that swapping the elements of the pair will make the sum of two arrays equal.\n#\n# Example 1:\n#\n# Input: N = 6, M = 4\n# A[] = {4, 1, 2, 1, 1, 2}\n# B[] = (3, 6, 3, 3)\n#\n# Output: 1\n# Explanation: Sum of elements in A[] = 11\n# Sum of elements in B[] = 15, To get same\n# sum from both arrays, we can swap following\n# values: 1 from A[] and 3 from B[]\n#\n# Example 2:\n#\n# Input: N = 4, M = 4\n# A[] = {5, 7, 4, 6}\n# B[] = {1, 2, 3, 8}\n#\n# Output: 1\n# Explanation: We can swap 6 from array\n# A[] and 2 from array B[]\n#\n# Your Task:\n# This is a function problem. You don't need to take any input, as it is already accomplished by the driver code.\n# You just need to complete the function findSwapValues() that takes array A, array B, integer N, and integer M\n# as parameters and returns 1 if there exists any such pair otherwise returns -1.\n#\n# Expected Time Complexity: O(MlogM+NlogN).\n# Expected Auxiliary Space: O(1).\n#\n# **************************************************************************\n# Source: https://practice.geeksforgeeks.org/problems/swapping-pairs-make-sum-equal4142/1 (GeeksForGeeks - Swapping pairs make sum equal)\n#\n# **************************************************************************\n# Solution Explanation\n# **************************************************************************\n# Refer to Solution_Explanation.md.\n#\nimport unittest\n\n\nclass Solution:\n # Returns sum of elements in list\n def getSum(self, X):\n sum = 0\n for i in X:\n sum += i\n return sum\n\n # Finds value of\n # a - b = (sumA - sumB) / 2\n def getTarget(self, A, B):\n # Calculations of sumd from both lists\n sum1 = self.getSum(A)\n sum2 = self.getSum(B)\n\n # Because that target must be an integer\n if (sum1 - sum2) % 2 != 0:\n return 0\n return (sum1 - sum2) / 2\n\n def findSwapValues(self, A, B):\n # Call for sorting the lists\n A.sort()\n B.sort()\n\n # Note that target can be negative\n target = self.getTarget(A, B)\n\n # target 0 means, answer is not possible\n if target == 0:\n return False\n i, j = 0, 0\n while i < len(A) and j < len(B):\n diff = A[i] - B[j]\n if diff == target:\n return True\n # Look for a greater value in list A\n elif diff < target:\n i += 1\n # Look for a greater value in list B\n else:\n j += 1\n\n\nclass Test(unittest.TestCase):\n def setUp(self) -> None:\n pass\n\n def tearDown(self) -> None:\n pass\n\n def test_fourSum(self) -> None:\n sol = Solution()\n for A, B, solution in (\n [[4, 1, 2, 1, 1, 2], [3, 6, 3, 3], True],\n [[5, 7, 4, 6], [1, 2, 3, 8], True],\n ):\n self.assertEqual(solution, sol.findSwapValues(A, B))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"} | |
| {"blob_id": "545049864c75b1045885c8eddba22cc60de252d9", "repo_name": "betty29/code-1", "path": "/recipes/Python/577289_Maclaurinsseriestan1/recipe-577289.py", "length_bytes": 1615, "score": 4.0625, "int_score": 4, "content": "#On the name of ALLAH and may the blessing and peace of Allah \n#be upon the Messenger of Allah Mohamed Salla Allahu Aliahi Wassalam.\n#Author : Fouad Teniou\n#Date : 06/07/10\n#version :2.6\n\n\"\"\"\nmaclaurin_tan-1 is a function to compute tan-1(x) using maclaurin series\nand the interval of convergence is -1 <= x <= +1\nsin(x) = x - x^3/3 + x^5/5 - x^7/7 ...........\n\"\"\"\n\nfrom math import *\n\ndef error(number):\n \"\"\" Raises interval of convergence error.\"\"\"\n \n if number > 1 or number < -1 :\n raise TypeError,\\\n \"\\n<The interval of convergence should be -1 <= value <= 1 \\n\"\n\ndef maclaurin_cot(value, k):\n \"\"\"\n Compute maclaurin's series approximation for tan-1(x)\n \"\"\"\n global first_value \n first_value = 0.0\n \n #attempt to Approximate tan-1(x) for a given value \n try:\n error(value)\n for item in xrange(1,k,4):\n next_value = value**item/float(item)\n first_value += next_value\n \n for arg in range(3,k,4):\n next_value = -1* value **arg/float(arg)\n first_value += next_value\n \n return round(first_value*180/pi,2)\n \n #Raise TypeError if input is not within\n #the interval of convergence\n except TypeError,exception:\n print exception \n\nif __name__ == \"__main__\":\n \n maclaurin_cot1 = maclaurin_cot(0.305730681,100)\n print maclaurin_cot1\n maclaurin_cot2 = maclaurin_cot(0.75355405,100)\n print maclaurin_cot2\n maclaurin_cot3 = maclaurin_cot(0.577350269,100)\n print maclaurin_cot3\n#################################################################\n#\"C:\\python\n#17.0\n#37.0\n#30.0\n"} | |
| {"blob_id": "c56d992234d558fd0b0b49aa6029d6d287e90f2a", "repo_name": "ARSimmons/IntroToPython", "path": "/Students/Dave Fugelso/Session 2/ack.py", "length_bytes": 2766, "score": 4.25, "int_score": 4, "content": "'''\n\nDave Fugelso Python Course homework Session 2 Oct. 9\n\nThe Ackermann function, A(m, n), is defined:\n\nA(m, n) =\n n+1 if m = 0\n A(m-1, 1) if m > 0 and n = 0\n A(m-1, A(m, n-1)) if m > 0 and n > 0.\n \n\n\n See http://en.wikipedia.org/wiki/Ackermann_funciton\n\nCreate a new module called ack.py in a session02 folder in your student folder. \n\nIn that module, write a function named ack that performs Ackermann's function.\n\n\nWrite a good docstring for your function according to PEP 257.\nAckermanns function is not defined for input values less than 0. Validate inputs to your function and return None if they are negative.\nThe wikipedia page provides a table of output values for inputs between 0 and 4. Using this table, add a if __name__ == \"__main__\": block to test your function.\n\nTest each pair of inputs between 0 and 4 and assert that the result produced by your function is the result expected by the wikipedia table.\n\nWhen your module is run from the command line, these tests should be executed. If they all pass, \n\n\nprint All Tests Pass as the result.\n\nAdd your new module to your git clone and commit frequently while working on your implementation. Include good commit messages that explain concisely both what you are doing and why.\n\nWhen you are finished, push your changes to your fork of the class repository in GitHub. Then make a pull request and submit your assignment in Canvas.\n\n'''\n\n#Ackermann function\ndef ack(m, n):\n '''\n Calculate the value for Ackermann's function for m, n.\n '''\n \n if m < 0 or n < 0: return None\n \n if m == 0: return n+1\n \n if n == 0: return ack(m-1, 1)\n \n return ack (m-1, ack (m, n-1))\n \nclass someClass (object):\n\n def __init__(self):\n self.setBody('there')\n\n def afunc (self, a):\n print a, self.getBody()\n\n def getBody(self):\n return self.__body\n \n def setBody(self, value):\n self.__body = value\n \n body = property(getBody, setBody, None, \"Body property.\") \n\n \nif __name__ == \"__main__\":\n '''\n Unit test for Ackermann function. Print table m = 0,4 and n = 0,4.\n '''\n \n #Print nicely\n print 'm/n\\t\\t',\n for n in range(0,5):\n print n, '\\t',\n print '\\n'\n \n for m in range (0,4):\n print m,'\\t',\n for n in range(0,5):\n print '\\t',\n print ack(m, n),\n print\n\n # for the m = 4 row, just print the first one (n = 0) otherwise we hit a stack overflow (maximum resursion)\n m = 4\n print m,'\\t',\n for n in range(0,1):\n print '\\t',\n print ack(m, n),\n print '\\t-\\t-\\t-\\t-'\n \n print 'All Tests Pass'\n \n s = someClass ()\n s.afunc('hello')\n s.body = 'fuck ya!'\n s.afunc('hello')\n s.body = 'why not?'"} | |
| {"blob_id": "2b6b64ed41e1ed99a4e8a12e1e6ab53e6a9596ef", "repo_name": "AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges", "path": "/Challenges/shortestWayToFormString.py", "length_bytes": 7619, "score": 3.78125, "int_score": 4, "content": "\"\"\"\nShortest Way to Form String\n\nFrom any string, we can form a subsequence of that string by deleting some number of characters (possibly no deletions).\n\nGiven two strings source and target, return the minimum number of subsequences of source such that their concatenation equals target. If the task is impossible, return -1.\n\"\"\"\n\n\n\"\"\"\nBinary Search\n\nCreate mapping from each source char to the indices in source of that char.\nIterate over target, searching for the next index in source of each char. Return -1 if not found.\nSearch is by binary search of the list of indices in source of char.\nIf the next index in source requires wrapping around to the start of source, increment result count.\nTime: O(n log m) for source of length m and target of length n.\nSpace: O(m) \n\nThe idea is to create an inverted index that saves the offsets of where each character occurs in source. The index data structure is represented as a hashmap, where the Key is the character, and the Value is the (sorted) list of offsets where this character appears. To run the algorithm, for each character in target, use the index to get the list of possible offsets for this character. Then search this list for next offset which appears after the offset of the previous character. We can use binary search to efficiently search for the next offset in our index.\n\nExample with source = \"abcab\", target = \"aabbaac\"\nThe inverted index data structure for this example would be:\ninverted_index = {\na: [0, 3] # 'a' appears at index 0, 3 in source\nb: [1, 4], # 'b' appears at index 1, 4 in source\nc: [2], # 'c' appears at index 2 in source\n}\nInitialize i = -1 (i represents the smallest valid next offset) and loop_cnt = 1 (number of passes through source).\nIterate through the target string \"aabbaac\"\na => get the offsets of character 'a' which is [0, 3]. Set i to 1.\na => get the offsets of character 'a' which is [0, 3]. Set i to 4.\nb => get the offsets of character 'b' which is [1, 4]. Set i to 5.\nb => get the offsets of character 'b' which is [1, 4]. Increment loop_cnt to 2, and Set i to 2.\na => get the offsets of character 'a' which is [0, 3]. Set i to 4.\na => get the offsets of character 'a' which is [0, 3]. Increment loop_cnt to 3, and Set i to 1.\nc => get the offsets of character 'c' which is [2]. Set i to 3.\nWe're done iterating through target so return the number of loops (3).\n\nThe runtime is O(M) to build the index, and O(logM) for each query. There are N queries, so the total runtime is O(M + N*logM). M is the length of source and N is the length of target. The space complexity is O(M), which is the space needed to store the index.\n\"\"\"\nclass Solution:\n def shortestWay(self, source: str, target: str) -> int:\n \n index = collections.defaultdict(list)\n \n for i, s in enumerate(source):\n index[s].append(i)\n \n res = 0\n i = 0 # next index of source to check\n \n for t in target:\n if t not in index:\n return -1 # cannot make target if char not in source\n \n indices = index[t]\n j = bisect.bisect_left(indices, i)\n if j == len(indices): # index in char_indices[c] that is >= i\n res += 1 # wrap around to beginning of source\n j = 0\n i = indices[j] + 1 # next index in source\n \n return res if i == 0 else res + 1 # add 1 for partial source\n \ndef shortestWay(self, source: str, target: str) -> int:\n inverted_index = collections.defaultdict(list)\n for i, ch in enumerate(source):\n inverted_index[ch].append(i)\n\n loop_cnt = 1\n i = -1\n for ch in target:\n if ch not in inverted_index:\n return -1\n offset_list_for_ch = inverted_index[ch]\n # bisect_left(A, x) returns the smallest index j s.t. A[j] >= x. If no such index j exists, it returns len(A).\n j = bisect.bisect_left(offset_list_for_ch, i)\n if j == len(offset_list_for_ch):\n loop_cnt += 1\n i = offset_list_for_ch[0] + 1\n else:\n i = offset_list_for_ch[j] + 1\n\n return loop_cnt\n\n\n\n\"\"\"\nDP\n\nThe main idea behind this code is also to build up an inverted index data structure for the source string and then to greedily use characters from source to build up the target. In this code, it's the dict array. Each character is mapped to an index where it is found at in source. In this code, dict[i][c - 'a'] represents the earliest index >= i where character c occurs in source.\n\nFor example, if source = \"xyzy\", then dict[0]['y' - 'a'] = 1 but dict[2]['y'-'a'] = 3.\n\nAlso a value of -1, means that there are no occurrences of character c after the index i.\n\nSo, after this inverted data structure is built (which took O(|\u03a3|*M) time). We iterate through the characters of our target String. The idxOfS represents the current index we are at in source.\nFor each character c in target, we look for the earliest occurrence of c in source using dict via dict[idxOfS][c - 'a']. If this is -1, then we have not found any other occurrences and hence we need to use a new subsequence of S.\n\nOtherwise, we update idxOfS to be dict[idxOfS][c - 'a'] + 1 since we can only choose characters of source that occur after this character if we wish to use the same current subsequence to build the target.\n\ndict[idxOfS][c-'a'] = N - 1 is used as a marker value to represent that we have finished consuming the entire source and hence need to use a new subsequence to continue.\n\n(I would highly recommend reading @Twohu's examples of how to use the inverted index data structure to greedily build target using the indexes. They go into much more detail).\n\nAt the end, the check for (idxOfS == 0? 0 : 1) represents whether or not we were in the middle of matching another subsequence. If we were in the middle of matching it, then we would need an extra subsequence count of 1 since it was never accounted for.\n\n\n\"\"\"\nclass Solution:\n def shortestWay(self, source: str, target: str) -> int:\n if len(set(target) - set(source)) > 0:\n return -1\n \n m = len(source)\n move = [[-1]*26 for _ in range(m)]\n move[0] = [source.find(chr(c)) + 1 for c in range(ord('a'), ord('a') + 26)]\n \n for i in range(-1, -m, -1):\n move[i] = list(map(lambda x: x+1, move[i+1]))\n move[i][ord(source[i]) - 97] = 1\n \n i = 0\n for c in target:\n i += move[i%m][ord(c)-ord('a')]\n return i//m + (i%m > 0)\n \n\"\"\"\nGreedy\nTime: O(MN)\n\"\"\"\nclass Solution(object):\n def shortestWay(self, source, target):\n def match(st):#match source from st index of target\n idx=0#idx of source\n while idx<len(source) and st<n:\n if source[idx]==target[st]:\n st+=1\n idx+=1\n else:\n idx+=1\n return st\n \n n=len(target)\n source_set=set(source)\n for ch in target:\n if ch not in source_set:\n return -1\n #match one by one,match string until cannot match anymore.\n st=0\n count=0\n while st<n:\n st=match(st)\n count+=1\n return count\n\nclass Solution:\n def shortestWay(self, source: str, target: str) -> int:\n def inc():\n self.cnt += 1\n return 0\n self.cnt = i = 0\n for t in target:\n i = source.find(t, i) + 1 or source.find(t, inc()) + 1\n if not i:\n return -1\n return self.cnt + 1\n"} | |
| {"blob_id": "6c8e13d208beafae5b669f07b0dadd18d1c6a2b4", "repo_name": "dltech-xyz/Alg_Py_Xiangjie", "path": "/\u7b2c5\u7ae0/huo.py", "length_bytes": 1953, "score": 3.921875, "int_score": 4, "content": "class Node(object):\n def __init__(self, value, left=None, right=None):\n self.value = value\n self.left = None\n self.right = None\n\nclass Huffman(object):\n\n def __init__(self, items=[]):\n while len(items)!=1:\n a, b = items[0], items[1]\n newvalue = a.value + b.value\n newnode = Node(value=newvalue)\n newnode.left, newnode.right = a, b\n items.remove(a)\n items.remove(b)\n items.append(newnode)\n items = sorted(items, key=lambda node: int(node.value))\n # \u6bcf\u6b21\u90fd\u8981\u8bb0\u5f97\u66f4\u65b0\u65b0\u7684\u970d\u592b\u66fc\u6811\u7684\u6839\u8282\u70b9\n self.root = newnode\n\n def print(self):\n queue = [self.root]\n while queue:\n current = queue.pop(0)\n print(current.value, end='\\t')\n if(current.left):\n queue.append(current.left)\n if current.right:\n queue.append(current.right)\n print()\n\ndef sortlists(lists):\n return sorted(lists, key=lambda node: int(node.value))\n\ndef create_huffman_tree(lists):\n while len(lists)>1:\n a, b = lists[0], lists[1]\n node = Node(value=int(a.value+b.value))\n node.left, node.right = a, b\n lists.remove(a)\n lists.remove(b)\n lists.append(node)\n lists = sorted(lists, key=lambda node: node.value)\n return lists\n\n\ndef scan(root):\n if root:\n queue = [root]\n while queue:\n current = queue.pop(0)\n print(current.value, end='\\t')\n if current.left:\n queue.append(current.left)\n if current.right:\n queue.append(current.right)\n\nif __name__ == '__main__':\n ls = [Node(i) for i in range(1, 5)]\n huffman = Huffman(items=ls)\n huffman.print()\n print('===================================')\n lssl = [Node(i) for i in range(1, 5)]\n root = create_huffman_tree(lssl)[0]\n scan(root)"} | |
| {"blob_id": "5b5b2327e84313fca65952be1f103454b6f63797", "repo_name": "annatjohansson/complex_dynamics", "path": "/Python scripts/M_DEM.py", "length_bytes": 2566, "score": 3.8125, "int_score": 4, "content": "def M_Dist(cx, cy, max_it, R):\n \"\"\"Computes the distance of a point z = x + iy from the Mandelbrot set \"\"\"\n \n \"\"\"Inputs: \n c = cx + cy: translation\n max_it: maximum number of iterations\n R: escape radius (squared)\"\"\"\n \n x = 0.0\n y = 0.0\n x2 = 0.0\n y2 = 0.0\n\n dist = 0.0\n it = 0\n \n # List to store the orbit of the origin\n X = [0]*(max_it + 1)\n Y = [0]*(max_it + 1)\n \n # Iterate p until orbit exceeds escape radius or max no. of iterations is reached\n while (it < max_it) and (x2 + y2 < R):\n temp = x2 - y2 + cx\n y = 2*x*y + cy\n x = temp\n \n x2 = x*x\n y2 = y*y\n \n # Store the orbit\n X[it] = x\n Y[it] = y\n \n it = it + 1\n \n # If the escape radius is exceeded, calculate the distance from M\n if (x2 + y2 > R):\n x_der = 0.0\n y_der = 0.0\n i = 0\n flag = False\n \n # Approximate the derivative\n while (i < it) and (flag == False):\n temp = 2*(X[i]*x_der - Y[i]*y_der)+1\n y_der = 2*(Y[i]*x_der + X[i]*y_der)\n x_der = temp\n flag = max(abs(x_der),abs(y_der)) > (2 ** 31 - 1)\n i = i+1\n \n if (flag == False):\n dist = np.log(x2 + y2)*np.sqrt(x2 + y2)/np.sqrt(x_der*x_der + y_der*y_der)\n \n return dist\n \ndef M_DEM(M, nx, ny, x_min, x_max, y_min, y_max, max_it, R, threshold):\n \"\"\"Computes an approximation of the Mandelbrot set via the distance estimation method\"\"\"\n \n \"\"\"Inputs: \n M: an output array of size nx*ny\n nx, ny: the image resolution in the x- and y direction\n x_min, x_max: the limits of the x-axis in the region\n y_min, y_max: the limits of the y-axis in the region\n max_it: the maximum number of iterations\n R: escape radius (squared)\n threshold: critical distance from the Mandelbrot set (in pixel units)\"\"\"\n \n # Calculate the threshold in terms of distance in the complex plane\n delta = threshold*(x_max-x_min)/(nx-1)\n \n # For each pixel in the nx*ny grid, calculate the distance of the point\n for iy in range(0, ny):\n cy = y_min + iy*(y_max - y_min)/(ny - 1)\n for ix in range(0, nx):\n cx = x_min + ix*(x_max - x_min)/(nx - 1)\n \n #Determine whether distance is smaller than critical distance\n dist = M_Dist(cx, cy, max_it, R)\n if dist < delta:\n M[ix][iy] = 1\n else:\n M[ix][iy] = 0\n \n return M "} | |
| {"blob_id": "5dda83f2be9b2a8a87c459d3ba1dfe867633e9a2", "repo_name": "dexterchan/DailyChallenge", "path": "/MAR2020/PhoneNumbers.py", "length_bytes": 2568, "score": 3.9375, "int_score": 4, "content": "#Skill: Tries\n#Difficulty : EASY\n#Given a phone number, return all valid words that can be created using that phone number.\n\n#For instance, given the phone number 364\n#we can construct the words ['dog', 'fog'].\n\n#Here's a starting point:\n\n#Analysis\n#If done by brutal force, time cost is exponent to find all possibilties\n#To reduce to linear, we can use data structure Tries\n#Create a Tries from valid words... using digit sequence.... time cost O[N] -> linear\n#To search for word with number, it cost O[N]\n#space complexity is Linear O(N)\nfrom typing import List\nlettersMaps = {\n 1: [],\n 2: ['a', 'b', 'c'],\n 3: ['d', 'e', 'f'],\n 4: ['g', 'h', 'i'],\n 5: ['j', 'k', 'l'],\n 6: ['m', 'n', 'o'],\n 7: ['p', 'q', 'r', 's'],\n 8: ['t', 'u', 'v'],\n 9: ['w', 'x', 'y', 'z'],\n 0: []\n}\n\nclass Tries():\n def __init__(self, isWord=False):\n self.digits = [None]*10\n self.isWord = isWord\n self.bagOfWords = []\n\n def insertWord(self, word):\n self.isWord = True\n self.bagOfWords.append(word)\n def get(self, digit):\n return self.digits[digit]\n\n def assign(self, digit):\n self.digits[digit] = Tries()\n\n\nvalidWords = ['dog', 'fish', 'cat', 'fog']\n\nclass PhoneNumbers():\n def __init__(self):\n self.tries = Tries()\n\n def constructTries(self, validWords:List[str]):\n for w in validWords:\n tries = self.tries\n cnt = 0\n maxLen = len(w)\n for ch in w:\n d = self.__mapChToNumber(ch)\n if d is None:\n raise Exception(\"not found character to map digit:\"+ch)\n if tries.get(d) is None:\n tries.assign(d)\n tries = tries.get(d)\n cnt = cnt + 1\n if cnt == maxLen:\n tries.insertWord(w)\n\n\n def __mapChToNumber(self, ch):\n for (d, l) in lettersMaps.items():\n if ch in l:\n return d\n return None\n\n def getWords(self, phoneNumbers:str):\n tries = self.tries\n result = []\n for d in phoneNumbers:\n tries = tries.get(int(d))\n if tries is None:\n return result\n result = tries.bagOfWords\n return result\n\nphoneNumbers = PhoneNumbers()\nphoneNumbers.constructTries(validWords)\n\ndef makeWords(phone):\n #Fill this in\n phoneNumbersRef = phoneNumbers\n return phoneNumbers.getWords(phone)\n\n\nif __name__ == \"__main__\":\n print(makeWords('364'))\n # ['dog', 'fog']\n\n print(makeWords('3474'))"} | |
| {"blob_id": "2e027c271f142affced4a4f873058702cea3487b", "repo_name": "Leahxuliu/Data-Structure-And-Algorithm", "path": "/Python/Binary Search Tree/669.Trim a Binary Search Tree.py", "length_bytes": 1471, "score": 4.09375, "int_score": 4, "content": "# !/usr/bin/python\n# -*- coding: utf-8 -*-\n# @Time : 2020/03/30 \n# @Author : XU Liu\n# @FileName: 669.Trim a Binary Search Tree.py\n\n'''\n1. \u9898\u76ee\u7c7b\u578b\uff1a\n BST\n\n2. \u9898\u76ee\u8981\u6c42\u4e0e\u7406\u89e3\uff1a\n Trim a Binary Search Tree\uff08\u4fee\u526a\u6811\uff09\n \u7ed9\u5b9a\u4e00\u4e2a\u4e8c\u53c9\u641c\u7d22\u6811\uff0c\u540c\u65f6\u7ed9\u5b9a\u6700\u5c0f\u8fb9\u754c L \u548c\u6700\u5927\u8fb9\u754c R\u3002\u901a\u8fc7\u4fee\u526a\u4e8c\u53c9\u641c\u7d22\u6811\uff0c\u4f7f\u5f97\u6240\u6709\u8282\u70b9\u7684\u503c\u5728 [L, R] \u4e2d (R>=L) \n\n3. \u89e3\u9898\u601d\u8def\uff1a\n \u5bf9\u6bd4R, L, root\u4e4b\u95f4\u7684\u5927\u5c0f\u5173\u7cfb\uff0c\u7c7b\u4f3c\u4e8c\u5206\u6cd5\u91cc\u627e\u4e00\u5b9a\u8303\u56f4\u5185\u7684\u503c\n \u7528recursion\n a. end: root is None\n b. R < root.val --> \u7559\u4e0bleft subtree, \u7f29\u5c0f\u8303\u56f4\n c. l > root.val --> \u7559\u4e0bright subtree, \u7f29\u5c0f\u8303\u56f4\n d. L <= root val and R >= root.val --> \u7559\u4e0bboth sides of the tree\n\n\n4. \u8f93\u51fa\u8f93\u5165\u4ee5\u53ca\u8fb9\u754c\u6761\u4ef6\uff1a\ninput: root: TreeNode, L: int, R: int\noutput: TreeNode\ncorner case: None\n\n5. \u7a7a\u95f4\u65f6\u95f4\u590d\u6742\u5ea6\n \n\n'''\n\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution:\n def trimBST(self, root, L, R):\n if root == None:\n return None\n \n if R < root.val:\n return self.trimBST(root.left, L, R)\n if L > root.val:\n return self.trimBST(root.right, L, R)\n if L <= root.val and R >= root.val:\n root.left = self.trimBST(root.left, L, R)\n root.right = self.trimBST(root.right, L, R)\n return root\n\n"} | |
| {"blob_id": "304f5e570b6810e9a79473cfa6b1fbda91a02a90", "repo_name": "boop34/adventofcode-2020", "path": "/day_13/day_13.py", "length_bytes": 1810, "score": 3.609375, "int_score": 4, "content": "#!/usr/bin/env python3\n\n# fetch the input\nwith open('input.txt', 'r') as f:\n # initialize the departure time\n d_time = int(f.readline().strip())\n # get the bus information\n bus_ids = f.readline().strip().split(',')\n # include the 'x' for the second part of the puzzle\n bus_ids = list((int (i) if i != 'x' else -1) for i in bus_ids)\n # bus_ids = list(map(int, (filter(lambda x: x != 'x', bus_ids))))\n\ndef solve1(d_time, bus_ids):\n # loop untill we find the perfect bus\n while True:\n # check if the current departure time can be fulfilled by buses\n for bus in bus_ids:\n # if -1 then skip\n if bus == -1:\n continue\n # chec if the current departure time is divisable by the bus id\n if d_time % bus == 0:\n return d_time, bus\n # otherwise increment the d_time\n d_time += 1\n # ideally the control should never get here\n return None\n\n\n# for the first puzzle\nd_time_, bus_id = solve1(d_time, bus_ids)\nprint(bus_id * (d_time_ - d_time))\n\n# for the second part we have to implement Chinese Remainder Theorem\n# https://en.wikipedia.org/wiki/Chinese_remainder_theorem\n\n# initialize a list to store the remainder and moduli tuple\nl = []\n# populate the list\nfor i, r in enumerate(bus_ids):\n # if -1 then skip\n if r == -1:\n continue\n # otherwise valid bus id\n else:\n l.append((r, (r - i) % r))\n\n# store the first moduli and the required value\nn, x = l[0]\n\n# https://en.wikipedia.org/wiki/Chinese_remainder_theorem#Search_by_sieving\n# https://github.com/woj76/adventofcode2020/blob/main/src/day13.py\n# iterate over the the list\nfor n_, a in l[1:]:\n while True:\n x += n\n if x % n_ == a:\n break\n n *= n_\n\n# for the second puzzle\nprint(x)\n"} | |
| {"blob_id": "16c125fbe1b7e1dfeba8515f38a5e88cf73e5380", "repo_name": "sanket-qp/IK", "path": "/16-Strings/longest_repeating_substring.py", "length_bytes": 6042, "score": 4.125, "int_score": 4, "content": "\"\"\"\nLongest repeating substring\n\nApproaches:\n\n(1) Brute force: Generate all substrings and count their occurrence\n Time Complexity: O(N^4) = O(N^2) for generating all substrings\n + O(N^2) for num_occurrence (string compare also takes O(N))\n\n Space Complexity: O(1)\n\n(2) Using radix tree:\n We'll add all the suffixes of a given string in to a radix tree.\n Then we'll find the node with most termination character ($) in it's subtree.\n\n A node in the radix tree represents a prefix and all the children represents suffixes\n whose prefix is a current node.\n\n That means that the node which has most termination characters is a prefix of more than one suffixes\n We need to find such node which has most $ under it.\n\n so, to find most repeating substring, we'll just find a node with maximum $ in it'subtree.\n\n --------\n\n Now, to find Longest repeating substring, we'll find a node which is farthest (i.e. longest) from the root and has\n multiple $s in it's subtree\n\n Example:\n banana:\n ana is a prefix of anana and ana\n ana is the Longest repeating substring\n\n mississippi:\n issi is prefix of issippi and issiissippi\n issi is the Longest repeating substring\n\n\"\"\"\n\nfrom radix_tree import RadixTree\n\n\ndef all_substrings(s):\n for i in range(len(s)):\n for j in range(i + 1, len(s) + 1):\n yield s[i:j]\n\n\ndef num_occurrence(s, substr):\n n = 0\n for idx in range(len(s) - len(substr) + 1):\n temp = s[idx:idx + len(substr)]\n # print temp\n if temp == substr:\n n += 1\n return n\n\n\ndef longest_repeating_substring_brute_force(s):\n max_len = 1\n longest_so_far = s[0]\n most_occurred = 1\n for substr in all_substrings(s):\n n = num_occurrence(s, substr)\n if len(substr) > max_len and n >= most_occurred and n > 1:\n max_len = max(max_len, len(substr))\n most_occurred = n\n longest_so_far = substr\n return longest_so_far\n\n\ndef all_suffixes(s):\n for i in range(len(s) - 1, -1, -1):\n yield s[i:]\n\n\ndef xnode_with_max_termination_chars(root):\n def get_node(node):\n if not node:\n return (None, 0, 0)\n\n if node.is_leaf():\n return (node, 1, 1)\n\n _max = 0\n chosen_node = None\n _sum = 0\n for child in node.children:\n n, num, sum_child = get_node(child)\n _sum += num\n if sum_child > _max:\n _max = sum_child\n chosen_node = child\n print \"chosen: %s, sum: %s\" % (chosen_node, sum_child)\n\n print \"child: %s, total: %s\" % (child, _sum)\n return chosen_node, _max, _sum\n\n node, _max, _sum = get_node(root)\n print \"node: %s, max: %s, sum: %s\" % (node, _max, _sum)\n\n\ndef node_with_max_termination_chars(root):\n def get_max(node):\n if not node:\n return 0\n\n if node.is_leaf():\n return 1\n\n _sum = 0\n for child in node.children:\n _sum += get_max(child)\n return _sum\n\n max_repeating_node = None\n max_occurrence = 0\n for child in root.children:\n temp = get_max(child)\n if temp > max_occurrence:\n max_repeating_node = child\n max_occurrence = temp\n\n return max_repeating_node, max_occurrence\n\n\ndef most_repeating_substring_using_radix_tree(s):\n tree = RadixTree()\n for suffix in all_suffixes(s):\n tree.add_word(suffix)\n\n tree.level_order()\n return node_with_max_termination_chars(tree.root)\n\n\ndef longest_node_with_max_termination_chars(root):\n def get_longest(node):\n if not node:\n return 0, None\n\n if node.is_leaf():\n return 1, node.key\n\n total = 0\n longest_so_far = \"\"\n max_dollars = 0\n for child in node.children:\n num_dollars, longest = get_longest(child)\n total += num_dollars\n # find the longest and most repeating\n if num_dollars > max_dollars:\n longest_so_far = longest\n max_dollars = num_dollars\n\n longest_so_far = node.key + longest_so_far\n return total, longest_so_far\n\n _max = 0\n longest_repeating = None\n for child in root.children:\n total, longest = get_longest(child)\n print \"%s: %s, total: %s\" % (child.key, longest, total)\n if total > _max:\n _max = total\n longest_repeating = longest\n\n return longest_repeating[:-1]\n\n\ndef longest_repeating_substring_using_radix_tree(s):\n \"\"\"\n root asks each of the children that give me the number of $ in your subtree and which one is the longest\n \"\"\"\n tree = RadixTree()\n for suffix in all_suffixes(s):\n tree.add_word(suffix)\n\n longest = longest_node_with_max_termination_chars(tree.root)\n # print \"longest: %s\" % longest\n return longest\n\n\ndef main():\n assert 2 == num_occurrence(\"banana\", \"ana\")\n assert 3 == num_occurrence(\"banana\", \"a\")\n assert 2 == num_occurrence(\"banana\", \"na\")\n assert 2 == num_occurrence(\"banana\", \"an\")\n assert 1 == num_occurrence(\"banana\", \"b\")\n assert 0 == num_occurrence(\"banana\", \"xyz\")\n\n assert \"ana\" == longest_repeating_substring_brute_force(\"banana\")\n assert \"a\" == longest_repeating_substring_brute_force(\"abcdef\")\n\n node, total = most_repeating_substring_using_radix_tree(\"banana\")\n assert \"a\" == node.key\n assert 3 == total\n\n node, total = most_repeating_substring_using_radix_tree(\"mississippi\")\n assert \"i\" == node.key\n assert 4 == total\n\n assert \"ana\" == longest_repeating_substring_using_radix_tree(\"banana\")\n assert \"issi\" == longest_repeating_substring_using_radix_tree(\"mississippi\")\n assert \"aaa\" == longest_repeating_substring_using_radix_tree(\"aaaa\")\n\n\nif __name__ == '__main__':\n main()\n"} | |
| {"blob_id": "0bb7b65666ac17d8207a34eea9141ea700d5aa46", "repo_name": "N11K6/Digi_FX", "path": "/Distortion/Valve.py", "length_bytes": 1552, "score": 3.5, "int_score": 4, "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nThis function applies distortion to a given audio signal by modelling the\neffects from a vacuum tube. Input parameters are the signal vector x,\npre-gain G, \"work point\" Q, amount of distortion D, and pole positions r1\nand r2 for the two filters used.\n\n@author: nk\n\"\"\"\nimport numpy as np\nfrom scipy import signal\nfrom scipy.io import wavfile\n#%%\ndef Valve(x,G=1,Q=-0.05,D=400,r1=0.97,r2=0.8):\n \n # Normalize input:\n x = x / (np.max(np.abs(x)))\n # Apply pre-gain:\n x *= G\n # Oversampling:\n x_over = signal.resample(x, 8 * len(x))\n if Q == 0:\n y_over = x_over/(1-np.exp(-D * x_over)) - 1 / D\n else:\n # Apply Distortion:\n PLUS = Q / (1-np.exp(D*Q))\n EQUAL_QX = 1 / D + Q / (1 - np.exp(D * Q))\n # Logical indexing:\n logiQ = (x_over % Q != 0).astype(int)\n x_Q = x_over - Q\n y_0 = - (logiQ - 1) * EQUAL_QX\n y_1 = (logiQ * x_Q) / (1 - np.exp(-D * (logiQ * x_over -Q)))+PLUS\n y_over = y_0 + y_1\n # Downsampling:\n y = signal.decimate(y_over, 8)\n # Filtering:\n B = [1, -2, 1]\n A = [1, -2*r1, r1**2]\n y = signal.filtfilt(B, A, y)\n b = 1-r2\n a = [1, -r2]\n y = signal.filtfilt(b, a, y)\n # Normalization:\n y /= np.max(np.abs(y))\n return y\n#%%\nif __name__ == \"__main__\":\n G=1\n Q=-0.05\n D=400\n r1=0.97\n r2=0.8\n \n sr, data = wavfile.read(\"../TestGuitarPhraseMono.wav\")\n y = Valve(data,G,Q,D,r1,r2)\n wavfile.write(\"example_Valve.wav\", sr, y.astype(np.float32))"} | |
| {"blob_id": "3690eb92ccb03029609dfd0ac4f38bfb363fb90e", "repo_name": "zeroviral/leetcode_stuff", "path": "/trapping-rain-water/trapping-rain-water.py", "length_bytes": 1519, "score": 3.75, "int_score": 4, "content": "class Solution:\n def trap(self, height: List[int]) -> int:\n '''\n Setup: We need - leftmax, rightmax, left pointer, right pointer and area.\n 1. We will begin by declaring the variables, which are all 0 except right, which is going to close from the end.\n 2. While left < right, we iterate and check our positional index values.\n 2.1. If our left value is less than or equal to our right value, we will do the following:\n 2.1.1. We will update the leftmax = max(leftmax, value_at_left_index)\n 2.1.2. We will add to area: the abs(value_at_left_index - leftmax)\n 2.1.3. We will increment the right pointer.\n 2.2. If our rught value is smaller than the left, we will do the same as left, but with right values.\n 2.2.1. Update rightmax = max(rightmax, value_at_right_index)\n 2.2.2. Update the area to the abs(rightmax - value_at_right_index)\n 2.2.3. Increment the right pointer.\n 3. Return the area.\n '''\n leftmax = rightmax = left = area = 0\n right = len(height) - 1\n \n while left < right:\n if height[left] <= height[right]:\n leftmax = max(leftmax, height[left])\n area += abs(height[left] - leftmax)\n left += 1\n else:\n rightmax = max(height[right], rightmax)\n area += abs(height[right] - rightmax)\n right -= 1\n \n return area\n "} | |