| {"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"} | |