{"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< 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 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 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 "} {"blob_id": "8d37650fc1728a38f41a5e70d4a560f19eef0631", "repo_name": "perennialAutodidact/algorithms_and_data_structures", "path": "/data_structures/singly_linked_list/SLL_has_cycle.py", "length_bytes": 1000, "score": 3.8125, "int_score": 4, "content": "from SLinkedList import SLinkedList, Node\n\ndef has_cycle(head):\n slow = head\n fast = head.next\n\n # while pointers aren't None\n while slow and fast:\n\n # if the slow and fast pointers land \n # on the same node, a cycle exists\n if slow == fast:\n return True\n \n # progress the slow pointer\n slow = slow.next\n \n # if fast\n if fast.next and fast.next.next:\n fast = fast.next.next\n else:\n return False\n\n# -------------------------------------------------- #\ns = SLinkedList()\n\ns.head = Node(1)\n\nn = s.head\nfor i in range(10):\n n.next = Node(i)\n # save node to create cycle\n if i == 3:\n loop_node = n\n n = n.next\n\n# cycle last node back in list\nn.next = loop_node\n\nprint(has_cycle(s.head))\n\n# -------------------------------------------- #\ns2 = SLinkedList()\n\ns2.head = Node(0)\nn = s2.head\nfor i in range(1,11):\n n.next = Node(i)\n n = n.next\n\nprint(has_cycle(s2.head))"} {"blob_id": "cb43682f18e797ba1aa9712739a54cbb9b1e655c", "repo_name": "Wangjunling1/leetcode-learn", "path": "/python/947.py", "length_bytes": 1858, "score": 3.53125, "int_score": 4, "content": "# n \u5757\u77f3\u5934\u653e\u7f6e\u5728\u4e8c\u7ef4\u5e73\u9762\u4e2d\u7684\u4e00\u4e9b\u6574\u6570\u5750\u6807\u70b9\u4e0a\u3002\u6bcf\u4e2a\u5750\u6807\u70b9\u4e0a\u6700\u591a\u53ea\u80fd\u6709\u4e00\u5757\u77f3\u5934\u3002\n#\n# \u5982\u679c\u4e00\u5757\u77f3\u5934\u7684 \u540c\u884c\u6216\u8005\u540c\u5217 \u4e0a\u6709\u5176\u4ed6\u77f3\u5934\u5b58\u5728\uff0c\u90a3\u4e48\u5c31\u53ef\u4ee5\u79fb\u9664\u8fd9\u5757\u77f3\u5934\u3002\n#\n# \u7ed9\u4f60\u4e00\u4e2a\u957f\u5ea6\u4e3a n \u7684\u6570\u7ec4 stones \uff0c\u5176\u4e2d stones[i] = [xi, yi] \u8868\u793a\u7b2c i \u5757\u77f3\u5934\u7684\u4f4d\u7f6e\uff0c\u8fd4\u56de \u53ef\u4ee5\u79fb\u9664\u7684\u77f3\u5b50 \u7684\u6700\u5927\u6570\u91cf\u3002\n\n# \u89e3\u9898\n# \u4f7f\u7528\u5e76\u67e5\u96c6\u5b9e\u73b0\u8be5\u9898\u89e3\u91ca\n# \u5e76\u67e5\u96c6\u6a21\u7248\nclass bing:\n def __init__(self,len_list):\n self.queue=list(range(len_list))\n self.root=set()\n def find(self,index):\n if self.queue[index]!=index:\n return self.find(self.queue[index])\n else:\n return index\n def union(self,index1,index2):\n x,y=self.find(index1),self.find(index2)\n if x!=y:\n self.queue[x] = y\n else:\n\n return \"\u7236\u8282\u70b9\u76f8\u540c\"\na=[[0,1],[1,0]]\ndisjoint_set=bing(len(a))\nfor x,y in a:\n print(disjoint_set.union(x,y))\nprint(disjoint_set.queue)\nprint(disjoint_set.root)\n\n\nfor i,k in a:\n print(disjoint_set.find(i))\n\nif __name__ == '__main__':\n stones=[[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]\n parent = list(range(len(stones)))\n\n n = 10010 # \u8fd9\u91cc\u8bbe\u7f6e\u8fd9\u4e48\u591a\u662f\u4e3a\u4e86\u533a\u5206 \u4e24\u4e2a\u7236\u8282\u70b9\uff0c\u9632\u6b62 \u5408\u5e76\u65f6\u8fde\u6210\u4e00\u7247\n parent = list(range(2 * n))\n\n co=0\n # \u5e76\u67e5\u96c6\u67e5\u627e\n def findset(x):\n global co\n if parent.index(x)==parent[-1]:\n co+=1\n if x != parent[x]:\n return findset(parent[x])\n return parent[x]\n\n\n # \u5408\u5e76\n def union(i, j):\n\n parent[findset(i)] = findset(j)\n # \u8fde\u901a\u6a2a\u7eb5\u5750\u6807\n\n\n for i, j in stones:\n union(i, j + n)\n # \u83b7\u53d6\u8fde\u901a\u533a\u57df\u7684\u6839\u8282\u70b9\n root = set()\n for i, j in stones:\n root.add(findset(i))\n print( len(stones) - len(root))\n print(co)\n\n"} {"blob_id": "e64a8783941c734247b4b22b8faa21f6167e1405", "repo_name": "Nobody0321/MyCodes", "path": "/OJ/LeetCode/56. Merge Intervals.py", "length_bytes": 455, "score": 3.59375, "int_score": 4, "content": "class Solution:\n def merge(self, intervals):\n ret = []\n print(sorted(intervals, key=lambda x:x[0]))\n for each in sorted(intervals, key=lambda x:x[0]):\n print(each)\n if ret and ret[-1][1] >= each[0]:\n ret[-1][1] = max(each[1], ret[-1][1])\n else:\n ret.append(each)\n return ret\n\n\nif __name__ == \"__main__\":\n print(Solution().merge([[1,3],[2,6],[8,10],[15,18]]))"} {"blob_id": "cd45184fb2c45cb505969e02122525623fdd939f", "repo_name": "llenfan/hackerrank", "path": "/new_year_chaos.py", "length_bytes": 1189, "score": 3.6875, "int_score": 4, "content": "#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n\n# Complete the minimumBribes function below.\ndef minimumBribes(q):\n\n bribes = 0\n\n # Makes an iteration of the list until it is in order again (undoing all bribes to count them)\n while q != list(range(1, len(q) + 1)):\n\n for i, n in enumerate(q):\n\n # If the position that is being analyzed is more than two positions far from his original or\n # designated position in the queue it's automatically chaotic\n if n - (i + 1) > 2:\n print(\"Too chaotic\")\n\n return\n\n try:\n\n # If the position that is being analyzed, it is bigger than the next position,\n # the position get inverted and the bribe counter get increased.\n if q[i] > q[i + 1]:\n q[i], q[i + 1] = q[i + 1], q[i]\n\n bribes = bribes + 1\n\n except IndexError:\n pass\n print(bribes)\n\n\nif __name__ == '__main__':\n t = int(input())\n\n for t_itr in range(t):\n n = int(input())\n\n q = list(map(int, input().rstrip().split()))\n\n minimumBribes(q)\n"} {"blob_id": "93c378525593aef72ea35ed3a740b1988ea22bf6", "repo_name": "kutoga/learning2cluster", "path": "/playground/creepy_network.py", "length_bytes": 4449, "score": 3.78125, "int_score": 4, "content": "# This test is independent of the MT;-)\r\n# This code is really just to play around. It is a try to implement some neural network like thing that only operates\r\n# on boolean values (which is much faster than working with floats).\r\n\r\nimport numpy as np\r\nnp.random.seed(1)\r\n\r\n# The complete network only works with 1d data. Currently we only use {0, 1} data\r\ninput_size = 2\r\nhidden_layer_sizes = [100]\r\noutput_size = 1\r\n\r\n# We need to generate some data. et us program an xor-software\r\nx = [\r\n [0, 0], [0, 1],\r\n [1, 0], [1, 1]\r\n]\r\ny = [\r\n 0, 1, 1, 0\r\n]\r\n\r\n# That's it for now:)\r\n# First make numpy arrays:\r\nx = np.asarray(x)\r\ny = np.asarray(y)\r\n# The output layer is just another \"hidden layer\"\r\nhidden_layer_sizes.append(output_size)\r\n\r\n# Create the required weights: Every layer contains for each input neuron a weight -1, 0 or 1 and also a bias b (b may be any natural number)\r\nweights = []\r\nfor i in range(len(hidden_layer_sizes)):\r\n\r\n # Get the number of inputs for the current layer\r\n if i == 0:\r\n input_count = input_size\r\n else:\r\n input_count = hidden_layer_sizes[i - 1]\r\n\r\n # Create a weight matrix (input_count, output_count) and a bias matrix\r\n # The weights are random initialized (-1, 0, 1), except for the bias: It is 0\r\n\r\n w = np.random.randint(-3, 4, (input_count, hidden_layer_sizes[i]))\r\n b = np.zeros((hidden_layer_sizes[i],), dtype=np.int32)\r\n\r\n weights.append((w, b))\r\n\r\ndef get_rand_value(p):\r\n if p == 0:\r\n return 0\r\n r = np.random.uniform()\r\n result = 0\r\n if p < 0:\r\n if r < (-p):\r\n result = -1\r\n else:\r\n if r < p:\r\n result = 1\r\n return result\r\n\r\ndef get_binary_delta_weights(arr):\r\n arr = np.copy(arr)\r\n arr = np.minimum(arr, 1)\r\n arr = np.maximum(arr, -1)\r\n if len(arr.shape) == 1:\r\n for i in range(arr.shape[0]):\r\n arr[i] = get_rand_value(arr[i])\r\n elif len(arr.shape) == 2:\r\n for i in range(arr.shape[0]):\r\n for j in range(arr.shape[1]):\r\n arr[i, j] = get_rand_value(arr[i, j])\r\n return arr.astype(np.int32)\r\n\r\n# Train (we train currently record by record)\r\ntemperature = 0.5\r\nfor i in range(100):\r\n wrong = 0\r\n w, b = weights[-1]\r\n\r\n w_d = np.zeros_like(w, dtype=np.float32)\r\n b_d = np.zeros_like(b, dtype=np.float32)\r\n for i in range(x.shape[0]):\r\n x_i = x[i]\r\n y_i = y[i]\r\n\r\n # Do the forward pass\r\n curr_v = x_i\r\n for j in range(len(hidden_layer_sizes)):\r\n (w_j, b_j) = weights[j]\r\n\r\n curr_v = np.dot(curr_v, w_j) + b_j\r\n\r\n # Execute the activation:\r\n curr_v[curr_v >= 0] = 1\r\n curr_v[curr_v < 0] = 0\r\n curr_y = curr_v\r\n\r\n # Compare x_i and y_i and backpropagate the error\r\n d0 = y_i - curr_y\r\n\r\n # For each y value that is excat we backpropagate nothing; for each which is too high we try to decrease the input\r\n # weights with a probability of temperature and we also try to decrease the bias (by 1) with the same probability.\r\n # The abs(bias) is equal to (the number of input neurons + 1).\r\n\r\n layer_temperature = temperature\r\n\r\n # Store the probability to increase a value from a previous layer:\r\n increase_w_p = np.zeros((hidden_layer_sizes[-1],), dtype=np.float32)\r\n increase_b_p = np.zeros(())\r\n\r\n if np.sum(np.abs(d0)) > 0:\r\n wrong += 1\r\n\r\n print(\"temperature={}\".format(temperature))\r\n for j in range(d0.shape[0]):\r\n dj = d0[j]\r\n\r\n # Try to increase the current weights\r\n w_d[:, j] += d0[j] * w[:, j] * layer_temperature\r\n\r\n # Try to increase the current bias\r\n b_d[j] += d0[j] * layer_temperature\r\n\r\n # Backpropagate the error\r\n\r\n # Create a mask for the input weights\r\n # increase_w_p += d0[j] * w[:, j]\r\n\r\n bdw = get_binary_delta_weights(w_d)\r\n w += bdw\r\n w = np.minimum(w, 3)\r\n w = np.maximum(w, -3)\r\n bdb = get_binary_delta_weights(b_d)\r\n b += bdb\r\n b_max = hidden_layer_sizes[-1] + 1\r\n b = np.minimum(b, b_max)\r\n b = np.maximum(b, -b_max)\r\n print(\"sum(bdw)={}, sum(bdb)={}\".format(np.sum(np.abs(bdw)), np.sum(np.abs(bdb))))\r\n\r\n weights[-1] = (w, b)\r\n\r\n temperature *= 0.95\r\n if temperature < .5:\r\n temperature = .5\r\n\r\n print(\"Error: {}\".format(wrong / x.shape[0]))\r\n print()\r\n\r\n\r\n"} {"blob_id": "2c6c40847ef4419d0c74e6f8d56bdcfdef9cefc4", "repo_name": "kunalJa/leetcodeforces-etc", "path": "/LeetCode/medium/958_check_completeness_of_a_binary_tree.py", "length_bytes": 1992, "score": 4.03125, "int_score": 4, "content": "\"\"\"\nhttps://leetcode.com/problems/check-completeness-of-a-binary-tree/\n\nGiven a binary tree, determine if it is a complete binary tree.\n\nIn a complete binary tree every level, except possibly the last, is completely filled,\nand all nodes in the last level are as far left as possible.\nIt can have between 1 and 2h nodes inclusive at the last level h.\n\"\"\"\n\n\"\"\"\nAccepted\nTime Complexity: O(n)\nSpace Complexity: O(n)\nSolution Explanation:\n BFS.\n Keep track that you always pop left then right from the same parent.\n If ever you skip a parent on the same level, then the tree is not complete.\n If ever you pop a right node first, then the tree is not complete.\n\"\"\"\n\nfrom collections import deque\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\n\nclass Solution:\n def isCompleteTree(self, root: TreeNode) -> bool:\n children = deque()\n children.append(root)\n while children:\n next_level = []\n while children: # Distinguish between levels of the tree\n current = children.popleft()\n if current is None:\n if len(children) > 0:\n return False\n # This for loop runs only once- the runtime does not become quadratic.\n for val in next_level:\n if val is not None:\n return False\n return True\n\n next_level.append(current.left)\n next_level.append(current.right)\n\n flag = False\n for node in next_level:\n if node is not None:\n if flag:\n return False\n children.append(node)\n else:\n if not flag:\n children.append(None)\n flag = True\n\n return True\n"} {"blob_id": "c9cbf5e1efbad21468e3d78508e7da1151ed122b", "repo_name": "reillydj/ProjectEuler", "path": "/problem_seven.py", "length_bytes": 797, "score": 3.90625, "int_score": 4, "content": "__author__ = \"David Reilly\"\n\n\"\"\"\n Project Euler\n Problem: 7\n\n 'By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.\n\n What is the 10 001st prime number?'\n\"\"\"\nimport math\n\ndef is_prime(integer):\n\n if integer == 2:\n return True\n for candidate in xrange(2, int(math.ceil(integer ** 0.5)) + 1):\n\n if integer % float(candidate) == 0:\n return False\n\n return True\n\ndef generate_primes(nth_prime):\n\n index = 1\n number = 2\n while index <= nth_prime:\n print number, is_prime(number), index\n if is_prime(number):\n index += 1\n number += 1\n else:\n number += 1\n\n return number\n\nif __name__ == \"__main__\":\n\n prime = generate_primes(10001)\n print prime\n"} {"blob_id": "a51dff73c16188226a01f2ce9ff02cff5bd2da5a", "repo_name": "chisness/aipoker", "path": "/ttt.py", "length_bytes": 2117, "score": 3.59375, "int_score": 4, "content": "from typing import List, Optional, Dict\nfrom abc import ABC, abstractmethod\n\n\nclass GamePosition(ABC):\n @abstractmethod\n def value(self) -> Optional[int]:\n pass\n\n @abstractmethod\n def player(self) -> int:\n pass\n\n @abstractmethod\n def available_moves(self) -> List['GamePosition']:\n pass\n\n\nclass TicTacToe(GamePosition):\n def __init__(self, positions: List[int], curplayer: int) -> None:\n self.positions = tuple(positions)\n self.curplayer = curplayer\n\n def __repr__(self) -> str:\n return f\"({self.positions}, {self.curplayer})\"\n\n def __hash__(self) -> int:\n return hash(repr(self))\n\n def __eq__(self, another: object) -> bool:\n return repr(self) == repr(another)\n\n def value(self) -> Optional[int]:\n for (a, b, c) in [(0, 1, 2), (3, 4, 5), (6, 7, 8),\n (0, 3, 6), (1, 4, 7), (2, 5, 8),\n (0, 4, 8), (2, 4, 6)]:\n if self.positions[a] == self.positions[b] == self.positions[c] != 0:\n return self.positions[a]\n if all(x != 0 for x in self.positions):\n return 0\n return None\n\n def available_moves(self) -> List['TicTacToe']: # type: ignore\n res = []\n for i in range(9):\n t = list(self.positions)\n if t[i] == 0:\n t[i] = self.curplayer\n res.append(TicTacToe(t, 0-self.curplayer))\n return res\n\n def player(self) -> int:\n return self.curplayer\n\n\nclass MinMaxSearch:\n def __init__(self):\n self.memo: Dict[GamePosition, int] = {}\n\n def find_value(self, state: GamePosition):\n if state not in self.memo:\n val = state.value()\n if val is None:\n val = max(self.find_value(s) * state.player() for s in state.available_moves())\n self.memo[state] = val * state.player()\n else:\n self.memo[state] = val\n return self.memo[state]\n\n\nif __name__ == \"__main__\":\n mms = MinMaxSearch()\n print(mms.find_value(TicTacToe([0, 0, 0, 0, 0, 0, 0, 0, 0], 1)))"} {"blob_id": "16cfc5f6d1bebd9a26135a931a5cb9e12b02d3ce", "repo_name": "kshimo69/euler", "path": "/euler12.py", "length_bytes": 1517, "score": 4.03125, "int_score": 4, "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nclass Triangle(object):\n \"\"\"\n f(T1) = f(1) * f(2/2) => 1(1)\n f(T2) = f(2/2) * f(3) => 2(1,2)\n f(T3) = f(3) * f(4/2) => 4(1,2,3,6)\n f(T4) = f(4/2) * f(5) => 4(1,2,5,10)\n f(T5) = f(5) * f(6/2) => 4(1,3,5,15)\n f(T6) = f(6/2) * f(7) => 4(1,3,7,21)\n f(T7) = f(7) * f(7/2) => 6(1,2,4,7,14,28)\n \n non even number: f(n) * f((n+1)/2)\n even number : f(n/2) * f(n+1)\n \"\"\"\n def __init__(self):\n self.prime = {1:1, 2:2, 3:2, 4:3}\n\n def get_triangle(self, n):\n \"\"\" return Nth triangle number\n \n Tn = n * (n + 1) / 2\n \"\"\"\n return n * (n + 1) / 2\n\n def search_divisors(self, n):\n count = 0\n for i in range(1, n + 1):\n if n % i == 0:\n count += 1\n return count\n\n def get_count(self, n):\n if n in self.prime:\n #print \"f(%d) is %d\" % (n, self.prime[n])\n return self.prime[n]\n else:\n self.prime[self.get_triangle(n)] = self.search_divisors(n)\n #print \"f(%d) is %d\" % (n, self.prime[self.get_triangle(n)])\n return self.prime[self.get_triangle(n)]\n\n def count_divisors(self, n):\n if n % 2 != 0:\n return self.get_count(n) * self.get_count((n+1)/2)\n else:\n return self.get_count(n/2) * self.get_count(n+1)\n\ntri = Triangle()\nc = 0\ni = 1\nwhile c < 500:\n c = tri.count_divisors(i)\n i += 1\nprint \"%d, its divisors: %d\" % (tri.get_triangle(i),c)\n"} {"blob_id": "93225d89dc61ec4098bd77f66a62a71bebc4146f", "repo_name": "maruichen2004/EPI", "path": "/Binary Search Tree/FindKLargestBST.py", "length_bytes": 624, "score": 3.640625, "int_score": 4, "content": "from Util.BinaryTree import TreeNode\nfrom Util.BinaryTree import BinaryTree\n\nclass Solution:\n # Time: O(n)\n # Space: O(h)\n def findKLargestBST(self, root, k):\n res = []\n self.findKLargestBSTHelper(root, k, res)\n return res\n\n def findKLargestBSTHelper(self, root, k, res):\n if root and len(res) < k:\n self.findKLargestBSTHelper(root.right, k, res)\n if len(res) < k:\n res.append(root.val)\n self.findKLargestBSTHelper(root.left, k, res)\n\nif __name__ == \"__main__\":\n tree = BinaryTree()\n t = Solution()\n k = 5\n print t.findKLargestBST(tree.getRoot(), k)\n"} {"blob_id": "b6dbb2ce166a364aba1d21cef86ce8e16211eff4", "repo_name": "lyjeff/Machine-Learning-Class", "path": "/hw1-Perceptron/hw1-1.py", "length_bytes": 1593, "score": 3.71875, "int_score": 4, "content": "import numpy as np\n\nfrom utils import (\n PLA, build_data,\n verification, plt_proc\n)\n\ndef PLA_3_times_with_30_data(m, b, num, times):\n # build 2D data\n x, y = build_data(m, b, num)\n\n #initial weight w = (0, 0, 0)\n w = np.zeros([1,3])\n\n # count the iteration total numbers\n iteration_count = 0\n\n # initial the figure\n plt_fig = plt_proc(x, num, title=\"HW1-1: PLA with 30 2D data samples\")\n\n # plot the sample line equation\n plt_fig.add_line(\n w=None,\n m=m,\n b=b,\n num=num,\n iteration=None,\n label=f\"Benchmark\",\n txt=\"\"\n )\n\n for i in range(times):\n\n # run PLA algorithm\n w_result, iteration = PLA(x, y, w, num)\n\n # verify the line equation\n verification(x, y, w_result, num, iteration, show=True)\n\n # count the total number of iterations\n iteration_count += iteration\n\n # plot the line equation\n plt_fig.add_line(\n w=w_result,\n m=None,\n b=None,\n num=num,\n iteration=iteration,\n label=f\"{i}\",\n txt=f\", iteration = {iteration}\"\n )\n\n print(f\"Avg. Iteration = {iteration_count/3:.3f}\")\n\n # save and show the figure\n plt_fig.save_and_show(\n itr_avg=iteration_count / 3,\n filename='hw1-1.png',\n avg_show=True\n )\n\nif __name__ == '__main__':\n \n # y = m * x + b\n m = 1\n b = 2\n \n # default number of data = 30\n num = 30\n \n # set the running times of PLA\n times = 3\n\n PLA_3_times_with_30_data(m, b, num, times)"} {"blob_id": "2977af25235183b601155c4059ba4100faa3aec1", "repo_name": "EmperorEuler/leetcode", "path": "/\u6570\u7ec4/[118]\u6768\u8f89\u4e09\u89d2.py", "length_bytes": 1199, "score": 3.53125, "int_score": 4, "content": "# \u7ed9\u5b9a\u4e00\u4e2a\u975e\u8d1f\u6574\u6570 numRows\uff0c\u751f\u6210\u300c\u6768\u8f89\u4e09\u89d2\u300d\u7684\u524d numRows \u884c\u3002 \n# \n# \u5728\u300c\u6768\u8f89\u4e09\u89d2\u300d\u4e2d\uff0c\u6bcf\u4e2a\u6570\u662f\u5b83\u5de6\u4e0a\u65b9\u548c\u53f3\u4e0a\u65b9\u7684\u6570\u7684\u548c\u3002 \n# \n# \n# \n# \n# \n# \u793a\u4f8b 1: \n# \n# \n# \u8f93\u5165: numRows = 5\n# \u8f93\u51fa: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]\n# \n# \n# \u793a\u4f8b 2: \n# \n# \n# \u8f93\u5165: numRows = 1\n# \u8f93\u51fa: [[1]]\n# \n# \n# \n# \n# \u63d0\u793a: \n# \n# \n# 1 <= numRows <= 30 \n# \n# Related Topics \u6570\u7ec4 \u52a8\u6001\u89c4\u5212 \ud83d\udc4d 600 \ud83d\udc4e 0\n\n\n\"\"\"\n\u89c2\u5bdf\u89c4\u5f8b\uff1a\u5148\u751f\u6210\u5bf9\u5e94\u884c\u6570, \u884c\u9996\u548c\u884c\u672b\u90fd\u662f1, \u4f9d\u7136\u7528\u4e0a\u4e00\u884c\u7684\u4e24\u4e2a\u90bb\u4f4d\u6c42\u548c\u586b\u5145\u6700\u65b0\u7684\u7a7a\u683c\n\"\"\"\n\n\n# leetcode submit region begin(Prohibit modification and deletion)\nclass Solution:\n def generate(self, numRows: int) -> List[List[int]]:\n res = []\n cnt = 1\n while cnt <= numRows:\n res.append([1] * cnt)\n cnt += 1\n for i in range(2, numRows):\n for i2 in range(1, i):\n res[i][i2] = res[i-1][i2-1] + res[i-1][i2]\n return res\n# leetcode submit region end(Prohibit modification and deletion)\n\n\n\"\"\"\n\u89e3\u7b54\u6210\u529f:\n\u6267\u884c\u8017\u65f6:40 ms,\u51fb\u8d25\u4e8611.20% \u7684Python3\u7528\u6237\n\u5185\u5b58\u6d88\u8017:14.7 MB,\u51fb\u8d25\u4e8697.27% \u7684Python3\u7528\u6237\n\"\"\"\n"} {"blob_id": "2355ee5a02dcbc66d33649b618d1c57e356e9ada", "repo_name": "jamj2000/Programming-Classes", "path": "/Math You Will Actually Use/Week6_Sympy.py", "length_bytes": 725, "score": 4.3125, "int_score": 4, "content": "' \"pip install sympy\" before you do any of this '\n\nimport sympy # import the calculator with variable buttons :)\nfrom sympy import Symbol\n\n# -------------------------- first, solve the simple equation 2*x=2\nx = Symbol('x') # create a \"symoblic variable\" x\n\nequation = 2*x - 2 # define the equation 2*x = 2\n\nsolution = sympy.solve(equation, x) # solve for x\n\nprint(solution) # print the list of all solutions\n\n# -------------------------- next, lets do the equation of a circle\ny = Symbol('y')\n\nequation = x**2 + y**2 - 1**2 # x**2 + y**2 = r**2 where r =1\n\nsolution = sympy.solve(equation, y) # solve for y\n\nprint(solution)\n\n# notice how one is the TOP half of the circle\n# and the other in the list is the BOTTOM half\n"} {"blob_id": "42b3c176483c9a5b7143fa51a88a0ffe2522b4ae", "repo_name": "martinchristen/pyRT", "path": "/pyrt/geometry/triangle.py", "length_bytes": 10928, "score": 3.65625, "int_score": 4, "content": "\"\"\"\nThis is the geometric object triangle\n\n(renderable object)\n\"\"\"\n\nfrom ..geometry import Shape, Vertex\nfrom ..material import PhongMaterial, TextureMaterial, NormalMappedMaterial\nfrom ..math import *\n\n\nclass Triangle(Shape):\n\n \"\"\"Triangle class for raytracing\"\"\"\n\n def __init__(self, a: Vertex, b: Vertex, c: Vertex, material=PhongMaterial()):\n if type(a) != Vertex or type(b) != Vertex or type(c) != Vertex:\n raise ValueError(\"Please initialize Triangle with 3x Vertex\")\n Shape.__init__(self, \"Triangle\")\n self.a = a\n self.b = b\n self.c = c\n self.material = material\n self.EPSILON = 0.000001\n\n def __str__(self):\n return \"\u25b3ABC: Position[\" + str(self.a.position) + \", \" + str(self.b.position) + \", \" + str(\n self.c.position) + \"]\"\n\n # ------------------------------------------------------------------------------------------------------------------\n def area(self) -> float:\n \"\"\"\n Calculate area of triangle\n :return: area\n \"\"\"\n return cross3(self.b.position - self.a.position,\n self.c.position - self.a.position).length() / 2.0\n\n # ------------------------------------------------------------------------------------------------------------------\n def toBarycentric(self, p: Vec3) -> Vec3:\n \"\"\"\n Calculate barycentric coordinate of point p\n :param P: the input point (cartesian)\n :return: barycentric coordinate\n \"\"\"\n abc = triangleArea(self.a.position, self.b.position, self.c.position)\n pbc = triangleArea(p, self.b.position, self.c.position)\n apc = triangleArea(self.a.position, p, self.c.position)\n\n if abc == 0.0:\n return Vec3(0, 0, 0)\n\n x = pbc / abc\n y = apc / abc\n return Vec3(x, y, 1.0 - x - y)\n\n # ------------------------------------------------------------------------------------------------------------------\n def fromBarycentric(self, b: Vec3) -> Vec3:\n \"\"\"\n Calculate cartesian coordinate from barycentric coordinate\n :param b: barycentric coordinate\n :return: cartesian coordinate\n \"\"\"\n return self.a.position * b.x + self.b.position * b.y + self.c.position * b.z\n\n # ------------------------------------------------------------------------------------------------------------------\n def circumradius(self) -> float:\n a = (self.c.position - self.b.position).length()\n b = (self.c.position - self.a.position).length()\n c = (self.b.position - self.a.position).length()\n\n s = (a + b + c) / 2.0 # semiperimeter\n z = a * b * c\n n = 4.0 * math.sqrt(s * (a + b - s) * (a + c - s) * (b + c - s))\n if n == 0.0:\n return 0.0\n return z / n\n\n # ------------------------------------------------------------------------------------------------------------------\n def inradius(self) -> float:\n a = (self.c.position - self.b.position).length()\n b = (self.c.position - self.a.position).length()\n c = (self.b.position - self.a.position).length()\n s = (a + b + c) / 2.0\n if s == 0.0:\n return 0.0\n return math.sqrt((s - a) * (s - b) * (s - c) / s)\n\n # ------------------------------------------------------------------------------------------------------------------\n def circumcenter(self) -> Vec3:\n a = (self.c.position - self.b.position).length()\n b = (self.c.position - self.a.position).length()\n c = (self.b.position - self.a.position).length()\n q = a * a * (-a * a + b * b + c * c)\n w = b * b * (a * a - b * b + c * c)\n e = c * c * (a * a + b * b - c * c)\n n = q + w + e\n if n == 0.0:\n return Vec3(0, 0, 0)\n return self.fromBarycentric(Vec3(q / n, w / n, e / n))\n\n # ------------------------------------------------------------------------------------------------------------------\n def incenter(self) -> Vec3:\n a = (self.c.position - self.b.position).length()\n b = (self.c.position - self.a.position).length()\n c = (self.b.position - self.a.position).length()\n n = a + b + c\n if n == 0.0:\n return Vec3(0, 0, 0)\n\n return self.fromBarycentric(Vec3(a / n, b / n, c / n))\n\n # ------------------------------------------------------------------------------------------------------------------\n def centroid(self) -> Vec3:\n return (self.a.position + self.b.position + self.c.position) / 3.0\n\n # ------------------------------------------------------------------------------------------------------------------\n def calcTexcoord(self, p: Vec3) -> Vec2:\n \"\"\"\n Returns texture-coordinate at cartesian position p\n :param p:\n :return: returns\n \"\"\"\n pb = self.toBarycentric(p)\n u = self.a.texcoord.x * pb.x + self.b.texcoord.x * pb.y + self.c.texcoord.x * pb.z\n v = self.a.texcoord.y * pb.x + self.b.texcoord.y * pb.y + self.c.texcoord.y * pb.z\n return Vec2(u, v)\n\n # ------------------------------------------------------------------------------------------------------------------\n\n def hit(self, ray: Ray, hitrecord: HitRecord) -> bool:\n \"\"\"\n Ray Triangle Intersection\n Original Code from:\n \"Practical Analysis of Optimized Ray-Triangle Intersection\"\n Tomas M\u00f6ller\n Department of Computer Engineering, Chalmers University of Technology, Sweden.\n http://fileadmin.cs.lth.se/cs/Personal/Tomas_Akenine-Moller/raytri/\n\n :param ray: the ray to check hit\n :param tmin: tmin to test intersection\n :param tmax: tmax to test intersection\n :param hitrecord: the hitrecord which is only valid if there is a hit\n :return: True if there is a hit\n \"\"\"\n t0 = hitrecord.t\n\n # find vectors for two edges sharing vert0\n edge1 = self.b.position - self.a.position\n edge2 = self.c.position - self.a.position\n\n # begin calculating determinant - also used to calculate U parameter\n pvec = cross3(ray.direction, edge2)\n\n # if determinant is near zero, ray lies in plane of triangle\n det = dot3(edge1, pvec)\n\n if det > self.EPSILON:\n tvec = ray.start - self.a.position\n u = dot3(tvec, pvec)\n if u < 0.0 or u > det:\n return False\n\n qvec = cross3(tvec, edge1)\n v = dot3(ray.direction, qvec)\n if v < 0.0 or u + v > det:\n return False\n elif det < -self.EPSILON:\n tvec = ray.start - self.a.position\n u = dot3(tvec, pvec)\n if u > 0.0 or u < det:\n return False\n\n qvec = cross3(tvec, edge1)\n v = dot3(ray.direction, qvec)\n if v > 0.0 or u + v < det:\n return False\n else:\n return False\n\n inv_det = 1.0 / det\n t = dot3(edge2, qvec) * inv_det\n u *= inv_det\n v *= inv_det\n\n if t0 is not None and t > t0:\n return False\n\n if t > 0.0: # and t bool:\n \"\"\"\n :param ray:\n :param tmin:\n :param tmax:\n :return:\n \"\"\"\n # find vectors for two edges sharing vert0\n edge1 = self.b.position - self.a.position\n edge2 = self.c.position - self.a.position\n\n # begin calculating determinant - also used to calculate U parameter\n pvec = cross3(ray.direction, edge2)\n\n # if determinant is near zero, ray lies in plane of triangle\n det = dot3(edge1, pvec)\n\n if det > self.EPSILON:\n tvec = ray.start - self.a.position\n u = dot3(tvec, pvec)\n if u < 0.0 or u > det:\n return False\n\n qvec = cross3(tvec, edge1)\n v = dot3(ray.direction, qvec)\n if v < 0.0 or u + v > det:\n return False\n elif det < -self.EPSILON:\n tvec = ray.start - self.a.position\n u = dot3(tvec, pvec)\n if u > 0.0 or u < det:\n return False\n\n qvec = cross3(tvec, edge1)\n v = dot3(ray.direction, qvec)\n if v > 0.0 or u + v < det:\n return False\n else:\n return False\n\n inv_det = 1.0 / det\n t = dot3(edge2, qvec) * inv_det\n u *= inv_det\n v *= inv_det\n\n if t > 0.0:\n return True\n\n return False\n\n\n def getBBox(self):\n \"\"\"\n Retrieve axis aligned bounding box of the triangle\n\n :return: bounding box\n \"\"\"\n xmin = min(self.a.position.x, self.b.position.x, self.c.position.x)\n ymin = min(self.a.position.y, self.b.position.y, self.c.position.y)\n zmin = min(self.a.position.z, self.b.position.z, self.c.position.z)\n\n xmax = max(self.a.position.x, self.b.position.x, self.c.position.x)\n ymax = max(self.a.position.y, self.b.position.y, self.c.position.y)\n zmax = max(self.a.position.z, self.b.position.z, self.c.position.z)\n\n return BBox(Vec3(xmin, ymin, zmin), Vec3(xmax, ymax, zmax))\n\n\n def getCentroid(self) -> Vec3:\n \"\"\"\n Retrieve center of triangle\n :return:\n \"\"\"\n return self.centroid()\n\n def getSurfaceArea(self) -> float:\n \"\"\"\n Retrieve Surface area of Triangle\n\n :return: surface area\n \"\"\"\n return self.area()\n\n\n\n\n# ----------------------------------------------------------------------------------------------------------------------\n# Utility functions related to triangles\n\ndef triangleArea(a: Vec3, b: Vec3, c: Vec3) -> float:\n \"\"\"\n Calculate area of triangle\n :return: area\n \"\"\"\n return cross3(b - a, c - a).length() / 2.0\n"} {"blob_id": "dbf005e674eeec4d1d02c7b83cbbfa12d8ae7f6f", "repo_name": "yennanliu/CS_basics", "path": "/leetcode_python/Dynamic_Programming/flip-string-to-monotone-increasing.py", "length_bytes": 5691, "score": 3.8125, "int_score": 4, "content": "\"\"\"\n\n926. Flip String to Monotone Increasing\nMedium\n\nA binary string is monotone increasing if it consists of some number of 0's (possibly none), followed by some number of 1's (also possibly none).\n\nYou are given a binary string s. You can flip s[i] changing it from 0 to 1 or from 1 to 0.\n\nReturn the minimum number of flips to make s monotone increasing.\n\n \n\nExample 1:\n\nInput: s = \"00110\"\nOutput: 1\nExplanation: We flip the last digit to get 00111.\nExample 2:\n\nInput: s = \"010110\"\nOutput: 2\nExplanation: We flip to get 011111, or alternatively 000111.\nExample 3:\n\nInput: s = \"00011000\"\nOutput: 2\nExplanation: We flip to get 00000000.\n \n\nConstraints:\n\n1 <= s.length <= 105\ns[i] is either '0' or '1'.\n\n\"\"\"\n\n# V0\nclass Solution:\n def minFlipsMonoIncr(self, s):\n ones = 0\n \"\"\"\n NOTE !!! :\n -> assume all element in s is \"0\"\n -> then we adjust this hypothesis below\n\n ones : # of ones on [:k]\n zeros : # of zero on [k+1:]\n \"\"\"\n res = zeros = s.count(\"0\")\n # go through s\n for c in s:\n \"\"\"\n case 1) if current c == \"1\"\n -> all right MUST be current zeros\n -> while left ones need to plus 1\n \"\"\"\n if c == \"1\":\n ones, zeros = (ones + 1, zeros)\n # \"\"\"\n # case 2) if current c == \"0\"\n # -> all right MUST be current - 1 zeros\n # -> while left ones be the same\n # \"\"\"\n else:\n ones, zeros = (ones, zeros - 1)\n \"\"\"\n NOTE : the op (flip) we need to take :\n -> num(ones) + nums(zeros)\n since we ones \"1\" on [:k] and zeros on [k+1:]\n -> so in order to make the string \"Monotone Increasing\"\n -> we need to \n -> flip \"1\" on [:k] to \"0\"\n -> flip \"0\" in [k+1:] to \"1\"\n\n -> so (ones + zeros) op\n \"\"\"\n res = min(res, ones + zeros)\n return res\n\n# V0' \n# IDEA : PREFIX SUM\nclass Solution(object):\n def minFlipsMonoIncr(self, S):\n # get pre-fix sum\n P = [0]\n for x in S:\n P.append(P[-1] + int(x))\n # find min\n res = float('inf')\n for j in range(len(P)):\n res = min(res, P[j] + len(S)-j-(P[-1]-P[j]))\n return res\n\n# V0''\nclass Solution:\n def minFlipsMonoIncr(self, s, ones = 0):\n res = zeros = s.count(\"0\")\n for c in s:\n ones, zeros = (ones + 1, zeros) if c == \"1\" else (ones, zeros - 1)\n res = min(res, ones + zeros)\n return res\n\n# V1\n# IDEA : PREFIX SUM\n# https://leetcode.com/problems/flip-string-to-monotone-increasing/solution/\nclass Solution(object):\n def minFlipsMonoIncr(self, S):\n # get pre-fix sum\n P = [0]\n for x in S:\n P.append(P[-1] + int(x))\n # return min\n return min(P[j] + len(S)-j-(P[-1]-P[j])\n for j in range(len(P)))\n\n# V1'\n# https://blog.csdn.net/fuxuemingzhu/article/details/83247054\nclass Solution(object):\n def minFlipsMonoIncr(self, S):\n \"\"\"\n :type S: str\n :rtype: int\n \"\"\"\n N = len(S)\n P = [0] # how many ones\n res = float('inf')\n for s in S:\n P.append(P[-1] + int(s))\n return min(P[i] + (N - P[-1]) - (i - P[i]) for i in range(len(P)))\n \n# V1''\n# https://leetcode.com/problems/flip-string-to-monotone-increasing/discuss/184080/Python-3-liner\n# IDEA\n# We start with assuming \"111..\" section occupies all string, s.\n# Then we update \"000..\" section as s[:i + 1] and \"111..\" section as s[i + 1:] during iteration as well as the result\n# \"zeros\" variable counts all misplaced \"0\"s and \"ones\" variable counts all misplaced \"1\"s\nclass Solution:\n def minFlipsMonoIncr(self, s, ones = 0):\n res = zeros = s.count(\"0\")\n for c in s:\n ones, zeros = (ones + 1, zeros) if c == \"1\" else (ones, zeros - 1)\n res = min(res, ones + zeros)\n return res\n\n# V1'''\n# https://leetcode.com/problems/flip-string-to-monotone-increasing/discuss/184080/Python-3-liner\n# IDEA :\n# -> We start with assuming \"111..\" section occupies all string, s.\n# -> Then we update \"000..\" section as s[:i + 1] and \"111..\" section as s[i + 1:] during iteration as well as the result\n# -> \"zeros\" variable counts all misplaced \"0\"s and \"ones\" variable counts all misplaced \"1\"s\nclass Solution:\n def minFlipsMonoIncr(self, s):\n res = cur = s.count(\"0\")\n for c in s:\n cur = cur + 1 if c == \"1\" else cur - 1\n res = min(res, cur)\n return res\n\n# V1'''''\n# https://leetcode.com/problems/flip-string-to-monotone-increasing/discuss/184080/Python-3-liner\nclass Solution:\n def minFlipsMonoIncr(self, s):\n res = cur = s.count(\"0\")\n for c in s: res, cur = c == \"1\" and (res, cur + 1) or (min(res, cur - 1), cur - 1)\n return res\n\n# V1''''''\n# https://www.jiuzhang.com/solution/flip-string-to-monotone-increasing/#tag-highlight-lang-python\nclass Solution:\n \"\"\"\n @param S: a string\n @return: the minimum number\n \"\"\"\n def minFlipsMonoIncr(self, S):\n # Write your code here.\n m, n = 0, 0\n for s in S:\n m += int(s)\n n = min(m, n + 1 - int(s))\n return n\n\n# V2\n# Time: O(n)\n# Space: O(1)\nclass Solution(object):\n def minFlipsMonoIncr(self, S):\n \"\"\"\n :type S: str\n :rtype: int\n \"\"\"\n flip0, flip1 = 0, 0\n for c in S:\n flip0 += int(c == '1')\n flip1 = min(flip0, flip1 + int(c == '0'))\n return flip1"} {"blob_id": "0f0887cc93752f387f2c7887d749e4ac721de72a", "repo_name": "cukejianya/leetcode", "path": "/linked_list/reverse_linked_list.py", "length_bytes": 884, "score": 3.78125, "int_score": 4, "content": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n def reverseList(self, head):\n if head == None:\n return None\n return self.reverseListRecur(head)[0]\n\n def reverseListRecur(self, head):\n if head.next == None:\n return (head, None)\n (new_head, tail) = self.reverseListRecur(head.next)\n if tail:\n tail.next = head\n else:\n new_head.next = head\n \n tail = head\n tail.next = None\n\n return (new_head, tail)\n\n def reverseListIter(self, head):\n curr = head\n head = None\n while curr != None:\n next_node = curr.next\n curr.next = head\n head = curr\n curr = next_node\n \n return head\n \n"} {"blob_id": "0f15f34d5bf4bd3ea64995f3252d8a0c43926232", "repo_name": "zhcHoward/Advent_of_Code", "path": "/Day13/part1.py", "length_bytes": 3079, "score": 3.96875, "int_score": 4, "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom collections import deque\nfrom operator import attrgetter\nfrom typing import Deque\n\nfrom utils import read_input\n\n\nclass Direction:\n UP = \"^\"\n DOWN = \"v\"\n LEFT = \"<\"\n RIGHT = \">\"\n\n\ndef turn_left(direction):\n if direction == Direction.DOWN:\n return Direction.RIGHT\n if direction == Direction.RIGHT:\n return Direction.UP\n if direction == Direction.UP:\n return Direction.LEFT\n return Direction.DOWN\n\n\ndef turn_right(direction):\n if direction == Direction.DOWN:\n return Direction.LEFT\n if direction == Direction.RIGHT:\n return Direction.DOWN\n if direction == Direction.UP:\n return Direction.RIGHT\n return Direction.UP\n\n\nclass Cart(object):\n def __init__(self, x, y, direction):\n self.x = x\n self.y = y\n self.direction = direction\n self.num_cross = 0\n\n def move(self):\n if self.direction == Direction.UP:\n self.y -= 1\n elif self.direction == Direction.DOWN:\n self.y += 1\n elif self.direction == Direction.LEFT:\n self.x -= 1\n else:\n self.x += 1\n\n if road_map[self.y][self.x] in (\"|\", \"-\"):\n return\n elif road_map[self.y][self.x] == \"/\":\n if self.direction in (Direction.UP, Direction.DOWN):\n self.direction = turn_right(self.direction)\n else:\n self.direction = turn_left(self.direction)\n elif road_map[self.y][self.x] == \"\\\\\":\n if self.direction in (Direction.UP, Direction.DOWN):\n self.direction = turn_left(self.direction)\n else:\n self.direction = turn_right(self.direction)\n else: # road_map[self.y][self.x] == '+'\n if self.num_cross == 0:\n self.direction = turn_left(self.direction)\n elif self.num_cross == 1:\n pass\n else:\n self.direction = turn_right(self.direction)\n self.num_cross = (self.num_cross + 1) % 3\n\n def __eq__(self, other): # for in operator\n return self.x == other.x and self.y == other.y\n\n def __repr__(self):\n return f\"({self.x}, {self.y}, {self.direction})\"\n\n\nraw = read_input(__file__)\nroad_map = []\ncarts: Deque[Cart] = deque([])\nfor y, line in enumerate(raw.splitlines()):\n row = []\n for x, char in enumerate(line):\n if char in (Direction.UP, Direction.DOWN):\n row.append(\"|\")\n carts.append(Cart(x, y, char))\n elif char in (Direction.LEFT, Direction.RIGHT):\n row.append(\"-\")\n carts.append(Cart(x, y, char))\n else:\n row.append(char)\n road_map.append(row)\n\n\ncrash = None\ncart_num = len(carts)\nwhile not crash:\n for _ in range(cart_num):\n cart = carts.popleft()\n cart.move()\n if cart in carts:\n crash = (cart.x, cart.y)\n break\n\n carts.append(cart)\n else:\n carts = deque(sorted(carts, key=attrgetter(\"y\", \"x\")))\n\nprint(crash)\n"} {"blob_id": "deefa01ac0ab3c0e80a00f0c963e61f8bd0281cf", "repo_name": "huangyingw/Leetcode-Python", "path": "/47.py", "length_bytes": 735, "score": 3.625, "int_score": 4, "content": "'''\nTime complexity: O(N*N!)\n'''\nfrom collections import defaultdict\n\n\nclass Solution:\n def permuteUnique(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[List[int]]\n \"\"\"\n nums.sort()\n ret = []\n used = defaultdict(lambda: False)\n self.dfs(nums, ret, [], used)\n return ret\n\n def dfs(self, nums, ret, permutation, used):\n if len(nums) == len(permutation):\n ret.append(permutation)\n for i in range(len(nums)):\n if used[i]: continue\n if i > 0 and nums[i] == nums[i - 1] and not used[i - 1]: continue\n used[i] = True\n self.dfs(nums, ret, permutation + [nums[i]], used)\n used[i] = False"} {"blob_id": "a1d31b32e70f7e324a2de098967f7cd113081264", "repo_name": "monpro/algorithm", "path": "/src/contest/169/all-elements-in-two-binary-search-trees-1305.py", "length_bytes": 1402, "score": 3.78125, "int_score": 4, "content": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]:\n queue_1 = []\n queue_2 = []\n result = []\n self.inorder(root1, queue_1)\n self.inorder(root2, queue_2)\n \n while len(queue_1) > 0 or len(queue_2) > 0:\n if len(queue_1) == 0:\n result.append(queue_2.pop(0))\n \n elif len(queue_2) == 0:\n result.append(queue_1.pop(0))\n else:\n if queue_1[0] > queue_2[0]:\n result.append(queue_2.pop(0))\n else:\n result.append(queue_1.pop(0))\n \n return result\n \n def inorder(self, root, queue):\n if not root:\n return\n self.inorder(root.left, queue)\n queue.append(root.val)\n self.inorder(root.right, queue)\n\n def getAllElementsUsingSorted(self, root1: TreeNode, root2: TreeNode) -> List[int]:\n result = []\n def inorder(root):\n if not root:\n return \n inorder(root.left)\n result.append(root.val)\n inorder(root.right)\n inorder(root1)\n inorder(root2)\n \n return sorted(result)"} {"blob_id": "1e9925f2b8cba7763274c1badcfa9e8a846923a1", "repo_name": "ajhofmann/PyEuler", "path": "/Problems 40-49/Problem 42.py", "length_bytes": 1014, "score": 3.75, "int_score": 4, "content": "## Project Euler Problem 42:\n\n## By converting each letter in a word to a number corresponding to its alphabetical position and\n## adding these values we form a word value.\n\n## If the word value is a triangle number then we shall call the word a triangle word.\n\n## Using words.txt, a 16K text file\n## containing nearly two-thousand common English words, how many are triangle words?\n\n# Assuming the max word is 20 letters, and average word value is 13 we don't need\n# triangle numbers higher than 260. t23 = 276 so use this as a stopping point\n\ntri_nums = [int(i*(i+1)/2) for i in range(1, 24)]\n\n# dictionary of letter to char\nalphabet = {chr(i+64): i for i in range(1, 27)}\n\nfile = open(\"words.txt\", \"r\")\nwords = file.read().split(',')\n\ncount = 0\n\n# since the text file has quotes around words, ignore first and last chars\nfor i in range(len(words)):\n word_val = 0\n for j in range(1, len(words[i]) - 1):\n word_val += alphabet[words[i][j]]\n if word_val in tri_nums:\n count += 1\n\nprint(count)"} {"blob_id": "6e4bc7d8121fe7e7d22acc0e33737ce563f40533", "repo_name": "bruinsan/home", "path": "/advent_calendar/day3/day3b.py", "length_bytes": 3998, "score": 3.625, "int_score": 4, "content": "import sys\nfrom pprint import pprint\nfrom math import sqrt, ceil\n\nfinished = 0\n\ndef move_right(mem, x, y, times, final_pos):\n\tglobal finished\n\t#print \"[RIGHT_START] x = {} \\t y = {}\".format(x, y)\n\n\tfor i in xrange(times):\n\t#\tprint \"[RIGHT] x = {} \\t y = {}\".format(x + i + 1, y)\n\t\tr = x + i + 1\n\t\tpositions = [mem[y + 1][r - 1], mem[y + 1][r], mem[y + 1][r + 1], mem[y][r - 1],\n mem[y][r], mem[y][r + 1], mem[y - 1][r - 1], mem[y - 1][r], mem[y - 1][r + 1]]\n\t#\tprint positions\n\t\tactual_nb = sum(positions)\n\t\tif actual_nb <= final_pos:\n\t\t\tprint actual_nb\n\t\t\tmem[y][r] = actual_nb\n#\t\t\tif actual_nb == final_pos:\n#\t\t\t\tbreak\n\t# \t# x += 1\n\t\telse:\n\t\t\tfinished = 1\n\t\t\tbreak\n\n\treturn x + times, y, actual_nb\n\n\ndef move_left(mem, x, y, times, final_pos):\n\tglobal finished\n\t# print \"[LEFT_START] x = {} \\t y = {}\".format(x, y)\n\tfor i in xrange(times):\n\t\t# print \"[LEFT] x = {} \\t y = {}\".format(x-i-1, y)\n\t\tr = x - i - 1\n\t\tpositions = [mem[y + 1][r - 1], mem[y + 1][r], mem[y + 1][r + 1], mem[y][r - 1],\n mem[y][r], mem[y][r + 1], mem[y - 1][r - 1], mem[y - 1][r], mem[y - 1][r + 1]]\n\t #\tprint positions\n\t\tactual_nb = sum(positions)\n\t\tif actual_nb <= final_pos:\n\t\t\tprint actual_nb\n\t\t\tmem[y][r] = actual_nb\n\t\t\t#if actual_nb == final_pos:\n\t\t\t#\tbreak\n\t# \t\tmem[y][x - i - 1] = actual_nb\n\t\telse:\n\t\t\tfinished = 1\n\t\t\tbreak\n\t# \tx=x-i\n\n\treturn x - times, y, actual_nb\n\n\ndef move_up(mem, x, y, times, final_pos):\n\tglobal finished\n\t#print \"[UP_START] x = {} \\t y = {}\".format(x, y)\n\n\tfor i in xrange(times):\n\t#\tprint \"[UP] x = {} \\t y = {}\".format(x, y-i-1)\n\t\ts = y - i - 1\n\t\tpositions = [mem[s + 1][x - 1], mem[s + 1][x], mem[s + 1][x + 1], mem[s][x - 1],\n mem[s][x], mem[s][x + 1], mem[s - 1][x - 1], mem[s - 1][x], mem[s - 1][x + 1]]\n\t#\tprint positions\n\t# \tprint \"x = {} \\t y = {}\".format(x, y)\n\n\t\tactual_nb = sum(positions)\n\t\tif actual_nb <= final_pos:\n\t\t\tprint actual_nb\n\t\t\tmem[s][x] = actual_nb\n#\t\t\tif actual_nb == final_pos:\n#\t\t\t\tbreak\n\t\telse:\n\t\t\tfinished = 1\n\t\t\tbreak\n\n\treturn x, y - times, actual_nb\n\n\ndef move_down(mem, x, y, times, final_pos):\n\tglobal finished\n\t# print \"[DOWN_START] x = {} \\t y = {}\".format(x, y)\n\n\tfor i in xrange(times):\n\t\t# print \"[DOWN] x = {} \\t y = {}\".format(x, y+i+1)\n\t\ts = y + i + 1\n\t\tpositions = [mem[s + 1][x - 1], mem[s + 1][x], mem[s + 1][x + 1], mem[s][x - 1],\n mem[s][x], mem[s][x + 1], mem[s - 1][x - 1], mem[s - 1][x], mem[s - 1][x + 1]]\n\t\tactual_nb = sum(positions)\n\t\tif actual_nb <= final_pos:\n\t\t\tprint actual_nb\n\t\t\tmem[s][x] = actual_nb\n#\t\t\tif actual_nb == final_pos:\n#\t\t\t\tbreak\n\t# \t\tmem[y + i + 1][x] = actual_nb\n\t\telse:\n\t\t\tfinished = 1\n\t\t\tbreak\n\n\treturn x, y + times, actual_nb\n\n\ndef create_spiral_memory(final_pos):\n\tglobal finished\n\t#size = int(sys.argv[2])\n\tsize = int(ceil(sqrt(final_pos)))\n\t\n\tmemory = [[0 for x in xrange(size)]\n for y in xrange(size)] # creating 11x11 matrix\n\n\t# RU\n\tx_init = len(memory) / 2 - 1\n\ty_init = len(memory) / 2 - 1\n\tactual_nb = 1\n\tmemory[x_init][y_init] = actual_nb\n\tadd = 1\n\n\twhile actual_nb <= final_pos: # change the condition for stopping when final_pos achieved\n\t\tx_init, y_init, actual_nb = move_right(memory, x_init, y_init, add, final_pos)\n\t\t#print \"x = {} \\t y = {} \\t actual_nb = {}\".format(x_init, y_init, actual_nb)\n\t\tif finished:\n\t\t\tbreak\n\t\tx_init, y_init, actual_nb = move_up(memory, x_init, y_init, add, final_pos)\n\t\tif finished:\n\t\t\tbreak\n\t\t#print \"x = {} \\t y = {} \\t actual_nb = {}\".format(x_init, y_init, actual_nb)\n\t\tx_init, y_init, actual_nb = move_left(memory, x_init, y_init, add + 1, final_pos)\n\t\tif finished:\n\t\t\tbreak\n\t\t#print \"x = {} \\t y = {} \\t actual_nb = {}\".format(x_init, y_init, actual_nb)\n\t\tx_init, y_init, actual_nb = move_down(memory, x_init, y_init, add + 1, final_pos)\n\t\tif finished:\n\t\t\tbreak\n\t\t#print \"x = {} \\t y = {} \\t actual_nb = {}\".format(x_init, y_init, actual_nb)\n\n\t\tadd += 2\n\t\t# pprint(memory)\n\treturn actual_nb\n\n\nfinal_num = int(sys.argv[1])\nm = create_spiral_memory(final_num)\nprint m\n\n#pprint(m)\n"} {"blob_id": "f9f23497985df30ee5acc29607e331f60c76b887", "repo_name": "WeilinXu/deeplearning_hw", "path": "/deeplearning_hw/Homeworks/Homework1/my_code/layers.py", "length_bytes": 25569, "score": 3.75, "int_score": 4, "content": "from builtins import range\nimport numpy as np\n\n\ndef fc_forward(x, w, b):\n\t\"\"\"\n\tComputes the forward pass for a fully-connected layer.\n\n\tThe input x has shape (N, Din) and contains a minibatch of N\n\texamples, where each example x[i] has shape (Din,).\n\n\tInputs:\n\t- x: A numpy array containing input data, of shape (N, Din)\n\t- w: A numpy array of weights, of shape (Din, Dout)\n\t- b: A numpy array of biases, of shape (Dout,)\n\n\tReturns a tuple of:\n\t- out: output, of shape (N, Dout)\n\t- cache: (x, w, b)\n\t\"\"\"\n\t###########################################################################\n\t# TODO: Implement the forward pass. Store the result in out. #\n\t###########################################################################\n\t\n\t# N: single number, Din: tuple, Dout: single number\n\tN = x.shape[0]\n\tx1 = x.reshape(N, -1);\n\tout = np.dot(x1, w) + b\n\t#print(\"w shape {}\".format(w.shape))\n\t#pass\n\t###########################################################################\n\t# END OF YOUR CODE #\n\t###########################################################################\n\tcache = (x, w, b)\n\treturn out, cache\n\n\ndef fc_backward(dout, cache):\n\t\"\"\"\n\tComputes the backward pass for a fully_connected layer.\n\n\tInputs:\n\t- dout: Upstream derivative, of shape (N, Dout)\n\t- cache: Tuple of:\n\t - x: Input data, of shape (N, Din)\n\t - w: Weights, of shape (Din, Dout)\n\t - b: Biases, of shape (Dout,)\n\n\tReturns a tuple of:\n\t- dx: Gradient with respect to x, of shape (N, Din)\n\t- dw: Gradient with respect to w, of shape (Din, Dout)\n\t- db: Gradient with respect to b, of shape (Dout,)\n\t\"\"\"\n\tx, w, b = cache\n\t#dx, dw, db = None, None, None\n\t###########################################################################\n\t# TODO: Implement the affine backward pass. #\n\t###########################################################################\n\t\n\tdb = np.sum(dout, axis=0)\n\tdw = np.dot(x.transpose(), dout)\n\t\n\tif (b.shape[0] == 1):\n\t\tdb = np.sum(dout)\n\t\tdb = np.array([db])\n\t\n\tdw = dw.reshape((w.shape[0], -1))\n\tif(len(w.shape) == 1):\n\t\tdw = dw.reshape(-1)\n\t\t\n\tif (len(dout.shape) == 1):\n\t\tw = w.reshape((w.shape[0], 1))\t\n\t\n\tif (len(dout.shape) == 1):\n\t\tdout = dout.reshape((dout.shape[0], 1))\n\tdx = np.dot(dout, np.transpose(w))\n\tdx = dx.reshape(x.shape)\n\t#pass\n\t###########################################################################\n\t# END OF YOUR CODE #\n\t###########################################################################\n\treturn dx, dw, db\n\n\ndef relu_forward(x):\n \"\"\"\n Computes the forward pass for a layer of rectified linear units (ReLUs).\n\n Input:\n - x: Inputs, of any shape\n\n Returns a tuple of:\n - out: Output, of the same shape as x\n - cache: x\n \"\"\"\n out = None\n ###########################################################################\n # TODO: Implement the ReLU forward pass. #\n ###########################################################################\n out = np.copy(x)\n out[out < 0] = 0\n ###########################################################################\n # END OF YOUR CODE #\n ###########################################################################\n cache = x\n return out, cache\n\n\ndef relu_backward(dout, cache):\n\t\"\"\"\n\tComputes the backward pass for a layer of rectified linear units (ReLUs).\n\n\tInput:\n\t- dout: Upstream derivatives, of any shape\n\t- cache: Input x, of same shape as dout\n\n\tReturns:\n\t- dx: Gradient with respect to x\n\t\"\"\"\n\tdx, x = None, cache\n\t###########################################################################\n\t# TODO: Implement the ReLU backward pass. #\n\t###########################################################################\n\tdx = np.copy(x)\n\tdx[dx >= 0] = 1\n\tdx[dx < 0] = 0\n\tdx = dx*dout\n\t###########################################################################\n\t# END OF YOUR CODE #\n\t###########################################################################\n\treturn dx\n\n\ndef batchnorm_forward(x, gamma, beta, bn_param):\n\t\"\"\"\n\tForward pass for batch normalization.\n\n\tDuring training the sample mean and (uncorrected) sample variance are\n\tcomputed from minibatch statistics and used to normalize the incoming data.\n\tDuring training we also keep an exponentially decaying running mean of the\n\tmean and variance of each feature, and these averages are used to normalize\n\tdata at test-time.\n\n\tAt each timestep we update the running averages for mean and variance using\n\tan exponential decay based on the momentum parameter:\n\n\trunning_mean = momentum * running_mean + (1 - momentum) * sample_mean\n\trunning_var = momentum * running_var + (1 - momentum) * sample_var\n\n\tNote that the batch normalization paper suggests a different test-time\n\tbehavior: they compute sample mean and variance for each feature using a\n\tlarge number of training images rather than using a running average. For\n\tthis implementation we have chosen to use running averages instead since\n\tthey do not require an additional estimation step; the torch7\n\timplementation of batch normalization also uses running averages.\n\n\tInput:\n\t- x: Data of shape (N, D)\n\t- gamma: Scale parameter of shape (D,)\n\t- beta: Shift paremeter of shape (D,)\n\t- bn_param: Dictionary with the following keys:\n\t - mode: 'train' or 'test'; required\n\t - eps: Constant for numeric stability\n\t - momentum: Constant for running mean / variance.\n\t - running_mean: Array of shape (D,) giving running mean of features\n\t - running_var Array of shape (D,) giving running variance of features\n\n\tReturns a tuple of:\n\t- out: of shape (N, D)\n\t- cache: A tuple of values needed in the backward pass\n\t\"\"\"\n\tmode = bn_param['mode']\n\teps = bn_param.get('eps', 1e-5)\n\tmomentum = bn_param.get('momentum', 0.9)\n\n\tN, D = x.shape\n\trunning_mean = bn_param.get('running_mean', np.zeros(D, dtype=x.dtype))\n\trunning_var = bn_param.get('running_var', np.zeros(D, dtype=x.dtype))\n\n\tout, cache = None, None\n\tif mode == 'train':\n\t\t#######################################################################\n\t\t# TODO: Implement the training-time forward pass for batch norm. #\n\t\t# Use minibatch statistics to compute the mean and variance, use #\n\t\t# these statistics to normalize the incoming data, and scale and #\n\t\t# shift the normalized data using gamma and beta. #\n\t\t# #\n\t\t# You should store the output in the variable out. Any intermediates #\n\t\t# that you need for the backward pass should be stored in the cache #\n\t\t# variable. #\n\t\t# #\n\t\t# You should also use your computed sample mean and variance together #\n\t\t# with the momentum variable to update the running mean and running #\n\t\t# variance, storing your result in the running_mean and running_var #\n\t\t# variables. #\n\t\t# #\n\t\t# Note that though you should be keeping track of the running #\n\t\t# variance, you should normalize the data based on the standard #\n\t\t# deviation (square root of variance) instead! # \n\t\t# Referencing the original paper (https://arxiv.org/abs/1502.03167) #\n\t\t# might prove to be helpful. #\n\t\t#######################################################################\n\t\tsample_mean = np.mean(x, axis = 0)\n\t\tsample_var = np.var(x, axis = 0)\n\t\t\n\t\tx_norm = (x-sample_mean)/ np.sqrt(sample_var+eps)\n\t\trunning_mean = momentum * running_mean + (1 - momentum) * sample_mean\n\t\trunning_var = momentum * running_var + (1 - momentum) * sample_var\n\t\tout = x_norm*gamma + beta\n\t\tcache = (x, x_norm, gamma, beta, eps, bn_param, sample_mean, sample_var)\n\t\t#pass\n\t\t#######################################################################\n\t\t# END OF YOUR CODE #\n\t\t#######################################################################\n\telif mode == 'test':\n\t\t#######################################################################\n\t\t# TODO: Implement the test-time forward pass for batch normalization. #\n\t\t# Use the running mean and variance to normalize the incoming data, #\n\t\t# then scale and shift the normalized data using gamma and beta. #\n\t\t# Store the result in the out variable. #\n\t\t#######################################################################\n\t\t\n\t\tx_norm = (x-running_mean)/np.sqrt(running_var+eps)\n\t\tout = x_norm*gamma + beta\t\n\t\tcache = (x, x_norm, gamma, beta, eps, bn_param, running_mean, running_var)\n\t\t#pass\n\t\t#######################################################################\n\t\t# END OF YOUR CODE #\n\t\t#######################################################################\n\telse:\n\t\traise ValueError('Invalid forward batchnorm mode \"%s\"' % mode)\n\n\t# Store the updated running means back into bn_param\n\tbn_param['running_mean'] = running_mean\n\tbn_param['running_var'] = running_var\n\t\n\treturn out, cache\n\n\ndef batchnorm_backward(dout, cache):\n\t\"\"\"\n\tBackward pass for batch normalization.\n\n\tFor this implementation, you should write out a computation graph for\n\tbatch normalization on paper and propagate gradients backward through\n\tintermediate nodes.\n\n\tInputs:\n\t- dout: Upstream derivatives, of shape (N, D)\n\t- cache: Variable of intermediates from batchnorm_forward.\n\n\tReturns a tuple of:\n\t- dx: Gradient with respect to inputs x, of shape (N, D)\n\t- dgamma: Gradient with respect to scale parameter gamma, of shape (D,)\n\t- dbeta: Gradient with respect to shift parameter beta, of shape (D,)\n\t\"\"\"\n\tx, x_norm, gamma, beta, eps, bn_param, cur_mean, cur_var = cache\n\tN, D = x.shape\n\tdx, dgamma, dbeta = None, None, None\n\t###########################################################################\n\t# TODO: Implement the backward pass for batch normalization. Store the #\n\t# results in the dx, dgamma, and dbeta variables. #\n\t# Referencing the original paper (https://arxiv.org/abs/1502.03167) #\n\t# might prove to be helpful. #\n\t###########################################################################\n\tx_mu = x - cur_mean\n\tstd_inv = 1.0/np.sqrt(cur_var + eps)\n\tdx_norm = dout*gamma\n\tdvar = np.sum(dx_norm * x_mu, axis=0) * (-0.5) * (std_inv**3)\n\tdmu = np.sum(dx_norm * (-std_inv), axis=0) + dvar * np.mean(-2. * x_mu, axis=0)\n\n\tdx = (dx_norm * std_inv) + (dvar * 2 * x_mu / N) + (dmu / N)\n\tdgamma =np.sum(dout * x_norm, axis = 0)\n\tdbeta = np.sum(dout, axis = 0)\n\t#pass\n\t###########################################################################\n\t# END OF YOUR CODE #\n\t###########################################################################\n\n\treturn dx, dgamma, dbeta\n\n\ndef dropout_forward(x, dropout_param):\n\t\"\"\"\n\tPerforms the forward pass for dropout.\n\n\tInputs:\n\t- x: Input data, of any shape\n\t- dropout_param: A dictionary with the following keys:\n\t - p: Dropout parameter. We keep each neuron output with probability p.\n\t - mode: 'test' or 'train'. If the mode is train, then perform dropout;\n\t\tif the mode is test, then just return the input.\n\t - seed: Seed for the random number generator. Passing seed makes this\n\t\tfunction deterministic, which is needed for gradient checking but not\n\t\tin real networks.\n\n\tOutputs:\n\t- out: Array of the same shape as x.\n\t- cache: tuple (dropout_param, mask). In training mode, mask is the dropout\n\t mask that was used to multiply the input; in test mode, mask is None.\n\n\tNOTE: Implement the vanilla version of dropout.\n\n\tNOTE 2: Keep in mind that p is the probability of **keep** a neuron\n\toutput; this might be contrary to some sources, where it is referred to\n\tas the probability of dropping a neuron output.\n\t\"\"\"\n\tp, mode = dropout_param['p'], dropout_param['mode']\n\tif 'seed' in dropout_param:\n\t\tnp.random.seed(dropout_param['seed'])\n\n\tmask = None\n\tout = None\n\n\tif mode == 'train':\n\t\t#######################################################################\n\t\t# TODO: Implement training phase forward pass for inverted dropout. #\n\t\t# Store the dropout mask in the mask variable. #\n\t\t#######################################################################\n\t\tprobs = np.random.rand(*x.shape)\n\t\tmask = probs < p\n\t\t\n\t\tout = mask*x\n\t\t#pass\n\t\t#######################################################################\n\t\t# END OF YOUR CODE #\n\t\t#######################################################################\n\telif mode == 'test':\n\t\t#######################################################################\n\t\t# TODO: Implement the test phase forward pass for inverted dropout. #\n\t\t#######################################################################\n\t\tout = np.copy(x)\n\t\t#pass\n\t\t#######################################################################\n\t\t# END OF YOUR CODE #\n\t\t#######################################################################\n\n\tcache = (dropout_param, mask)\n\tout = out.astype(x.dtype, copy=False)\n\n\treturn out, cache\n\n\ndef dropout_backward(dout, cache):\n \"\"\"\n Perform the backward pass for dropout.\n\n Inputs:\n - dout: Upstream derivatives, of any shape\n - cache: (dropout_param, mask) from dropout_forward.\n \"\"\"\n dropout_param, mask = cache\n mode = dropout_param['mode']\n\n dx = None\n if mode == 'train':\n #######################################################################\n # TODO: Implement training phase backward pass for inverted dropout #\n #######################################################################\n dx = mask*dout\n #pass\n #######################################################################\n # END OF YOUR CODE #\n #######################################################################\n elif mode == 'test':\n dx = dout\n return dx\n\n\ndef conv_forward(x, w):\n\t\"\"\"\n\tThe input consists of N data points, each with C channels, height H and\n\twidth W. We convolve each input with F different filters, where each filter\n\tspans all C channels and has height HH and width WW. Assume that stride=1\n\tand there is no padding. You can ignore the bias term in your\n\timplementation.\n\n\tInput:\n\t- x: Input data of shape (N, C, H, W)\n\t- w: Filter weights of shape (F, C, HH, WW)\n\n\tReturns a tuple of:\n\t- out: Output data, of shape (N, F, H', W') where H' and W' are given by\n\t H' = H - HH + 1\n\t W' = W - WW + 1\n\t- cache: (x, w)\n\t\"\"\"\n\tout = None\n\t###########################################################################\n\t# TODO: Implement the convolutional forward pass. #\n\t# Hint: you can use the function np.pad for padding. #\n\t###########################################################################\n\tN, C, H, W = x.shape\n\tF, _, Hp, Wp = w.shape\n\tHnew = H - Hp + 1\n\tWnew = W - Wp + 1\n\tout = np.zeros((N, F, Hnew, Wnew))\n\t\n\tfor n in range(N):\n\t\tfor f in range(F):\n\t\t\tfor i in range(Hnew):\n\t\t\t\tfor j in range(Wnew):\n\t\t\t\t\tout[n, f, i, j] = np.sum(x[n, :, i:(i + Hp), j:(j + Wp)] * w[f])\n\n\t###########################################################################\n\t# END OF YOUR CODE #\n\t###########################################################################\n\tcache = (x, w)\n\treturn out, cache\n\t\n\n\t\ndef conv_backward(dout, cache):\n\t\"\"\"\n\tInputs:\n\t- dout: Upstream derivatives.\n\t- cache: A tuple of (x, w) as in conv_forward\n\n\tReturns a tuple of:\n\t- dx: Gradient with respect to x\n\t- dw: Gradient with respect to w\n\t\"\"\"\n\tdx, dw = None, None\n\t###########################################################################\n\t# TODO: Implement the convolutional backward pass. #\n\t###########################################################################\n\tx, w = cache\n\tN, C, H, W = x.shape\n\tF, _, Hp, Wp = w.shape\n\tHnew = int(H - Hp + 1)\n\tWnew = int(W - Wp + 1)\n\n\tdx = np.zeros((N, C, H, W))\n\tdw = np.zeros((F, C, Hp, Wp))\n\tfor f in range(F):\n\t\tfor n in range(N):\n\t\t\tfor i in range(Hnew):\n\t\t\t\tfor j in range(Wnew):\n\t\t\t\t\tdx[n, :, i:(i + Hp), j:(j + Wp)] += dout[n, f, i, j] * w[f]\n\t\t\t\t\t\n\tfor f in range(F):\n\t\tfor c in range(C):\n\t\t\tfor i in range(Hp):\n\t\t\t\tfor j in range(Wp):\n\t\t\t\t\tdw[f, c, i, j] = np.sum(dout[:, f, :, :] * x[:, c, i:(i + Hnew), j:(j + Wnew)])\n\t\t\t\t\t\n\t###########################################################################\n\t# END OF YOUR CODE #\n\t###########################################################################\n\treturn dx, dw\n\n\n\t\ndef conv_forward2(x, w, conv_param = None):\n\t\"\"\"\n\tThe input consists of N data points, each with C channels, height H and\n\twidth W. We convolve each input with F different filters, where each filter\n\tspans all C channels and has height HH and width WW. Assume that stride=1\n\tand there is no padding. You can ignore the bias term in your\n\timplementation.\n\n\tInput:\n\t- x: Input data of shape (N, C, H, W)\n\t- w: Filter weights of shape (F, C, HH, WW)\n\n\tReturns a tuple of:\n\t- out: Output data, of shape (N, F, H', W') where H' and W' are given by\n\t H' = H - HH + 1\n\t W' = W - WW + 1\n\t- cache: (x, w)\n\t\"\"\"\n\tout = None\n\t###########################################################################\n\t# TODO: Implement the convolutional forward pass. #\n\t# Hint: you can use the function np.pad for padding. #\n\t###########################################################################\n\tstride = 1\n\tpad = 0\n\tif conv_param is not None:\n\t\tstride = int(conv_param['stride'])\n\t\tpad = int(conv_param['pad'])\n\t\t\n\t\n\tN, C, H, W = x.shape\n\tF, _, Hp, Wp = w.shape\n\tHnew = int((H + 2*pad - Hp)/stride) + 1\n\tWnew = int((W + 2*pad - Wp)/stride) + 1\n\tout = np.zeros((N, F, Hnew, Wnew))\n\tx_new = np.pad(x, ((0,), (0,), (pad,), (pad,)), 'constant')\n\t\n\tfor n in range(N):\n\t\tfor f in range(F):\n\t\t\tfor i in range(Hnew):\n\t\t\t\tfor j in range(Wnew):\n\t\t\t\t\tout[n, f, i, j] = np.sum(x_new[n, :, (i*stride):(i*stride + Hp), (j*stride):(j*stride + Wp)] * w[f])\n\n\t###########################################################################\n\t# END OF YOUR CODE #\n\t###########################################################################\n\tcache = (x, w)\n\treturn out, cache\n\t\n\n\n\t\ndef conv_backward2(dout, cache, conv_param = None):\n\t\"\"\"\n\tInputs:\n\t- dout: Upstream derivatives.\n\t- cache: A tuple of (x, w) as in conv_forward\n\n\tReturns a tuple of:\n\t- dx: Gradient with respect to x\n\t- dw: Gradient with respect to w\n\t\"\"\"\n\tdx, dw = None, None\n\t###########################################################################\n\t# TODO: Implement the convolutional backward pass. #\n\t###########################################################################\n\tstride = 1\n\tpad = 0\n\tif conv_param is not None:\n\t\tstride = int(conv_param['stride'])\n\t\tpad = int(conv_param['pad'])\n\t\t\n\t\n\tx, w = cache\n\tN, C, H, W = x.shape\n\tF, _, Hp, Wp = w.shape\n\tHnew = int((H + 2*pad - Hp)/stride) + 1\n\tWnew = int((W + 2*pad - Wp)/stride) + 1\n\n\tdx = np.zeros((N, C, H, W))\n\tdx = np.pad(dx, ((0,), (0,), (pad,), (pad,)), 'constant')\n\tdw = np.zeros((F, C, Hp, Wp))\n\t\n\tx_new = np.pad(x, ((0,), (0,), (pad,), (pad,)), 'constant')\n\t\n\tfor f in range(F):\n\t\tfor n in range(N):\n\t\t\tfor i in range(Hnew):\n\t\t\t\tfor j in range(Wnew):\n\t\t\t\t\tdx[n, :, (i*stride):(i*stride + Hp), (j*stride):(j*stride + Wp)] += dout[n, f, i, j] * w[f]\n\t\n\t\n\tif pad is not 0:\n\t\tdx = dx[:, :, pad:-pad, pad:-pad]\n\t\t\n\tfor f in range(F):\n\t\tfor c in range(C):\n\t\t\tfor i in range(Hp):\n\t\t\t\tfor j in range(Wp):\n\t\t\t\t\tdw[f, c, i, j] = np.sum(dout[:, f, :, :] * x_new[:, c, i:(i + Hnew*stride), j:(j + Wnew*stride)])\n\t\t\t\t\t\n\t###########################################################################\n\t# END OF YOUR CODE #\n\t###########################################################################\n\treturn dx, dw\n\ndef max_pool_forward(x, pool_param):\n\t\"\"\"\n\tA naive implementation of the forward pass for a max-pooling layer.\n\n\tInputs:\n\t- x: Input data, of shape (N, C, H, W)\n\t- pool_param: dictionary with the following keys:\n\t - 'pool_height': The height of each pooling region\n\t - 'pool_width': The width of each pooling region\n\t - 'stride': The distance between adjacent pooling regions\n\n\tNo padding is necessary here. Output size is given by \n\n\tReturns a tuple of:\n\t- out: Output data, of shape (N, C, H', W') where H' and W' are given by\n\t H' = 1 + (H - pool_height) / stride\n\t W' = 1 + (W - pool_width) / stride\n\t- cache: (x, pool_param)\n\t\"\"\"\n\tout = None\n\t###########################################################################\n\t# TODO: Implement the max-pooling forward pass #\n\t###########################################################################\n\tN, C, H, W = x.shape\n\tpool_height, pool_width, stride = pool_param['pool_height'], pool_param['pool_width'], pool_param['stride']\n\tHout = 1 + int((H - pool_height) / stride)\n\tWout = 1 + int((W - pool_width) / stride)\n\tout = np.zeros((N, C, Hout, Wout))\n\tfor n in range(0, N):\n\t\tfor c in range(0, C):\n\t\t\tfor i in range(0, Hout):\n\t\t\t\tfor j in range(0, Wout):\n\t\t\t\t\tout[n, c, i, j] = np.max(x[n, c, (i*stride):(i*stride+(pool_width)), (j*stride):(j*stride+(pool_width))])\n\n\t#pass\n\t###########################################################################\n\t# END OF YOUR CODE #\n\t###########################################################################\n\tcache = (x, pool_param)\n\treturn out, cache\n\n\ndef max_pool_backward(dout, cache):\n\t\"\"\"\n\tA naive implementation of the backward pass for a max-pooling layer.\n\n\tInputs:\n\t- dout: Upstream derivatives\n\t- cache: A tuple of (x, pool_param) as in the forward pass.\n\n\tReturns:\n\t- dx: Gradient with respect to x\n\t\"\"\"\n\n\n\tdx = None\n\t###########################################################################\n\t# TODO: Implement the max-pooling backward pass #\n\t###########################################################################\n\tx, pool_param = cache\n\tN, C, H, W = x.shape\n\tpool_height, pool_width, stride = pool_param['pool_height'], pool_param['pool_width'], pool_param['stride']\n\tHout = int(1 + (H - pool_height) / stride)\n\tWout = int(1 + (W - pool_width) / stride)\n\tdx = np.zeros((N, C, H, W))\n\tfor n in range(0, N):\n\t\tfor c in range(0, C):\n\t\t\tfor i in range(0, Hout):\n\t\t\t\tfor j in range(0, Wout):\n\t\t\t\t\ttempa = x[n, c, (i*stride):(i*stride+(pool_height)), (j*stride):(j*stride+(pool_width))]\n\t\t\t\t\ttempmax = np.max(tempa)\n\t\t\t\t\tdx[n, c, (i*stride):(i*stride+(pool_height)), (j*stride):(j*stride+(pool_width))] += dout[n, c, i, j]*(tempa==tempmax)\n\n\t#pass\n\t###########################################################################\n\t# END OF YOUR CODE #\n\t###########################################################################\n\treturn dx\n\n\ndef svm_loss(x, y):\n\t\"\"\"\n\tComputes the loss and gradient for binary SVM classification.\n\tInputs:\n\t- x: Input data, of shape (N,) where x[i] is the score for the ith input.\n\t- y: Vector of labels, of shape (N,) where y[i] is the label for x[i]\n\tReturns a tuple of:\n\t- loss: Scalar giving the loss\n\t- dx: Gradient of the loss with respect to x\n\t\"\"\"\n\tN = x.shape[0]\n\tloss = 0\n\tdx = np.zeros(x.shape)\n\tfor i in range(0, N):\n\t\tif(y[i] == 0):\n\t\t\ty[i] = -1\n\t\ttemp = 1-x[i]*y[i]\n\t\tif(temp > 0):\n\t\t\tloss += temp\n\t\t\tdx[i] = -y[i]\n\t\t\t\n\tloss /= x.shape[0]\n\tdx /= x.shape[0]\n\treturn loss, dx\n\n\ndef logistic_loss(x, y):\n\t\"\"\"\n\tComputes the loss and gradient for binary classification with logistic \n\tregression.\n\tInputs:\n\t- x: Input data, of shape (N,) where x[i] is the logit for the ith input.\n\t- y: Vector of labels, of shape (N,) where y[i] is the label for x[i]\n\tReturns a tuple of:\n\t- loss: Scalar giving the loss\n\t- dx: Gradient of the loss with respect to x\n\t\"\"\"\n\tsigmoid_p = 1.0/(1.0+np.exp(-x))\t\n\tloss = 0\n\tdx = np.copy(sigmoid_p)\n\tfor i in range(0, x.shape[0]):\n\t\tif y[i] == 0 or y[i] == -1:\n\t\t\tcur_loss = -np.log(1 - sigmoid_p[i])\n\t\telse:\n\t\t\tcur_loss = -np.log(sigmoid_p[i])\n\t\t\tdx[i] -= 1\n\t\t\t\n\t\tloss += cur_loss\n\t\n\tloss /= x.shape[0]\n\tdx /= x.shape[0]\n\treturn loss, dx\n\n\t\ndef softmax_loss(x, y):\n\t\"\"\"\n\tComputes the loss and gradient for softmax classification.\n\tInputs:\n\t- x: Input data, of shape (N, C) where x[i, j] is the score for the jth class\n\tfor the ith input.\n\t- y: Vector of labels, of shape (N,) where y[i] is the label for x[i] and\n\t0 <= y[i] < C\n\tReturns a tuple of:\n\t- loss: Scalar giving the loss\n\t- dx: Gradient of the loss with respect to x\n\t\"\"\"\n\tloss = 0\n\tdx = np.zeros(x.shape)\n\tfor i in range(0, x.shape[0]):\n\t\ttemp_sum = np.sum(np.exp(x[i, :]))\n\t\ttemp_score = np.exp(x[i, :])\n\t\t#idx_max = np.argmax(temp_score)\n\t\tloss -= np.log(temp_score[y[i]]/temp_sum)\t\t### numeraical issue\n\t\tdx[i, :] = np.exp(x[i, :])/temp_sum\n\t\tdx[i, y[i]] -= 1\n\tloss = loss/x.shape[0]\n\tdx = dx/x.shape[0]\n\treturn loss, dx\n"} {"blob_id": "c7f09b38290cd555d9d940f93cbf765b2421a32d", "repo_name": "DougScalioni/project-euler", "path": "/PE054 - Poker Hands.py", "length_bytes": 3678, "score": 3.5, "int_score": 4, "content": "file = open('poker.txt', 'r').read()\nlines = file.split('\\n')\n\nsuits_value = {\n 'C': 0,\n 'D': 1,\n 'H': 2,\n 'S': 3\n}\n\ncards_value = {\n '2': 2,\n '3': 3,\n '4': 4,\n '5': 5,\n '6': 6,\n '7': 7,\n '8': 8,\n '9': 9,\n 'T': 10,\n 'J': 11,\n 'Q': 12,\n 'K': 13,\n 'A': 14\n}\n\n\ndef draw(ln):\n cards = ln.split(' ')\n hand_p1 = cards[0:5]\n hand_p2 = cards[5:10]\n return hand_p1, hand_p2\n\n\ndef highest_card(hand):\n values = get_values(hand)\n n = 15\n sum_cards = 0\n for i in range(len(values)):\n sum_cards += values[i]/n**(i+1)\n return True, sum_cards\n\n\ndef one_pair(hand):\n cards = n_cards(hand)\n for c in cards:\n if c[1] == 2:\n return True, c[0] + highest_card(hand)[1]\n return False, 0\n\n\ndef two_pairs(hand):\n cards = n_cards(hand)\n pairs = 0\n tiebreaker = 0\n for c in cards:\n if c[1] == 2:\n tiebreaker += c[0]/15**pairs\n pairs += 1\n return pairs == 2, tiebreaker\n\n\ndef three_of_a_kind(hand):\n cards = n_cards(hand)\n for c in cards:\n if c[1] == 3:\n return True, c[0] + highest_card(hand)[1] # game, tiebreaker\n return False, 0\n\n\ndef straight(hand):\n values = get_values(hand)\n for i in range(0, 4):\n if values[i] - values[i + 1] != 1:\n return False, 0\n return True, highest_card(hand)[1]\n\n\ndef flush(hand):\n suit = hand[0][1]\n for card in hand:\n if card[1] != suit:\n return False, 0\n return True, highest_card(hand)[1]\n\n\ndef full_house(hand):\n pair, tb2 = one_pair(hand)\n three, tb3 = three_of_a_kind(hand)\n return pair and three, tb3+tb2/15\n\n\ndef four_of_a_kind(hand):\n cards = n_cards(hand)\n for c in cards:\n if c[1] == 4:\n return True, c[0]+highest_card(hand)[1] # game, tiebreaker\n return False, 0\n\n\ndef straight_flush(hand):\n st = straight(hand)[0]\n fl = flush(hand)[0]\n tiebreaker = highest_card(hand)[1]\n return st and fl, tiebreaker # game, tiebreaker\n\n\ndef royal_flush(hand):\n if not straight_flush(hand)[0]:\n return False, 0\n suit = hand[0][1]\n if 'A' + suit not in hand:\n return False, 0\n elif 'T' + suit not in hand:\n return False, 0\n else:\n return True, suits_value[hand[0][1]]/4 # game, tiebreaker\n\n\ndef get_values(hand):\n values = []\n for card in hand:\n c = card[0]\n c = cards_value[c]\n values.append(c)\n values.sort(reverse=True)\n return values\n\n\ndef n_cards(hand):\n values = get_values(hand)\n cards = []\n for v in values:\n if not cards:\n cards.append([v, 1])\n elif v == cards[-1][0]:\n cards[-1][1] += 1\n else:\n cards.append([v, 1])\n return cards\n\n\ndef evaluate(hand):\n r = {\n 0: royal_flush(hand),\n 1: straight_flush(hand),\n 2: four_of_a_kind(hand),\n 3: full_house(hand),\n 4: flush(hand),\n 5: straight(hand),\n 6: three_of_a_kind(hand),\n 7: two_pairs(hand),\n 8: one_pair(hand),\n 9: highest_card(hand)\n }\n return r\n\n\ndef compare_hands(p1, p2):\n p1 = evaluate(p1)\n p2 = evaluate(p2)\n i = 0\n while not p1[i][0] and not p2[i][0]:\n i += 1\n if p1[i][0] and p2[i][0]:\n return p1[i][1] > p2[i][1]\n else:\n return p1[i][0] > p2[i][0]\n\n\nplayer1_wins = 0\nplayer2_wins = 0\nfor line in lines:\n player1, player2 = draw(line)\n print(player1, player2)\n if compare_hands(player1, player2):\n player1_wins += 1\n print(\"player1\")\n else:\n player2_wins += 1\n print(\"player2\")\nprint(player1_wins)\nprint(player2_wins)\n\n"} {"blob_id": "8082068ef255b601febec4722ca8292cb4de4594", "repo_name": "mishashahab/left_leaning_red_black_tree", "path": "/LLRBT (19B-004-CS)(19B-043-CS).py", "length_bytes": 16254, "score": 3.84375, "int_score": 4, "content": "# Creating a public class of RBTNode\r\nclass RBTNode:\r\n # This constructor takes one argument data key i.e. data to set the elements\r\n def __init__(self, key):\r\n\r\n self.key = key\r\n # Initialize Node pointers left and right\r\n self.left = None\r\n self.right = None\r\n # New node is always Red\r\n self.color = True\r\n # Red = True, Black = False\r\n self.Red = True\r\n self.Black = False\r\n\r\n # Traverse the Nodes in PostOrder\r\n # Perform action on left then right then currentNode\r\n def postOrder(self, output=None):\r\n if output is None:\r\n output = []\r\n\r\n if self.left:\r\n self.left.postOrder(output)\r\n\r\n if self.right:\r\n self.right.postOrder(output)\r\n output.append(self.key)\r\n\r\n return output\r\n\r\n # Traverse the Nodes in InOrder\r\n # Perform action on left then currentNode then Right\r\n def inOrder(self, output=None):\r\n if output is None:\r\n output = []\r\n\r\n if self.left:\r\n self.left.inOrder(output)\r\n\r\n output.append(self.key)\r\n\r\n if self.right:\r\n self.right.inOrder(output)\r\n\r\n return output\r\n\r\n # Traverse the Nodes in PreOrder\r\n # Perform action on currentNode then Left then Right\r\n def preOrder(self, output=None):\r\n if output is None:\r\n output = []\r\n\r\n output.append(self.key)\r\n if self.left:\r\n self.left.preOrder(output)\r\n\r\n if self.right:\r\n self.right.preOrder(output)\r\n\r\n return output\r\n\r\n\r\n# Creating a private class of LeftLeaning\r\nclass LeftLeaning:\r\n\r\n def __init__(self):\r\n # Initialize root pointer\r\n self.root = None\r\n\r\n def insert(self, key):\r\n # Public function of insert\r\n if self.root is None:\r\n self.root = RBTNode(key)\r\n else:\r\n self.root = self.__insert(self.root, key)\r\n self.root.color = False\r\n\r\n def __insert(self, root, node):\r\n # Creating a private function of Insert\r\n if root is None:\r\n return RBTNode(node)\r\n if self.__isRed(root.left) and self.__isRed(root.right):\r\n self.flipColors(root) # If both children are red, then parent node flip it's color\r\n if node < root.key:\r\n root.left = self.__insert(root.left, node) # If new node is less than root node it will add on left side\r\n elif node > root.key:\r\n root.right = self.__insert(root.right,\r\n node) # If new node is greater than root node it will add on right side\r\n if self.__isRed(root.right) and not self.__isRed(root.left):\r\n root = self.rotateLeft(root) # If only right child is red, then parent node will rotate left\r\n if self.__isRed(root.left) and self.__isRed(root.left.left):\r\n root = self.rotateRight(\r\n root) # If left child of node is red and also it's left child is red, then parent node will rotate right\r\n return root\r\n\r\n def rotateLeft(self, node):\r\n # This function rotates the nodes to it's left\r\n x = node.right\r\n node.right = x.left\r\n x.left = node\r\n x.color = x.left.color\r\n x.left.color = True # Changing color of left node to red\r\n return x\r\n\r\n def rotateRight(self, node):\r\n # This function rotates the nodes to it's right\r\n x = node.left\r\n node.left = x.right\r\n x.right = node\r\n x.color = x.right.color\r\n x.right.color = True # Changing color of right node to red\r\n return x\r\n\r\n def flipColors(self, node):\r\n # This function flips the color of node\r\n node.color = not node.color\r\n if node.left:\r\n node.left.color = not node.left.color\r\n if node.right:\r\n node.right.color = not node.right.color\r\n\r\n def isRed(self, node):\r\n # Check the color of Node is Red or not\r\n x = self.root\r\n while x.key is not None:\r\n if x.key == node:\r\n return x.color == True\r\n elif node < x.key: # If the node is less than the root node then it will check towards left side\r\n x = x.left\r\n elif node > x.key: # If the node is greater than the root node then it will check towards right side\r\n x = x.right\r\n return -1 # Else return -1\r\n\r\n def __isRed(self, node):\r\n # Private function to check, If node is none then return False means Black Color\r\n if node is None:\r\n return False\r\n return node.color == True\r\n\r\n def Search(self, node):\r\n # Public function to search node, Returns True if node is in tree.\r\n node = self._Search(self.root, node)\r\n if node:\r\n return True\r\n else:\r\n return False\r\n\r\n def _Search(self, root, node):\r\n # Private function of search\r\n if root is None:\r\n return None # If root is none then tree is empty\r\n if root.key == node:\r\n return node # If the desired node is equal to root node\r\n if node < root.key:\r\n return self._Search(root.left,\r\n node) # If the desired node is less than the root node then it will find towards left side\r\n else:\r\n return self._Search(root.right,\r\n node) # If the desired node is greater than the root node then it will find towards right side\r\n\r\n def fixUp(self):\r\n # Public function of fixup\r\n self.__fixUp(self.root)\r\n\r\n def __fixUp(self, current_node):\r\n # Private function of fixup, for fixing problems in tree\r\n if self.__isRed(current_node.right):\r\n current_node = self.rotateLeft(\r\n current_node) # If the right child of given node is red then it will rotate left\r\n if self.__isRed(current_node.left) and self.__isRed(current_node.left.left):\r\n current_node = self.rotateRight(\r\n current_node) # If left child of given node is red and also it's left child is red, then given node will rotate right\r\n if self.__isRed(current_node.left) and self.__isRed(current_node.right):\r\n self.flipColors(current_node) # If both children of given node are red, then given node flip it's color\r\n return current_node\r\n\r\n def delete(self, val):\r\n # Public function to delete node by value\r\n if self.root is None:\r\n return None\r\n else:\r\n self.root = self._delete_node(self.root, val)\r\n\r\n def _delete_node(self, node, val):\r\n # Private function for desired node by rotations and color fliping to maintain balance of LLRBT\r\n if node is None:\r\n return node # Return none if desired node is none\r\n if val < node.key: # If the desired node is less than the root node then it will traverse towards left side\r\n if not self.__isRed(node.left) and not self.__isRed(\r\n node.left.left): # If left children of desired node are not red\r\n node = self._moveRedLeft(node) # parent node of desired node will rotate left and also flip it's color\r\n node.left = self._delete_node(node.left, val) # delete node\r\n else: # else (val > node.key) If the desired node is greater than the root node then it will traverse towards right side\r\n if self.__isRed(node.left):\r\n node = self.rotateRight(node) # If the left child of desired node is red then it will rotate right\r\n if val == node.key and node.right is None: # If the value equals to node and right child of node is None\r\n return None # None\r\n if node.right is None or (not self.__isRed(node.right) and not self.__isRed(node.right.left)):\r\n # If right child of desired node is none or If right child and it's left child of desired node is not red\r\n node = self._moveRedRight(\r\n node) # parent node of desired node will rotate right and also flip it's color\r\n if val == node.key:\r\n # If value is equal to the node in tree, it will search right and minimum right node and take place of desired node\r\n node.key = self._Search(node.right, self.__min(node.right))\r\n node.right = self._deleteMin(node.right) # delete minimum right child\r\n else: # else If desired node is not equal to the node in tree\r\n node.right = self._delete_node(node.right, val) # delete minimum right child\r\n return self.__fixUp(node) # Applying fixups\r\n\r\n def FindMax(self):\r\n # Public function to find maximum node\r\n x = self.__FindMax(self.root)\r\n if x.color:\r\n x.color = \"Red\"\r\n else:\r\n x.color = \"Black\"\r\n return x.key, x.color # return node of maximum value and it's color\r\n\r\n def __FindMax(self, node):\r\n # Private function of find maximum\r\n if node.right is None:\r\n return node # find the node on right side of root\r\n return self.__FindMax(node.right) # tail recursion, return value of maximum node\r\n\r\n def FindMin(self):\r\n # Public function to find minimum node\r\n x = self.__FindMin(self.root)\r\n if x.color:\r\n x.color = \"Red\"\r\n else:\r\n x.color = \"Black\"\r\n return x.key, x.color # return node of minimum value and it's color\r\n\r\n def __FindMin(self, root):\r\n # Private function of find mimimum\r\n if root.left is None:\r\n return root # find the node on left side of root\r\n return self.__FindMin(root.left) # tail recursion, return value of minimum node\r\n\r\n def _deleteMin(self, node):\r\n # private function to delete the minimum decendant.\r\n if node.left is None:\r\n return None # If left node of minimum decendant is None, return None\r\n if not self.__isRed(node.left) and not self.__isRed(node.left.left):\r\n node = self._moveRedLeft(node) # If children of left node is not red, red node will rotate left\r\n node.left = self._deleteMin(node.left) # minimum left node will delete\r\n return self.__fixUp(node) # Applying fixing up\r\n\r\n def _deleteMax(self, node):\r\n # private function to delete the maximum decendant.\r\n if self.__isRed(node.left):\r\n node = self.rotateRight(node) # If left node of maximum decendant is red , node will rotate right\r\n if node.right is None:\r\n return None # If left node of maximum decendant is None, return None\r\n if not self.__isRed(node.right) and not self.__isRed(node.right.left):\r\n node = self._moveRedRight(node) # If left children of right node is not red, red node will rotate right\r\n node.left = self._deleteMax(node.left) # minimum left node will delete\r\n return self.__fixUp(node) # Applying fixing up\r\n\r\n def Successor(self):\r\n # Public function of successor\r\n x = self.__Successor(self.root)\r\n if x.color:\r\n x.color = \"Red\"\r\n else:\r\n x.color = \"Black\"\r\n return x.key, x.color # Returns node and also it's color\r\n\r\n def __Successor(self, node):\r\n # Private function which returns the minimum node on left side of root\r\n if node.right is not None:\r\n return self.__FindMin(\r\n node.right) # if right node of root is not none,finds the minimum node on right side of root\r\n suc = node.parent\r\n while node is suc.right and suc is not None:\r\n node = suc\r\n suc = suc.parent\r\n return suc # returns the minimum node on right side of root\r\n\r\n def Predecessor(self):\r\n # public funtion of predecessor\r\n x = self.__Predecessor(self.root)\r\n if x.color:\r\n x.color = \"Red\"\r\n else:\r\n x.color = \"Black\"\r\n return x.key, x.color # Returns node and also it's color\r\n\r\n def __Predecessor(self, node):\r\n # Private function which returns the maximum node on left side of root\r\n if node.left is not None:\r\n return self.__FindMax(node.left) # if left node of root is not none,finds maximum node on left side of root\r\n pre = node.parent\r\n while node is pre.left and pre is not None:\r\n node = pre\r\n pre = node.parent\r\n return pre # returns the maximum node on left side of root\r\n\r\n def __min(self, node):\r\n # private function to return the minimum node.\r\n while node.left is not None:\r\n node = node.left # make bottom left node the desired node\r\n if node is None:\r\n return None # If desired node is none, return none\r\n else:\r\n return node.key # returns minimum node\r\n\r\n def __max(self, node):\r\n # private function to return the maximum node.\r\n while node.right is not None:\r\n node = node.right # make bottom left node the desired node\r\n if node is None:\r\n return None # If desired node is none, return none\r\n else:\r\n return node.key # returns maximum node\r\n\r\n def _moveRedLeft(self, node):\r\n # private function to rotate red node to left\r\n self.flipColors(node) # flips the color of node\r\n if node.right and self.__isRed(\r\n node.right.left): # if the right node of desired node is not red and and it's left node is red\r\n node.right = self.rotateRight(node.right) # right node of desired node will rotate right\r\n node = self.rotateLeft(node) # desired node will rotate left\r\n self.flipColors(node) # flips the color of node\r\n return node\r\n\r\n def _moveRedRight(self, node):\r\n # private function to rotate red node to right\r\n self.flipColors(node) # flips the color of node\r\n if node.left and self.__isRed(\r\n node.left.left): # if the left node of desired node is not red and and it's left node is red\r\n node = self.rotateRight(node) # desired node will rotate right\r\n self.flipColors(node) # flips the color of node\r\n return node\r\n\r\n def Print(self, root):\r\n # Public function to print node color\r\n if not self.isRed(root):\r\n print(\"Black\", root) # if is_Red function return false the color will be Black of desired node\r\n else:\r\n print(\"Red\", root) # if is_Red function return True the color will be Red of desired node\r\n\r\n\r\n# Driver Code\r\nleftredblack = LeftLeaning()\r\n# Inserting nodes 45, 55, 15, 35, 25, 155, 99, 36\r\nleftredblack.insert(45)\r\nleftredblack.insert(55)\r\nleftredblack.insert(15)\r\nleftredblack.insert(35)\r\nleftredblack.insert(25)\r\nleftredblack.insert(155)\r\nleftredblack.insert(99)\r\nleftredblack.insert(36)\r\nprint(\"Print Nodes of Tree\")\r\n# Print nodes in inOrder traversal\r\nprint(\"Inorder\", leftredblack.root.inOrder())\r\n# Print nodes in postOrder traversal\r\nprint(\"PostOrder\", leftredblack.root.postOrder())\r\n# Print nodes in preOrder traversal\r\nprint(\"PreOrder\", leftredblack.root.preOrder())\r\n# Print the maximum value with color in LLRBT\r\nprint(\"Maximum Node\", leftredblack.FindMax())\r\n# Print the maximum value with color in LLRBT\r\nprint(\"Minimum Node\", leftredblack.FindMin())\r\n# Print the colors of respective nodes\r\nprint(\"Colors of the Desired Node\")\r\nleftredblack.Print(45)\r\nleftredblack.Print(15)\r\nleftredblack.Print(55)\r\nleftredblack.Print(25)\r\n# Delete the nodes of values 35, 155\r\nleftredblack.delete(35)\r\nleftredblack.delete(155)\r\nprint(\"Print Nodes of Tree after Deletion\")\r\n# Print nodes in inOrder traversal after deletion\r\nprint(\"InOrder\", leftredblack.root.inOrder())\r\n# Print nodes in postOrder traversal after deletion\r\nprint(\"PostOrder\", leftredblack.root.postOrder())\r\n# Print nodes in preOrder traversal after deletion\r\nprint(\"PreOrder\", leftredblack.root.preOrder())\r\nprint(\"Successor\")\r\n# Print the minimum node on right side of root\r\nprint(leftredblack.Successor())\r\nprint(\"Predecessor\")\r\n# Print the maximum node on left side of root\r\nprint(leftredblack.Predecessor())\r\n"} {"blob_id": "e8e74b30ac6da31bb4907216ea45f4a3136c23cb", "repo_name": "eembees/molstat_water", "path": "/rotation.py", "length_bytes": 2600, "score": 4.15625, "int_score": 4, "content": "## rotation.py Version 1.0\n## Written by Magnus Berg Sletfjerding (eembees)\n###########################################################\n\"\"\"Rotation Functions, inspired by\nhttp://paulbourke.net/geometry/rotate/\nVerified as working 01/07/17 by eembees\"\"\"\n\n\"\"\"Importing modules\"\"\"\nimport numpy as np\nfrom math import pi, sin, cos, sqrt\n\n\n\ndef rotation3d(axis1, axis2, point, angle):\n \"\"\"Rotates a point around an arbitrary axis in a 3D space\n INPUTS:\n *axis1 -- 3d (xyz) array of 1st axis point\n *axis2 -- 3d (xyz) array of 2nd axis point\n *point -- 3d (xyz) array of point to be rotated\n *angle -- angle (radians) of rotation\n Positive angles are counter-clockwise.\n \"\"\"\n #Translate axis to (virtual) origin, define new point ax\n ax = point - axis1\n axis1_neg = [-x for x in axis1]\n axis2_neg = [-x for x in axis2]\n\n #Initialize virtual rotation point rot\n rot = [0.0, 0.0, 0.0]\n\n # Axis direction vector (normalized)\n N = map(sum, zip(axis2, axis1_neg)) # axis vector\n sqsum = sqrt(sum((N[i]**2) for i in range(3)))\n direction = [N[i]/sqsum for i in range(3)]\n\n # Simplifying 3d rotation matrix factors - cosine, sine, translation factor\n co = cos(angle)\n tr = (1-cos(angle))\n si = sin(angle)\n\n x = direction[0]\n y = direction[1]\n z = direction[2]\n\n # Matrix 'D'[3x3] 3D rotation matrix\n d11 = tr*x**2 + co\n d12 = tr*x*y - si*z\n d13 = tr*x*z + si*y\n d21 = tr*x*y + si*z\n d22 = tr*y**2 + co\n d23 = tr*y*z - si*x\n d31 = tr*x*z - si*y\n d32 = tr*y*z + si*x\n d33 = tr*z**2 + co\n\n\n # # Define rot\n rot[0] = d11 * ax[0] + d12 * ax[1] + d13 * ax[2]\n rot[1] = d21 * ax[0] + d22 * ax[1] + d23 * ax[2]\n rot[2] = d31 * ax[0] + d32 * ax[1] + d33 * ax[2]\n\n # # Define output point as rotation point transformed back\n newpoint = rot + axis1\n\n return newpoint\n\nif __name__ == '__main__':\n import extract as ex\n\n a, b, c = ex.readfile(\"w6.xyz\") # # reading file\n\n # Test for distances > paste this after rotation to see if the rotation maintains accurate distance\n '''\n dlist = []\n\n d = 0\n for i in range(3):\n d += c[1][i]-c[0][i]\n d = np.sqrt(d)\n dlist.append(d)\n\n d = 0\n for i in range(3):\n d += c[1][i]-c[2][i]\n d = np.sqrt(d)\n dlist.append(d)\n\n d = 0\n for i in range(3):\n d += c[0][i]-c[2][i]\n d = np.sqrt(d)\n dlist.append(d)\n\n dist = np.sqrt(sum([i**2 for i in dlist]))\n\n print \"DISTANCE BEFORE: \\n\", dist\n '''\n c[1] = rotation3d(c[0], c[2], c[1], 1*pi)\n\n ex.writefile(\"w6_rotated.xyz\", a, b, c) # # Writing file\n"} {"blob_id": "514fe109710e644314731ae105fb383386ed1edf", "repo_name": "ScSteffen/neuralEntropyComparison", "path": "/ext/steffensCode/ext/sphericalquadpy/tools/rotations.py", "length_bytes": 2324, "score": 4.0625, "int_score": 4, "content": "\"\"\"Rotating cartesian points that live on the unit sphere\naround a random or specified axis by a random or specified amount\"\"\"\nfrom numpy.random import rand, randn\nfrom numpy import zeros, cos, sin, pi, multiply, matmul\nfrom numpy.linalg import norm\n\n\n# pylint: disable=C0103\n\n\ndef rotate(axis, angle, xyz):\n \"\"\"Rotates xyz around axis by angle.\"\"\"\n rot = rotationmatrix(axis, angle)\n if len(xyz.shape) == 1: # just one point\n if not len(xyz) == 3:\n raise ValueError(\"Points have to either be of shape (3,) or (n,3). \")\n return multiply(rot, xyz)\n if len(xyz.shape) == 2:\n # we assume xyz to be of shape n x 3\n if not xyz.shape[1] == 3:\n raise ValueError(\"Points have to either be of shape (3,) or (n,3). \")\n\n return matmul(rot, xyz.T).T\n\n raise ValueError(\"Points have to either be of shape (3,) or (n,3). \")\n\n\ndef randomaxisrotate(angle, xyz):\n \"\"\"Rotates xyz around a random axis by angle.\"\"\"\n\n # get random point on unit sphere\n axis = randn(3)\n axis = axis / norm(axis)\n return rotate(axis, angle, xyz)\n\n\ndef randomanglerotate(axis, xyz):\n \"\"\"Rotates xyz around axis by a random angle.\"\"\"\n angle = 2 * pi * rand()\n return rotate(axis, angle, xyz)\n\n\ndef randomrotate(xyz):\n \"\"\"Rotates xyz around a random axis by a random angle.\"\"\"\n # get random point on unit sphere\n axis = randn(3)\n axis = axis / norm(axis)\n angle = 2 * pi * rand()\n return rotate(axis, angle, xyz)\n\n\ndef rotationmatrix(axis, angle):\n \"\"\"Returns the rotation matrix of size 3x3 that rotates a point\n around axis by angle.\n See: https://en.wikipedia.org/wiki/Rotation_matrix\n \"\"\"\n ux = axis[0]\n uy = axis[1]\n uz = axis[2]\n\n costheta = cos(angle)\n sintheta = sin(angle)\n rot = zeros((3, 3))\n\n rot[0, 0] = ux * ux * (1 - costheta) + costheta\n rot[0, 1] = ux * uy * (1 - costheta) - uz * sintheta\n rot[0, 2] = ux * uz * (1 - costheta) + uy * sintheta\n\n rot[1, 0] = uy * ux * (1 - costheta) + uz * sintheta\n rot[1, 1] = uy * uy * (1 - costheta) + costheta\n rot[1, 2] = uy * uz * (1 - costheta) - ux * sintheta\n\n rot[2, 0] = uz * ux * (1 - costheta) - uy * sintheta\n rot[2, 1] = uz * uy * (1 - costheta) + ux * sintheta\n rot[2, 2] = uz * uz * (1 - costheta) + costheta\n\n return rot\n"} {"blob_id": "339ffbf7ac0f9779f107176cc74c5833a600701e", "repo_name": "Janna112358/Gloomhaven", "path": "/Gloomhaven.py", "length_bytes": 2791, "score": 3.921875, "int_score": 4, "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Aug 13 13:40:41 2019\n\n@author: jgoldstein\n\"\"\"\n### docstring convenience stuff ###\n\n# so we don't repeat bits of docstring many times, use this decorator\n# to add standard bits of docstring for parameters and return values\ndef add_doc(doc):\n def decorator(func):\n func.__doc__ += doc\n return func\n return decorator\n\n\nstd_params_doc = \"\"\"\n\n Parameters\n ----------\n n: int\n cards in hand\n m: int\n cards in discard (not lost)\n\"\"\"\n\nturns_returns_doc = \"\"\"\n Returns\n -------\n int: max number of turns (not counting long rests)\n\"\"\"\n\nlost_returns_doc = \"\"\"\n Returns\n -------\n int: number of turns lost\n\"\"\"\n\n### Gloomhaven functions ###\n\n@add_doc(turns_returns_doc)\ndef max_turns_initial(n):\n \"\"\"\n Maximum number of turns you can play, assuming no shenanigans, if you start\n with n cards in hand, no cards in discard. This also assumes you don't \n loose cards through card abilities, damage prevention, and that you only \n rest when necessary (i.e. once you've played your hand).\n \n Parameters\n ----------\n n: int\n \"\"\"\n # n even\n if (n%2 == 0):\n return (n//2)**2\n # n odd\n else:\n return (n-1)//2 * (n+1)//2\n \n \n@add_doc(turns_returns_doc)\ndef max_turns_recursive(n):\n \"\"\"\n Same as max_turns_initial, but use a recursive implementation.\n \n Parameters\n ----------\n n: int\n \"\"\"\n if n == 2:\n return 1\n else:\n return n//2 + max_turns_recursive(n-1)\n\n\n@add_doc(std_params_doc + turns_returns_doc)\ndef max_turns(n, m):\n \"\"\"\n Maximum number of turns you can play (same assumptions as max_turns_initially),\n for cards in hand and discard.\n \"\"\"\n return (n//2) + max_turns_initial(n+m-1)\n\n\n@add_doc(std_params_doc + lost_returns_doc)\ndef turns_lost(n, m):\n \"\"\"\n Number of turns lost by preventing damage. Assumes you always lose one card \n from hand if possible, otherwise 2 cards from discard\n \"\"\"\n if n == 0:\n return max_turns(n, m) - max_turns(n, m-2)\n else:\n return max_turns(n, m) - max_turns(n-1, m)\n \n\n@add_doc(std_params_doc + lost_returns_doc)\ndef turns_lost_from_disc(n, m):\n \"\"\"\n Same as turns_lost, except assumes you always choose to lose 2 cards from\n discard, instead of from hand where possible.\n \"\"\"\n return max_turns(n, m) - max_turns(n, m-2)\n\n\n@add_doc(std_params_doc + lost_returns_doc)\ndef turns_lost_early_rest(n, m):\n \"\"\"\n Compute number of turns lost by resting right now. Compare to max turns \n where we rest only once we have to.\n \"\"\"\n \n max_num_turns = max_turns(n, m)\n rest_num_turns = max_turns(n+m-1, 0)\n \n return max_num_turns - rest_num_turns\n \n \n\n"} {"blob_id": "1d2132b560e493b2d001cea3c158580f31730080", "repo_name": "pravsp/problem_solving", "path": "/Python/TrappingRainWater/TrapRainWater.py", "length_bytes": 969, "score": 4.03125, "int_score": 4, "content": "\"\"\"Solution to trap the rain water.\"\"\"\n\n\"\"\"\nProblem:\n=======\nGiven n Non-negative integers representing an elevation map where the width of\neach bar is 1, compute how much water it is able to trap after raining\n\"\"\"\nclass TrapRainWater:\n def trap(self, height):\n left_hieghest = 0\n right_hieghest = 0\n lmap = list()\n rmap = list()\n total_liters = 0\n for map_v in height:\n left_hieghest = max(left_hieghest, map_v)\n lmap.append(left_hieghest)\n\n for map_v in height[::-1]:\n right_hieghest = max(right_hieghest, map_v)\n rmap.append(right_hieghest)\n\n for elem,l_h,r_h in zip(height,lmap,reversed(rmap)):\n total_liters = total_liters + (min(l_h, r_h) - elem)\n\n return total_liters\n\nif __name__ == '__main__':\n elv_map = [0,1,0,2,1,0,1,3,2,1,2,1]\n trapped_water = TrapRainWater().trap(elv_map)\n print(\"Amount of water trapped: \", trapped_water)\n"} {"blob_id": "dce707766fffe15ebc6702fa82ce9f6148eea612", "repo_name": "JeromeLee-ljl/leetcode", "path": "/001~050/_031_next_permutation.py", "length_bytes": 1646, "score": 3.59375, "int_score": 4, "content": "class Solution:\n def nextPermutation(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: void Do not return anything, modify nums in-place instead.\n \"\"\"\n i = len(nums) - 2\n while i >= 0:\n if nums[i] < nums[i + 1]:\n left, right = i + 1, len(nums) - 1\n while left < right - 1:\n center = (left + right) // 2\n mid = nums[center]\n if nums[i] >= mid:\n right = center\n else:\n left = center\n if nums[i] >= nums[right]:\n right -= 1\n nums[i], nums[right] = nums[right], nums[i]\n break\n i -= 1\n #\n # for i in range(len(nums) - 2, -2, -1):\n # if i >= 0 and nums[i] < nums[i + 1]:\n # left, right = i + 1, len(nums) - 1\n # while left < right - 1:\n # center = (left + right) // 2\n # mid = nums[center]\n # if nums[i] >= mid:\n # right = center\n # else:\n # left = center\n # if nums[i] >= nums[right]:\n # right -= 1\n # nums[i], nums[right] = nums[right], nums[i]\n # break\n\n left, right = i + 1, len(nums) - 1\n while left < right:\n nums[right], nums[left] = nums[left], nums[right]\n left += 1\n right -= 1\n\n print(nums)\n\n\nif __name__ == '__main__':\n Solution().nextPermutation([3, 2, 1])\n"} {"blob_id": "92d69cc9d69ffa986c1500254d67ec4edaa4490d", "repo_name": "jfsawyer88/CodeEval", "path": "/1-Easy/004-SumofPrimes/SumOfPrimes.py", "length_bytes": 1582, "score": 3.6875, "int_score": 4, "content": "## CodeEval\n## Sum of Primes\n\nimport sys\nimport math\n\n\ndef prime_pi(n):\n \"count primes below n\"\n r = int(n ** 0.5)\n V = [n//i for i in range(1,r+1)]\n V += list(range(V[-1]-1,0,-1))\n S = {i:i-1 for i in V}\n for p in range(2,r+1):\n if S[p] > S[p-1]: # p is prime\n sp = S[p-1] # sum of primes smaller than p\n p2 = p*p\n for v in V:\n if v < p2: break\n S[v] -= (S[v//p] - sp)\n return S[n]\n\n\ndef sum_of_primes_below(n):\n r = int(n**0.5)\n assert r*r <= n and (r+1)**2 > n\n V = [n//i for i in range(1,r+1)]\n V += list(range(V[-1]-1,0,-1))\n S = {i:i*(i+1)//2-1 for i in V}\n for p in range(2,r+1):\n if S[p] > S[p-1]: # p is prime\n sp = S[p-1] # sum of primes smaller than p\n p2 = p*p\n for v in V:\n if v < p2: break\n S[v] -= p*(S[v//p] - sp)\n return S[n]\n\n\nn = 1000 # int(sys.argv[1])\n\ndef sum_of_first_primes(n):\n init = int(n * (math.log(n) + (math.log(math.log(n)) - 1) + (math.log(math.log(n))-2)/(math.log(n)) - (((math.log(math.log(n)))**2) - 6*math.log(math.log(n) + 11))/(2 * math.log(n)**2)))\n\n pp = prime_pi(init)\n while pp != n:\n \n i = 0\n while pp > n:\n pp = prime_pi(init - 2**i)\n i = i + 1\n init = init - 2**(i-1)\n\n i = 0\n while pp < n:\n pp = prime_pi(init + 2**i)\n i = i + 1\n init = init + 2**(i-1)\n\n return sum_of_primes_below(init)\n\n\nsys.stdout.write(str(sum_of_first_primes(n)) + '\\n')\n"} {"blob_id": "006bea4018aa98977a2720f167bb0c81ed724aca", "repo_name": "4dsolutions/School_of_Tomorrow", "path": "/ivm_tetra_edges.py", "length_bytes": 3962, "score": 3.5, "int_score": 4, "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nSee:\nhttps://oeis.org/A007531\nNumber of contact points between equal spheres \narranged in a tetrahedron with n - 1 spheres \nin each edge. - Ignacio Larrosa Ca\u00f1estro, Jan 07 2013\n\nhttps://oeis.org/A035006\nNumber of contact points between equal spheres \narranged in a half octahedron with n - 1 spheres \nin each edge. - Kirby Urner, Apr 27 2021\n\nhttps://oeis.org/A300758\nNumber of contact points between equal spheres \narranged in an octahedron with n - 1 spheres \nin each edge. - Kirby Urner, Apr 27 2021\n\n[0, 36, 216, 660, 1488, 2820, 4776, 7476, 11040, 15588]\nNumber of contact points between equal spheres \narranged in cuboctahedron with n spheres \nin each edge. - Kirby Urner, Apr 30 2021\n\nhttps://oeis.org/A069074\nNumber of contact points between equal spheres \narranged in layer n of a cuboctahedron with n \nintervals between balls along each edge. \n- Kirby Urner, Apr 30 2021\n\nWith thanks to\nhttps://www.instagram.com/struppipohl/\nwho derived the tet_edges result as well.\n\n>>> [tet_edges(n) for n in range(1, 100)] \n[6,\n 24,\n 60,\n 120,\n 210,\n 336,\n 504,\n 720,\n 990,\n 1320,\n ...\n 884640,\n 912576,\n 941094,\n 970200,\n 999900]\n\"\"\"\n\ndef tri(n : int) -> int:\n \"Triangular number n\"\n return (n)*(n+1)//2\n \ndef sqr(n : int) -> int:\n \"Square number n\"\n return n**2\n\ndef tet_edges(f : int) -> int:\n \"\"\"\n Each layer of tri(N) balls 3, 10, 15...\n spawns N tetrahedrons of 6 edges each, accumulating \n to give a next layer of tri(N+1) balls, and so on.\n f = frequency (number of intervals along each edge)\n \"\"\"\n cumm = 0\n for layer in range(1, f+1):\n if layer == 1: # initial frequency\n cumm = 6\n else:\n cumm = cumm + tri(layer)*6\n return cumm \n\ndef half_oct_edges(f : int) -> int:\n \"\"\"\n Each layer of sqr(N) balls 4, 9, 16...\n spawns N half-octahedrons, with 4*N edges\n to the next layer of N+1 balls per edge, \n plus (layer+1)*layer*2 layer edges.\n \"\"\"\n cumm = 0\n for layer in range(1, f+1):\n if layer == 1: # initial frequency\n cumm = 8\n else:\n cumm = cumm + \\\n sqr(layer)*4 + \\\n (layer+1)*layer*2\n return cumm \n\ndef oct_edges(f : int) -> int:\n \"\"\"\n Two half-octas minus the layer they have in common\n \"\"\"\n return 2*half_oct_edges(f) - (f+1)*f*2\n\ndef cubocta_edges(f: int) -> int: \n \"\"\"\n Number of contact points between equal spheres \n arranged in a cuboctahedron with f i.e. n-1 \n intervals between balls along in each edge.\n \"\"\"\n x = f+1 \n return 20*x**3 - 48*x**2 + 40*x - 12 \n\ndef cubocta_layer(f: int) -> int:\n \"\"\"\n Number of contact points between equal spheres \n arranged in layer n of a cuboctahedron with n \n intervals between balls along in each edge.\n \"\"\"\n x = f-1\n return 8*x**3 + 36*x**2 + 52*x + 24 \n\ndef make_table(n:int, nm:str = \"edges_table.txt\", s:str = \"tetra\") -> None:\n \"\"\"\n n: up to max frequency\n nm: name of output file\n s: shape used for accumulating \n (\"tetra\", \"hocta\", \"octa\", \"cubocta\", \"layer\")\n \n prints a file as a side effect, using either \n tetra or half-octa edge accumulator as f:Callable = global function\n \"\"\"\n template = \"{:3}. {:10d}\"\n if s==\"tetra\":\n f = tet_edges\n elif s==\"hocta\":\n f = half_oct_edges # globals \n elif s==\"octa\":\n f = oct_edges \n elif s==\"cubocta\":\n f = cubocta_edges\n elif s==\"layer\":\n f = cubocta_layer\n with open(nm, \"w\") as output:\n print(\"Freq Edges\", file=output)\n print(\"---------------\", file=output)\n for i in range(n):\n print(template.format(i, f(i)), file=output)\n\n \ndef a007531(n):\n \"tetra edges (ball contacts)\"\n return n*(n+1)*(n+2)\n\ndef a035006(n):\n \"half octa edges (ball contacts)\"\n return n*2*(n+1)**2\n\ndef a300758(n):\n \"octa edges (ball contacts)\"\n return 2*n*(n+1)*(2*n+1)\n"} {"blob_id": "01db338d18893fed2689056c5b9d20ae3f102b06", "repo_name": "Moby5/myleetcode", "path": "/python/225_Implement_Stack_using_Queues.py", "length_bytes": 3792, "score": 4.03125, "int_score": 4, "content": "#!/usr/bin/env python\n# coding=utf-8\n\n\"\"\"\nhttp://bookshadow.com/weblog/2015/06/11/leetcode-implement-stack-using-queues/\n\n225. Implement Stack using Queues\nImplement the following operations of a stack using queues.\npush(x) -- Push element x onto stack.\npop() -- Removes the element on top of the stack.\ntop() -- Get the top element.\nempty() -- Return whether the stack is empty.\nNotes:\nYou must use only standard operations of a queue -- which means only push to back, peek/pop from front, size, and is empty operations are valid.\nDepending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.\nYou may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).\n\n\u9898\u76ee\u5927\u610f\uff1a\n\u4f7f\u7528\u961f\u5217\u5b9e\u73b0\u6808\u7684\u4e0b\u5217\u64cd\u4f5c\uff1a\n\npush(x) -- \u5c06\u5143\u7d20x\u538b\u5165\u6808.\npop() -- \u79fb\u9664\u6808\u9876\u5143\u7d20.\ntop() -- \u83b7\u5f97\u6808\u9876\u5143\u7d20.\nempty() -- \u8fd4\u56de\u6808\u662f\u5426\u4e3a\u7a7a.\n\n\u6ce8\u610f\uff1a\n\n\u4f60\u53ef\u4ee5\u5047\u8bbe\u6240\u6709\u7684\u64cd\u4f5c\u90fd\u662f\u6709\u6548\u7684\uff08\u4f8b\u5982\uff0c\u4e0d\u4f1a\u5bf9\u7a7a\u6808\u6267\u884cpop\u6216\u8005top\u64cd\u4f5c\uff09\n\u53d6\u51b3\u4e8e\u4f60\u4f7f\u7528\u7684\u8bed\u8a00\uff0cqueue\u53ef\u80fd\u6ca1\u6709\u88ab\u539f\u751f\u652f\u6301\u3002\u4f60\u53ef\u4ee5\u4f7f\u7528list\u6216\u8005deque\uff08\u53cc\u7aef\u961f\u5217\uff09\u6a21\u62df\u4e00\u4e2a\u961f\u5217\uff0c\u53ea\u8981\u4fdd\u8bc1\u4f60\u4ec5\u4ec5\u4f7f\u7528\u961f\u5217\u7684\u6807\u51c6\u64cd\u4f5c\u5373\u53ef\u2014\u2014\u4ea6\u5373\u53ea\u6709\u5982\u4e0b\u64cd\u4f5c\u662f\u6709\u6548\u7684\uff1a\npush to back\uff08\u52a0\u5165\u961f\u5c3e\uff09\uff0cpop from front\uff08\u5f39\u51fa\u961f\u9996\uff09\uff0csize\uff08\u53d6\u961f\u5217\u5927\u5c0f\uff09\u4ee5\u53cais empty\uff08\u5224\u65ad\u662f\u5426\u4e3a\u7a7a\uff09\n\n\u89e3\u9898\u601d\u8def\uff1a\n# push(x) -- \u4f7f\u7528queue\u7684push to back\u64cd\u4f5c.\n# pop() -- \u5c06queue\u4e2d\u9664\u961f\u5c3e\u5916\u7684\u6240\u6709\u5143\u7d20pop from front\u7136\u540epush to back\uff0c\u6700\u540e\u6267\u884c\u4e00\u6b21pop from front\n# top() -- \u5c06queue\u4e2d\u6240\u6709\u5143\u7d20pop from front\u7136\u540epush to back\uff0c\u4f7f\u7528\u8f85\u52a9\u53d8\u91cftop\u8bb0\u5f55\u6bcf\u6b21\u5f39\u51fa\u7684\u5143\u7d20\uff0c\u8fd4\u56detop\n# empty() -- \u4f7f\u7528queue\u7684is empty\u64cd\u4f5c.\n\"\"\"\n\n\nclass MyStack(object):\n\n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n self.queue = []\n \n\n def push(self, x):\n \"\"\"\n Push element x onto stack.\n :type x: int\n :rtype: void\n \"\"\"\n self.queue.append(x)\n \n\n def pop(self):\n \"\"\"\n Removes the element on top of the stack and returns that element.\n :rtype: int\n \"\"\"\n # for x in range(len(self.queue) - 1):\n # self.queue.append(self.queue.pop(0))\n # self.queue.pop(0)\n return self.queue.pop()\n \n\n def top(self):\n \"\"\"\n Get the top element.\n :rtype: int\n \"\"\"\n # top = None\n # for x in range(len(self.queue)):\n # top = self.queue.pop(0)\n # self.queue.append(top)\n # return top\n return self.queue[-1]\n \n\n def empty(self):\n \"\"\"\n Returns whether the stack is empty.\n :rtype: bool\n \"\"\"\n return len(self.queue) == 0\n\n\nif __name__ == '__main__':\n obj = MyStack()\n for x in range(5):\n obj.push(x)\n param_2 = obj.pop()\n param_3 = obj.top()\n param_4 = obj.empty()\n\n print param_2\n print param_3\n print param_4\n\n\"\"\"\nclass Stack:\n # initialize your data structure here.\n def __init__(self):\n self.queue = []\n\n # @param x, an integer\n # @return nothing\n def push(self, x):\n self.queue.append(x)\n\n # @return nothing\n def pop(self):\n for x in range(len(self.queue) - 1):\n self.queue.append(self.queue.pop(0))\n self.queue.pop(0)\n\n # @return an integer\n def top(self):\n top = None\n for x in range(len(self.queue)):\n top = self.queue.pop(0)\n self.queue.append(top)\n return top\n\n # @return an boolean\n def empty(self):\n return self.queue == []\n\"\"\""} {"blob_id": "f56742594244dcc5edf17389b2b7d9c8621dbb81", "repo_name": "zhangpanzhan/leetcode-solution", "path": "/20120901 Recover Binary Search Tree.py", "length_bytes": 1158, "score": 3.78125, "int_score": 4, "content": "class TreeNode:\r\n def __init__(self, x):\r\n self.val = x\r\n self.left = None\r\n self.right = None\r\n'''\r\nTwo elements of a binary search tree (BST) are swapped by mistake.\r\n\r\nRecover the tree without changing its structure.\r\n\r\nNote:\r\nA solution using O(n) space is pretty straight forward. Could you devise a constant space solution?\r\n'''\r\n\r\n# Definition for a binary tree node\r\n# class TreeNode:\r\n# def __init__(self, x):\r\n# self.val = x\r\n# self.left = None\r\n# self.right = None\r\n\r\nclass Solution:\r\n # @param root, a tree node\r\n # @return a tree node\r\n def recoverTree(self, root):\r\n self.pre = None\r\n self.n1 = self.n2 = None\r\n self.dfs(root)\r\n self.n1.val, self.n2.val = self.n2.val, self.n1.val\r\n return root\r\n \r\n def dfs(self, root):\r\n if not root:\r\n return\r\n self.dfs(root.left)\r\n if self.pre and root.val < self.pre.val:\r\n if not self.n1:\r\n self.n1, self.n2 = self.pre, root\r\n else:\r\n self.n2 = root\r\n self.pre = root\r\n self.dfs(root.right)\r\n \r\n\r\n"} {"blob_id": "893af752512eebff4a4a534b485bcd1f9a8f9dd3", "repo_name": "AshwinHebbar314/pjelr", "path": "/014.py", "length_bytes": 655, "score": 3.5, "int_score": 4, "content": "#%%\r\ndef collatz(x):\r\n counter = 0\r\n while(x!=1):\r\n counter += 1\r\n if(x%2 == 0):\r\n x = x/2\r\n else:\r\n x = (3*x + 1)\r\n return counter+1\r\n#collatz(27)\r\n\r\n#%%\r\nimport time\r\ndef determinelen(l):\r\n longlen = 0\r\n longind = 0\r\n for i in range(l, 0, -1):\r\n #if(i%100 == 0): \r\n # print(\"i = \", i)\r\n if(i%2 != 0):\r\n if(collatz(i) > longlen):\r\n longlen = collatz(i)\r\n longind = i \r\n return longlen, longind\r\nstart = time.time()\r\nprint(determinelen(1000000))\r\nend = time.time()\r\nprint(start)\r\nprint(end)\r\nprint(end-start)\r\n# %%\r\n"} {"blob_id": "fa3bc9c81d4b37176016c1965c624b739522c510", "repo_name": "chao-shi/lclc", "path": "/572_subtree_of_another_m/substring.py", "length_bytes": 884, "score": 3.6875, "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\nclass Solution(object):\n def isSubtree(self, s, t):\n \"\"\"\n :type s: TreeNode\n :type t: TreeNode\n :rtype: bool\n \"\"\"\n def pre_order(node, res):\n if not node:\n res.append(\"#\")\n else:\n res.append(str(node.val))\n pre_order(node.left, res)\n pre_order(node.right, res)\n return res\n \n ps, pt = pre_order(s, []), pre_order(t, [])\n ps, pt = \",\".join(ps), \",\".join(pt)\n # return ps.find(pt) != -1\n idx = ps.find(pt)\n return idx != -1 and (idx == 0 or ps[idx-1] == ',')\n \n# Careful of case [12] and [2]\n# KMP for speedup substring matching"} {"blob_id": "1d32b762a1d7b214ec7254c2489f2e3c9db8f651", "repo_name": "AlanFermat/leetcode", "path": "/backtracking/211 AddSearchWord.py", "length_bytes": 1028, "score": 3.875, "int_score": 4, "content": "from collections import defaultdict as dd\nclass WordDictionary(object):\n\n\tdef __init__(self):\n\t\t\"\"\"\n\t\tInitialize your data structure here.\n\t\t\"\"\"\n\t\tself.child = dd(WordDictionary)\n\t\tself.isleaf = False\n\t\t\n\t\t\n\n\tdef addWord(self, word):\n\t\t\"\"\"\n\t\tAdds a word into the data structure.\n\t\t:type word: str\n\t\t:rtype: void\n\t\t\"\"\"\n\t\tcurr = self\n\t\tfor c in word:\n\t\t\tcurr = curr.child[c]\n\t\tcurr.isleaf = True\n\t\t\n\t\t\n\t\t\n\n\tdef search(self, word):\n\t\t\"\"\"\n\t\tReturns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.\n\t\t:type word: str\n\t\t:rtype: bool\n\t\t\"\"\"\n\t\tdef helper(level, w, curr):\n\t\t\tif level == len(w):\n\t\t\t\treturn curr.isleaf\n\t\t\telse:\n\t\t\t\tif w[level] == \".\":\n\t\t\t\t\tcandidate = curr.child.keys()\n\t\t\t\t\tfor letter in candidate:\n\t\t\t\t\t\tif helper(level+1, w, curr.child[letter]):\n\t\t\t\t\t\t\treturn True\n\t\t\t\t\treturn False\n\t\t\t\telse:\n\t\t\t\t\tif curr.child.get(word[level]):\n\t\t\t\t\t\treturn helper(level+1, w, curr.child[w[level]])\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn False\n\t\t\t\t\t\n\t\t\t\n\t\t\t\n\t\treturn helper(0,word, self)"} {"blob_id": "a3c4626ed5309753b7225ae11d9c9b0b989eaabb", "repo_name": "TheSpeedX/codex", "path": "/python/problem_27.py", "length_bytes": 651, "score": 3.765625, "int_score": 4, "content": "import math\n\n\ndef isPrime(n):\n if n <= 1:\n return False\n if n == 2:\n return True\n for i in range(3, math.floor(math.sqrt(n)) + 1):\n if n % i == 0:\n return False\n return True\n\n\nprimes = []\n\nfor i in range(1000):\n if isPrime(i):\n primes.append(i)\n\nlongest = 0\nlargestA = 0\nlargestB = 0\n\nfor a in range(-1000, 1000):\n for b in primes:\n n = 0\n term = n ** 2 + a * n + b\n\n while isPrime(term):\n term = n ** 2 + a * n + b\n n += 1\n\n if n > longest:\n longest = n\n largestA = a\n largestB = b\n\nprint(largestA * largestB)\n"} {"blob_id": "914bf490e08ff5cd453c610ddf42d00d55a91617", "repo_name": "Rivarrl/leetcode_python", "path": "/leetcode/301-600/372.py", "length_bytes": 969, "score": 3.828125, "int_score": 4, "content": "# -*- coding: utf-8 -*-\n# ======================================\n# @File : 372.py\n# @Time : 2020/4/21 19:53\n# @Author : Rivarrl\n# ======================================\nfrom algorithm_utils import *\n\nclass Solution:\n \"\"\"\n [372. \u8d85\u7ea7\u6b21\u65b9](https://leetcode-cn.com/problems/super-pow/)\n \"\"\"\n @timeit\n def superPow(self, a: int, b: List[int]) -> int:\n # \u5feb\u901f\u5e42\n def pow(a, b):\n if b == 0: return 1\n a %= 1337\n res = 1\n while b:\n if b & 1:\n res *= a\n res %= 1337\n a *= a\n b >>= 1\n return res\n n = len(b)\n if n == 0: return 1\n res = 1\n c = b.pop()\n res *= pow(a, c)\n res *= pow(self.superPow(a, b), 10)\n res %= 1337\n return res\n\nif __name__ == '__main__':\n a = Solution()\n a.superPow(a = 2, b = [3])\n a.superPow(a = 2, b = [1,0])"} {"blob_id": "61a7141bca80b77f239764dd654796180e309a00", "repo_name": "hjalves/project-euler", "path": "/problems26-50/problem27.py", "length_bytes": 947, "score": 3.796875, "int_score": 4, "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nProject Euler - Problem 27\nQuadratic primes\n\"\"\"\n\nfrom itertools import takewhile, count\n\ndef is_prime(n):\n return n >= 2 and all(n % i != 0 for i in range(2, int(n**0.5)+1))\n\ndef formula(a, b, n):\n return n*n + a*n + b\n\ndef iter_formula(a, b):\n return (formula(a, b, i) for i in count())\n\ndef formula_primes(a, b):\n return list(takewhile(is_prime, iter_formula(a, b)))\n\ndef primelist(max):\n return list(filter(is_prime, range(max)))\n\ndef filter_a(b, min, max):\n return (a for a in range(min, max) if is_prime(1 + a + b))\n\n# Observa\u00e7\u00f5es:\n# - b tem de ser um numero primo. f(0) = b = primo\n# - a e b t\u00eam de obedecer \u00e0 seguinte rela\u00e7\u00e3o: f(1) = 1 + a + b = primo\n\nl = ((a, b, len(formula_primes(a, b))) for b in primelist(max=1000)\n for a in filter_a(b, -999, 1000))\na, b, l = max(l, key=lambda x:x[2])\nprint(a, b, l)\nprint(\"a*b:\", a*b)\n"} {"blob_id": "8d4dcc0931d3f3a15c7c8865d2a03e42d7b17616", "repo_name": "ppysjp93/Effective-Computation-in-Physics", "path": "/NumpyArrays/gradMid.py", "length_bytes": 1519, "score": 3.9375, "int_score": 4, "content": "import numpy as np \n\nprint(\"\\nPERFORMING DERIVATIVE\\n\")\n\nprint(\"\"\"The only problem with this method is the length of the gradient and\nmidpoint arrays are one less than the original arrays.\"\"\") \n\na = np.arange(10, 20)\nb = np.arange(20, 30)\na = np.array(a ** 2)\nprint(\"The points in x and y are bin boundaries in this case\")\nprint(\"y = \" + str(a))\nprint(\"x = \" + str(b))\nprint()\nprint(\"y[1:] = \" + str(a[1:])) # From 11 - 19 \nprint(\"y[:-1] = \" + str(a[:-1])) # From 10 - 18\nprint()\nprint(\"x[1:] = \" + str(b[1:])) # From 21 - 29 \nprint(\"x[:-1] = \" + str(b[:-1])) # From 20 - 28 \nprint()\nprint(\"(y[1:] - y[:-1]) / (x[1:] - x[:-1]) = \")\ngradient = (a[1:] - a[:-1]) / (b[1:] - b[:-1]) \nprint(gradient)\nprint(\"The gradient for the midpoint of the bin is given above\")\nprint(\"midpoint = (x[1:] + x[:-1])/2\")\nmidpoint = np.array((b[1:] + b[:-1])/2)\nprint(midpoint)\nprint()\nprint(\"\"\"Exercise: Create a function that takes two arrays and returns, the\nthe corresponding gradient and midpoint arrays\"\"\")\n\ndef gradMid(x, y):\n \"\"\"\n Takes two numpy arrays which act as bin boundaries of the same length and \n returns gradient and midpoints of each bin, numpy arrays with a length one \n less of the original arrays.\n \"\"\"\n gradient = (y[1:] - y[:-1]) / (x[1:] - x[:-1]) \n midpoint = np.array((x[1:] + x[:-1])/2)\n return (gradient, midpoint)\n\nx = np.arange(0, 20, 1)\ny = np.arange(0, 40, 2)\n\ngradient, midpoint = gradMid(x, y)\nprint(\"gradient = \\n\" + str(gradient))\nprint(\"midpoint = \\n\" + str(midpoint))\n\n"} {"blob_id": "b50b252970354c8d2aa79c9155ef0cbe2a59d563", "repo_name": "SilvesSun/learn-algorithm-in-python", "path": "/string/43_\u5b57\u7b26\u4e32\u76f8\u4e58.py", "length_bytes": 1687, "score": 3.65625, "int_score": 4, "content": "# \u7ed9\u5b9a\u4e24\u4e2a\u4ee5\u5b57\u7b26\u4e32\u5f62\u5f0f\u8868\u793a\u7684\u975e\u8d1f\u6574\u6570 num1 \u548c num2\uff0c\u8fd4\u56de num1 \u548c num2 \u7684\u4e58\u79ef\uff0c\u5b83\u4eec\u7684\u4e58\u79ef\u4e5f\u8868\u793a\u4e3a\u5b57\u7b26\u4e32\u5f62\u5f0f\u3002\n#\n# \u793a\u4f8b 1:\n#\n# \u8f93\u5165: num1 = \"2\", num2 = \"3\"\n# \u8f93\u51fa: \"6\"\n#\n# \u793a\u4f8b 2:\n#\n# \u8f93\u5165: num1 = \"123\", num2 = \"456\"\n# \u8f93\u51fa: \"56088\"\n#\n# \u8bf4\u660e\uff1a\n#\n#\n# num1 \u548c num2 \u7684\u957f\u5ea6\u5c0f\u4e8e110\u3002\n# num1 \u548c num2 \u53ea\u5305\u542b\u6570\u5b57 0-9\u3002\n# num1 \u548c num2 \u5747\u4e0d\u4ee5\u96f6\u5f00\u5934\uff0c\u9664\u975e\u662f\u6570\u5b57 0 \u672c\u8eab\u3002\n# \u4e0d\u80fd\u4f7f\u7528\u4efb\u4f55\u6807\u51c6\u5e93\u7684\u5927\u6570\u7c7b\u578b\uff08\u6bd4\u5982 BigInteger\uff09\u6216\u76f4\u63a5\u5c06\u8f93\u5165\u8f6c\u6362\u4e3a\u6574\u6570\u6765\u5904\u7406\u3002\n#\n# Related Topics \u6570\u5b66 \u5b57\u7b26\u4e32 \u6a21\u62df\n# \ud83d\udc4d 775 \ud83d\udc4e 0\n\n\n# leetcode submit region begin(Prohibit modification and deletion)\nclass Solution:\n def multiply(self, num1: str, num2: str) -> str:\n \"\"\"\n m,n\u5206\u522b\u8868\u793anum1 \u548c num2d\u7684\u957f\u5ea6, \u5e76\u4e14\u5747\u4e0d\u4e3a0. \u5219\u4e58\u79ef\u7684\u957f\u5ea6\u4e3a m+n-1\u6216\u8005 m+n\n \u7531\u4e8e\u4e24\u6570\u76f8\u4e58\u7684\u6700\u5927\u957f\u5ea6\u4e3a m+n, \u521b\u5efa\u4e00\u4e2a m+n \u7684\u6570\u7ec4\u5b58\u50a8\u4e58\u79ef. \u5bf9\u4e8e\u4efb\u610f\u7684 0 <=i=10, \u8fdb\u4f4d\u52a0\u5230ansArr[i+j]\n\n \u65f6\u95f4\u590d\u6742\u5ea6\u4e3a O(mn)\n \u7a7a\u95f4\u590d\u6742\u5ea6O(m+n)\n \"\"\"\n if num1 == '0' or num2 == '0':\n return '0'\n\n m, n = len(num1), len(num2)\n ans_arr = [0] * (m+n)\n for i in range(m-1, -1, -1):\n for j in range(n-1, -1, -1):\n ans_arr[i+j+1] += int(num1[i]) * int(num2[j])\n\n for i in range(m+n-1, 0, -1):\n ans_arr[i-1] += ans_arr[i] // 10\n ans_arr[i] %= 10\n\n index = 1 if ans_arr[0] == 0 else 0\n ans = \"\".join(str(x) for x in ans_arr[index:])\n return ans"} {"blob_id": "6c78847d06c260ddb9586bc7531f3959be1b258e", "repo_name": "markdawson/AIND-Sudoku", "path": "/solution.py", "length_bytes": 6065, "score": 3.84375, "int_score": 4, "content": "\nassignments = []\n\n# Define some helpful global variables\ndef cross(A, B):\n \"Cross product of elements in A and elements in B.\"\n return [a + b for a in A for b in B]\n\nrows = 'ABCDEFGHI'\ncols = '123456789'\n\nboxes = cross(rows, cols)\n\nrow_units = [cross(row, cols) for row in rows]\ncolumn_units = [cross(rows, col) for col in cols]\nsquare_units = [cross(row, col) \n for row in ['ABC', 'DEF', 'GHI'] \n for col in ['123', '456', '789']]\ndiagonal_units = [[''.join(z) for z in zip(rows, cols)],\n [''.join(z) for z in zip(rows, reversed(cols))]]\nunit_list = row_units + column_units + square_units + diagonal_units\nunits = dict((s, [u for u in unit_list if s in u]) for s in boxes)\npeers = dict((s, set(sum(units[s],[]))-set([s])) for s in boxes)\n\ndef assign_value(values, box, value):\n \"\"\"\n Please use this function to update your values dictionary!\n Assigns a value to a given box. If it updates the board record it.\n \"\"\"\n values[box] = value\n if len(value) == 1:\n assignments.append(values.copy())\n return values\n\ndef naked_twins(values):\n \"\"\"Eliminate values using the naked twins strategy.\n\n Args:\n values(dict): a dictionary of the form {'box_name': '123456789', ...}\n\n Returns:\n the values dictionary with the naked twins eliminated from peers.\n \"\"\"\n\n # Find all instances of naked twins\n # Eliminate the naked twins as possibilities for their peers\n from collections import Counter\n for unit in unit_list:\n # Collect all the twins in a unit in case there are multiple twins in one unit\n twins = [digits for digits, count in \n Counter(values[box] for box in unit if len(values[box]) == 2).items()\n if count > 1]\n\n for twin in twins:\n for box in unit:\n if set(values[box]) == set(twin): \n # Skip if this box is eactly equal to the twin\n # Take set in case order got mixed up\n continue\n for digit in twin:\n if digit in values[box]:\n new_value = values[box].replace(digit, '')\n assign_value(values, box, new_value)\n return values\n\n\ndef grid_values(grid):\n \"Convert grid into a dict of {square: char} with '.' for empties.\"\n assert len(grid) == 81\n board = []\n digits = '123456789'\n for val in grid:\n if val in digits:\n board.append(val)\n if val == '.':\n board.append(digits)\n return dict(zip(boxes, board))\n\ndef display(values):\n \"Display these values as a 2-D grid.\"\n width = max(len(values[k]) for k in boxes) + 1\n for i, row in enumerate(rows):\n if i % 3 == 0:\n if i is 0:\n print('')\n else:\n print((('-' * (width) * 3 + '-+-') * 3)[:-2])\n display_row = []\n for j, col in enumerate(cols):\n bar = ''\n if j % 3 == 2 and j is not 8:\n bar = ' | '\n display_row.append(values[row + col].center(width, ' ') + bar)\n print(''.join(display_row))\n\ndef eliminate(values):\n \"\"\"\n Elinate possibilities from a box if one of its \n peers definitely already has that value.\n \"\"\"\n for box, value in values.items():\n for unit in peers[box]:\n if len(values[unit]) == 1:\n value = value.replace(values[unit][0], '')\n # values[key] = value\n assign_value(values, box, value)\n \n return values\n\ndef only_choice(values):\n \"\"\"\n Assign a box to a value if it's the only box \n in a unit that could contain that value\n \"\"\"\n\n # To reviewer - yeah this is quite clunky compared to the \n # solution from Udacity, but I figure might as well have you \n # reveiw the one I wrote rather than copy and paste \u00af\\_(\u30c4)_/\u00af\n # Thanks in advance!!\n\n # First find all the numbers that occur only once in a unit\n for unit in unit_list:\n occurs_only_once = set()\n occurs_more_than_once = set()\n for box in unit:\n for possibility in values[box]:\n if possibility in occurs_more_than_once:\n continue\n elif possibility in occurs_only_once:\n occurs_only_once.remove(possibility)\n occurs_more_than_once.add(possibility)\n else:\n occurs_only_once.add(possibility)\n\n for box in unit:\n for possibility in values[box]:\n if possibility in occurs_only_once:\n assign_value(values, box, possibility)\n return values\n\ndef reduce_puzzle(values):\n stalled = False\n while not stalled:\n if type(values) == type('string'):\n print('Values is {}'.format(values))\n number_solved_before = len([box for box in values.keys() if len(values[box]) == 1])\n values = eliminate(values)\n values = only_choice(values)\n number_solved_after = len([box for box in values.keys() if len(values[box]) == 1])\n stalled = number_solved_before == number_solved_after\n # Sanity check\n if len([box for box in values.keys() if len(values[box]) == 0]):\n return False\n return values\n \n\ndef solve(grid):\n return search(grid_values(grid))\n\ndef search(values):\n\n value = reduce_puzzle(values)\n if value is False:\n return False\n\n if all((len(value[k]) == 1 for k in boxes)):\n return value\n\n min, min_box = min((len(values[box]), box) for box in boxes if len(values[box]) > 1)\n for possibility in value[min_box]:\n new_search_values = values.copy()\n new_search_values[min_box] = possibility\n attempt = search(new_search_values)\n if attempt:\n return attempt\n\ntry:\n from visualize import visualize_assignments\n visualize_assignments(assignments)\nexcept:\n print('We could not visualize your board due to a pygame issue. Not a problem! It is not a requirement.')\n"} {"blob_id": "22f8114028d0f872c8072223af30d79abfdbc52a", "repo_name": "puttak/CS433", "path": "/ex02/template/stochastic_gradient_descent.py", "length_bytes": 1388, "score": 3.921875, "int_score": 4, "content": "# -*- coding: utf-8 -*-\n\"\"\"Stochastic Gradient Descent\"\"\"\n\ndef compute_stoch_gradient(y, tx, w):\n \"\"\"Compute a stochastic gradient from just few examples n and their corresponding y_n labels.\"\"\"\n # ***************************************************\n # INSERT YOUR CODE HERE\n # TODO: implement stochastic gradient computation. It's same as the gradient descent.\n # ***************************************************\n grad = compute_gradient(y, tx, w)\n return grad\n\n\ndef stochastic_gradient_descent(\n y, tx, initial_w, batch_size, max_iters, gamma):\n \"\"\"Stochastic gradient descent algorithm.\"\"\"\n # ***************************************************\n # INSERT YOUR CODE HERE\n # TODO: implement stochastic gradient descent.\n # ***************************************************\n ws = [initial_w]\n losses = []\n w = initial_w\n for n_iter in range(max_iters):\n for y_batch, tx_batch in batch_iter(y, tx, batch_size=batch_size, num_batches=1):\n loss = compute_loss(y, tx, w)\n grad = compute_stoch_gradient(y_batch, tx_batch, w)\n w = w - gamma*grad\n ws.append(w)\n losses.append(loss)\n print(\"Stochastic Gradient Descent({bi}/{ti}): loss={l}, w0={w0}, w1={w1}\".format(\n bi=n_iter, ti=max_iters - 1, l=loss, w0=w[0], w1=w[1]))\n\n return losses, ws"} {"blob_id": "1513eb5d5b56a10e7f27d5ff10c0546ae3afa94a", "repo_name": "chengaojie0011/offer-comein", "path": "/py-project/Solution62.py", "length_bytes": 956, "score": 3.515625, "int_score": 4, "content": "# -*- coding:utf-8 -*-\nclass Solution:\n def LastRemaining_Solution(self, n, m):\n # write code here\n res = 0\n if n<1 or m<1:\n return -1\n numbers = list(range(n))\n cur = 0\n while len(numbers)>1:\n for i in range(0,m-1):\n cur +=1\n if cur == len(numbers):\n cur = 0\n numbers.remove(numbers[cur])\n if cur == len(numbers):\n cur = 0\n # print(numbers[cur])\n res = numbers[0]\n return res\n\nclass Solution2:\n def LastRemaining_Solution(self, n, m):\n # write code here\n res = 0\n if n<1 or m<1:\n return -1\n last = 0\n for i in range(2, n + 1):\n last = (last + m) % i\n return last\n\nif __name__ == \"__main__\":\n solution1 = Solution2()\n a = 5\n b = 3\n x = solution1.LastRemaining_Solution(a,b)\n print(x)\n\n # 0,1,2,3,4\n\n"} {"blob_id": "20b2ee96ffe2969985b02dd57c89ca0a111c9e0d", "repo_name": "dnr101/Neural-Net-Image-Proc", "path": "/NNetImageProc.py", "length_bytes": 6347, "score": 3.59375, "int_score": 4, "content": "#!/usr/bin/python\n\n'''\nExample of Neural Net from AI App Prog\nCSDP 638\nCreated on Jul 14, 2010\n@author: David Raizen\n'''\n\nimport random\nimport math\nfrom PIL import Image\n\n#Constants\nINPUT_NEURS = 3\nHIDDEN_NEURS = 3\nOUTPUT_NEURS = 1\nMAX_SAMPLES = 200\n#ACTION_LABLES = ['Attack', 'Run', 'Wander', 'Hide']\nLEARN_RATE = 0.2 #Rho\n\n#Neuron weight lists...\nwih = [[0] * (HIDDEN_NEURS) for i in range(INPUT_NEURS+1)]\nwho = [[0] * (OUTPUT_NEURS) for i in range(HIDDEN_NEURS+1)]\n\n#Neuron activations...\ninputs = [0] * INPUT_NEURS\nhidden = [0] * HIDDEN_NEURS\ntarget = [0] * OUTPUT_NEURS\nactual = [0] * OUTPUT_NEURS\n\n#Unit Errors\nerro = [0] * OUTPUT_NEURS\nerrh = [0] * HIDDEN_NEURS\n\n#Some simple support functions...\ndef randWeight():\n return random.uniform(-0.5, 0.5)\n \ndef getSRand():\n return random.random()\n \ndef getRand(x):\n return int(x * getSRand())\n \ndef sqr(x):\n return x*x\n \ndef assignRandomWeights():\n \"\"\"\n randomizes the weights on all neuron connections\n \"\"\"\n for inp in xrange(INPUT_NEURS+1):\n for hid in xrange(HIDDEN_NEURS):\n wih[inp][hid] = randWeight()\n #wih[inp][hid] = 42\n for hid in xrange(HIDDEN_NEURS):\n for out in xrange(OUTPUT_NEURS):\n who[hid][out] = randWeight()\n\ndef sigmoid(val):\n \"\"\"\n Squashing function for feed forward phase\n \"\"\"\n return (1.0 / (1.0 + math.exp(-val)))\n\ndef sigmoidDerivative(val):\n \"\"\"\n used in error backprop\n \"\"\"\n return (val * (1.0 - val))\n\ndef feedForward():\n \"\"\"\n Calculates the current status of the NNet, using the training data in samples[]\n \"\"\"\n #Calculate input to hidden layer\n for hid in xrange(HIDDEN_NEURS):\n sum = 0.0\n for inp in xrange(INPUT_NEURS):\n sum += inputs[inp] * wih[inp][hid]\n #Add bias...\n sum += wih[INPUT_NEURS][hid]\n hidden[hid] = sigmoid(sum)\n \n #Calculate hidden to output layer\n for out in xrange(OUTPUT_NEURS):\n sum = 0.0\n for hid in xrange(HIDDEN_NEURS):\n sum += hidden[hid] * who[hid][out]\n \n #More bias...\n sum += who[HIDDEN_NEURS][out]\n actual[out] = sigmoid(sum)\n \ndef backPropagate():\n \"\"\"\n Trains the NNet by passing error data backwards and adjusting the weights accordingly\n \"\"\"\n #Calc the error on the output layer...\n for out in xrange(OUTPUT_NEURS):\n erro[out] = (target[out] - actual[out]) * sigmoidDerivative(actual[out])\n \n #Calc the error on the hidden layer...\n for hid in xrange(HIDDEN_NEURS):\n errh[hid] = 0.0\n for out in xrange(OUTPUT_NEURS):\n errh[hid] += erro[out] * who[hid][out]\n errh[hid] *= sigmoidDerivative(hidden[hid])\n \n #Update weights on the output layer...\n for out in xrange(OUTPUT_NEURS):\n for hid in xrange(HIDDEN_NEURS):\n who[hid][out] += (LEARN_RATE * erro[out] * hidden[hid]) \n #Update the bias...\n who[HIDDEN_NEURS][out] += (LEARN_RATE * erro[out])\n \n #Update weights on the hidden layer...\n for hid in xrange(HIDDEN_NEURS):\n for inp in xrange(INPUT_NEURS):\n wih[inp][hid] += (LEARN_RATE * errh[hid] * inputs[inp])\n #Update the bias...\n wih[INPUT_NEURS][hid] += (LEARN_RATE * errh[hid])\n \nclass element ():\n \"\"\"\n Simple training data object\n \"\"\"\n def __init__(self, pixel = (0, 0, 0), out = 0):\n self.pixel = pixel\n self.out = out\nimgIn = Image.open('test.jpg')\npix = imgIn.load()\nsamples = [] \n#Training data for the feedForward phase\n#samples = [element([1, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0] ), \\\n# element([0, 1, 1, 0, 0, 0, 0], [0, 0, 0, 1] ), \\\n# element([1, 1, 0, 1, 1, 0, 1], [0, 0, 1, 0] ), \\\n# element([1, 1, 1, 1, 0, 0, 1], [0, 0, 1, 1] ), \\\n# element([0, 1, 1, 0, 0, 1, 1], [0, 1, 0, 0] ), \\\n# element([1, 0, 1, 1, 0, 1, 1], [0, 1, 0, 1] ), \\\n# element([1, 0, 1, 1, 1, 1, 1], [0, 1, 1, 0] ), \\\n# element([1, 1, 1, 0, 0, 0, 0], [0, 1, 1, 1] ), \\\n# element([1, 1, 1, 1, 1, 1, 1], [1, 0, 0, 1] ), \\\n# element([1, 1, 1, 0, 0, 1, 1], [1, 0, 0, 1] )]\nfor i in xrange(10, 20):\n for j in xrange(10, 20):\n testPx = pix[i, j]\n samples.append(element(testPx, 1))\nfor i in xrange(225, 235):\n for j in xrange(150, 160):\n testPx = pix[i, j]\n samples.append(element(testPx, 0))\n\ndef action(vect):\n \"\"\"\n Binary display output function\n \"\"\"\n \n if vect >= 0.5:\n vect = 1.0\n else:\n vect = 0.0\n \n return vect\n\n\ndef main():\n \"\"\"\n Train the NNet and then allow the user to test it interactively \n \"\"\"\n \n sample = -1\n iterations = 0\n sum = 0\n fout = open('stats.txt', 'w')\n random.seed()\n assignRandomWeights()\n #Train the network...\n while True:\n sample += 1\n if sample >= MAX_SAMPLES:\n sample = 0\n\n for i in xrange(3):\n inputs[i] = samples[sample].pixel[i]\n \n target[0] = samples[sample].out\n \n feedForward()\n \n err = 0.0\n \n err += sqr(samples[sample].out - actual[0])\n err *= 0.5\n \n fout.write('%2.8f \\n' %err)\n print 'mse = %2.8f \\n' % err\n \n if iterations > 100000:\n break\n iterations += 1\n backPropagate()\n #Test the NNet against the training data \n for i in xrange(MAX_SAMPLES):\n for j in xrange(3):\n inputs[j] = samples[sample].pixel[j]\n\n \n target[0] = samples[sample].out\n \n feedForward()\n \n if action(actual) != action(target):\n for j in xrange(3):\n print inputs[j], \n print action(actual), action(target)\n else:\n sum += 1\n \n print 'Network is %2.2f%% correct\\n' %((float(sum)/MAX_SAMPLES) * 100)\n \n #Allow the user to test the NNet interactively\n for x in xrange(640):\n for y in xrange(500):\n testPx = pix[x, y]\n for i in xrange(3):\n inputs[i] = testPx[i]\n feedForward()\n if action(actual[0]) < 0.5:\n pix[x, y] = (0, 0, 0)\n imgIn.save('test2.jpg')\n \n fout.close()\n \nif __name__ == '__main__':\n main()\n "} {"blob_id": "b00a279f932aaa6c0a1b418ce5ab08cb4fd2de6b", "repo_name": "patrickqrim/CSUF-Optimized-C4.5", "path": "/attribute_selection_methods.py", "length_bytes": 3267, "score": 3.5, "int_score": 4, "content": "import csv\nimport math\nimport continuous_attribute_split as cas\nfrom pprint import pprint\n'''\nModule that imports data and contains attribute selection methods.\n\nVariables\n-------\nclass_attribute : string\n attribute used for ultimate classification of the data\ndata : list of dictionaries\n data imported from file (created in cas module )\n\nMethods\n-------\ninfo(D), info_A(D, attribute), gain(D, attribute), splitInfo(D, attribute), gain_ratio(D, attribute)\n'''\nclass_attribute = cas.class_attribute\ndata = [] # a list of dictionaries\n#imports data from file (created in cas module)\nwith open('training_data_split.csv') as f:\n reader = csv.DictReader(f, delimiter=',')\n for line in reader:\n data.append(line)\n\ndef info(D):\n '''\n Method that calculates expected information (entropy) needed to classify a tuple in a set of data.\n \n Parameters\n -------\n D : list\n a particular set of data\n '''\n samples = []\n entropy = 0\n for x in D:\n samples.append(x[class_attribute])\n for i in set(samples):\n p = samples.count(i) / len(samples)\n entropy+=p*math.log2(p)\n return entropy*-1\n\ndef infoA(D, attribute):\n '''\n Method that calculates information needed after using a certain attribute to split the data.\n \n Parameters\n -------\n D : list\n a particular set of data\n attribute : string\n attribute used to split the data\n '''\n samples = []\n info_needed = 0\n for x in D:\n samples.append(x[attribute])\n for i in set(samples):\n p = samples.count(i) / len(samples)\n subset = []\n for x in D:\n if x[attribute] == i:\n subset.append(x)\n info_needed+=p*info(subset)\n return info_needed\n\ndef gain(D, attribute):\n '''\n Method that calculates information gain by splitting the data with attribute A.\n \n Parameters\n -------\n D : list\n a particular set of data\n attribute : string\n attribute used to split the data\n '''\n return info(D) - infoA(D, attribute)\n\ndef splitInfo(D, attribute):\n '''\n Method that calculates the split information of an attribute for a set of data.\n \n Parameters\n -------\n D : list\n a particular set of data\n attribute : string\n attribute used to split the data\n '''\n samples = []\n split_info = 0\n for x in D:\n samples.append(x[attribute])\n for i in set(samples):\n p = samples.count(i) / len(samples)\n split_info += p*math.log2(p)\n return split_info * -1\n\ndef gainRatio(D, attribute):\n '''\n Method that calculates the gain ratio of an attribute for a set of data.\n \n Parameters\n -------\n D : list\n a particular set of data\n attribute : string\n attribute used to split the data\n '''\n # **IMPORTANT**: splitInfo becomes 0 when there is 1 in each category\n # This is because log2(1) = 0\n # I'm not sure how to correct this but for now I replaced it with 0.0000001 and it seems to work\n if splitInfo(D, attribute) == 0:\n return gain(D, attribute) / 0.0000001\n return gain(D, attribute) / splitInfo(D, attribute)\n\n# printing stuff to see if they work:\n#print(gainRatio(data, 'income'))\n#pprint(data)\n"} {"blob_id": "7e0a1a3b4e5c9df5194249a60363ec710e3dfdaf", "repo_name": "ellinj2/Past_Projects", "path": "/CSCI1100/Simple_Spell_Check/hw7Part1.py", "length_bytes": 6924, "score": 4.0, "int_score": 4, "content": "'''\nThis code checks a set of input words against a set of known words. If the word isn't in the dictionary, it tries\ndropping each letter and checking the new word, then inserting each letter in the alphabet into each index and\nchecking the new words, then swapping consecutive letters and checking the new words, then replacing each letter\nwith a letter form the set of possible letters from the keyboard input. It then returns the top 3 matches by\nthe frequency ratings found in the dictionary file. If no matches are found, return thusly.\n\nDate: November 9, 2018\nAuthor: Jesse Ellin\nVersion: 1.2\n'''\n\ndef check_word(word, dic):\n '''Checks if the word -word- is in the dictionary -dic-'''\n if word in dic:\n return True\n return False\n\ndef drop(word, dic):\n '''checks if the word -word- is in the dictionary -dic- after dropping each letter individually'''\n possible = set()\n for i in range(0, len(word)):\n lst = [letter for letter in word]\n del lst[i]\n temp = ''.join(lst)\n '''if word == 'darmed':\n print(temp)'''\n if check_word(temp, dic):\n possible.add(temp)\n\n if possible: #is there anything in the list of possible words?\n return list(possible)\n return False\n\ndef flatten(lst):\n '''Creates a flat list out of a list of lists'''\n flat_list = []\n for i in range(0, len(lst)):\n if isinstance(lst[i], list): #if the item is a list\n flat_list.extend(flatten(lst[i])) #extend flat list by a flattened lst\n else:\n flat_list.append(lst[i]) #add the item\n\n return flat_list\n\ndef get_dictionary(name):\n '''Converts file to dictionary'''\n out = dict()\n with open(name, 'r') as file:\n temp = file.read().strip().split('\\n')\n semi = [line.strip().split(',') for line in temp]\n for item in semi:\n out[item[0]] = item[1]\n\n return out\n\ndef insert(word, dic):\n '''Inserts and checks each possible letter at each possible index'''\n possible = set()\n alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',\\\n 'u', 'v', 'w', 'x', 'y', 'z']\n lst = [letter for letter in word]\n #checks every possible letter in every possible index\n for i in range(0, len(lst)):\n for letter in alphabet:\n templst = lst[:]\n templst.insert(i, letter)\n if check_word(''.join(templst), dic):\n possible.add(''.join(templst))\n if possible: #Is there anything in the list of possible words?\n return list(possible)\n return False\n\ndef listify(name):\n '''Turns a file into a list'''\n file = open(name, 'r')\n temp = file.read().strip().split('\\n')\n file.close()\n\n return temp\n\ndef replace(word, dic, keyboard):\n '''checks if the word -word- is in the dictionary -dic- after replacing each letter with each letter from the\n alphapbet individually'''\n possible = set()\n lst = [letter for letter in word]\n #check every possible index\n for i in range(0, len(lst)):\n alphabet = keyboard.get(lst[i])\n if alphabet:\n for item in alphabet:\n templst = lst[:]\n templst[i] = item\n '''if word == 'darmed':\n print(''.join(templst))'''\n if check_word(''.join(templst), dic):\n possible.add(''.join(templst))\n\n if possible: #is there anything in the list of possible words?\n return list(possible)\n return False\n\ndef swap(word, dic):\n '''checks if the word -word- is in the dictionary -dic- after swapping neighboring letters'''\n possible = set()\n lst = [letter for letter in word]\n #check every possible index except the last one\n for i in range(0, len(word) - 1):\n templst = lst[:]\n templst[i], templst[i + 1] = templst[i + 1], templst[i]\n if check_word(''.join(templst), dic):\n possible.add(''.join(templst))\n\n if possible: #is there anything in the list of possible words?\n return list(possible)\n return False\n\ndef run():\n '''does the things'''\n #print('Hello world!')\n dictionaryname = input('Dictionary file => ')\n print(dictionaryname)\n wordsname = input('Input file => ')\n print(wordsname)\n keyboardname = input('Keyboard file => ')\n print(keyboardname)\n\n #dictionaryname = 'words_10percent.txt'\n #wordsname = 'input_words.txt'\n #keyboardname = 'keyboard.txt'\n\n words = listify(wordsname)\n dictionary_setup = dict()\n with open(dictionaryname, 'r') as file:\n temp = file.read().strip().split('\\n')\n semi = [line.strip().split(',') for line in temp]\n for item in semi:\n dictionary_setup[item[0]] = item[1]\n\n dictionary = list(set(dictionary_setup.keys()))\n\n keyboard = dict()\n with open(keyboardname, 'r') as file:\n temp = file.read().strip().split('\\n')\n semi = [line.strip().split(' ') for line in temp]\n for item in semi:\n keyboard[item[0]] = item[1:]\n\n #check each word\n for word in words:\n #print(word)\n word = word.strip()\n if check_word(word, dictionary):\n print('{:15s} -> {:15s} :FOUND'.format(word, word))\n else:\n possible = []\n result_type = dict()\n if drop(word, dictionary) is not False:\n possible.append(drop(word, dictionary))\n for item in drop(word, dictionary):\n result_type[item] = 'DROP'\n if insert(word, dictionary) is not False:\n possible.append(insert(word, dictionary))\n for item in insert(word, dictionary):\n result_type[item] = 'INSERT'\n if swap(word, dictionary) is not False:\n possible.append(swap(word, dictionary))\n for item in swap(word, dictionary):\n result_type[item] = 'SWAP'\n if replace(word, dictionary, keyboard) is not False:\n possible.append(replace(word, dictionary, keyboard))\n for item in replace(word, dictionary, keyboard):\n result_type[item] = 'REPLACE'\n if not drop(word, dictionary) and not insert(word, dictionary) and not swap(word, dictionary)\\\n and not replace(word, dictionary, keyboard):\n print('{0:15s} -> {0:15s} :NO MATCH'.format(word))\n else:\n outcomes = []\n for item in flatten(possible):\n outcomes.append([dictionary_setup.get(item), item])\n outcomes.sort(reverse=True)\n result = [item[1] for item in outcomes]\n\n output = result[0:3]\n\n for i in range(0, len(output)):\n print('{:15s} -> {:15s} :MATCH {}'.format(word, output[i], i + 1))\n\n\nrun()\n"} {"blob_id": "f34ace8f794dba90324f2f96cd5673e347608e8a", "repo_name": "Pandinosaurus/Deep-Reinforcement-Learning-Algorithms-with-PyTorch", "path": "/environments/Ant_Navigation_Environments.py", "length_bytes": 2608, "score": 3.53125, "int_score": 4, "content": "from .ant_environments.create_maze_env import create_maze_env\nimport numpy as np\n\n\"\"\"Environments taken from HIRO paper github repo: https://github.com/tensorflow/models/tree/master/research/efficient-hrl\nThere are three environments that can be represented by this class depending on what environment_name you provide. \nThe options are: [\"AntMaze\", \"AntPush\", \"AntFall\"].\n\nNote that \"Success\" for this game is defined by the authors as achieving -5 or more on the last step of the episode \nbut that this isn't coded in anyway as part of the environment. \n\"\"\"\nclass Ant_Navigation_Environments(object):\n\n def __init__(self, environment_name):\n self.environment_name = environment_name\n self.base_env = create_maze_env(env_name=self.environment_name).gym #\n\n self.goal_sample_fn = self.get_goal_fn()\n self.reward_fn = self.get_reward_fn()\n self.goal = None\n\n self.unwrapped = self.base_env.unwrapped\n self.spec = self.base_env.spec\n self.action_space = self.base_env.action_space\n\n def reset(self):\n self.steps_taken = 0\n obs = self.base_env.reset()\n self.goal = self.goal_sample_fn()\n return np.concatenate([obs, self.goal])\n\n def step(self, action):\n self.steps_taken += 1\n obs, _, _, info = self.base_env.step(action)\n reward = self.reward_fn(obs, self.goal)\n done = self.steps_taken >= 500\n return np.concatenate([obs, self.goal]), reward, done, info\n\n def get_goal_fn(self):\n \"\"\"Produces the function required to generate a goal for each environment\"\"\"\n if self.environment_name == \"AntMaze\":\n return lambda: np.array([0., 16.])\n #Can also use np.random.uniform((-4, -4), (20, 20)) for training purposes\n elif self.environment_name == \"AntPush\":\n return lambda: np.array([0., 19.])\n elif self.environment_name == \"AntFall\":\n return lambda: np.array([0., 27., 4.5])\n else:\n raise ValueError(\"Unknown environment name\")\n\n def get_reward_fn(self):\n \"\"\"Provides function required to calculates rewards for each game\"\"\"\n if self.environment_name == 'AntMaze':\n return lambda obs, goal: -np.sum(np.square(obs[:2] - goal)) ** 0.5\n elif self.environment_name == 'AntPush':\n return lambda obs, goal: -np.sum(np.square(obs[:2] - goal)) ** 0.5\n elif self.environment_name == 'AntFall':\n return lambda obs, goal: -np.sum(np.square(obs[:3] - goal)) ** 0.5\n else:\n raise ValueError(\"Unknown environment name\")\n\n\n\n\n"} {"blob_id": "1a36432332636bb9a5b54efe452e5b7467b49fb8", "repo_name": "baduy9x/AlgorithmPractice", "path": "/validate_bst.py", "length_bytes": 503, "score": 3.765625, "int_score": 4, "content": "\"\"\" Node is defined as\nclass node:\n def __init__(self, data):\n self.data = data\n self.left = None\n self.right = None\n\"\"\"\n\ndef check(root, MIN, MAX):\n if root is None:\n return True\n if root.left is None and root.right is None:\n if MIN < root.data < MAX:\n return True\n return False\n \n return check(root.left, MIN, root.data) and check(root.right, root.data, MAX)\n\ndef checkBST(root):\n return check(root, -float(\"inf\"), float(\"inf\"))\n\n"} {"blob_id": "a7022d4acdad24db3974f4624ebec2abf1023394", "repo_name": "nictrak/MappingICP", "path": "/occupancy_grid.py", "length_bytes": 3617, "score": 3.828125, "int_score": 4, "content": "import math\nimport numpy as np\nfrom functools import reduce\n\nIDENTITY = np.array([[1, 0],\n [0, 1]])\n\n\ndef raw_to_point(raw):\n # define meaning of raw data\n deg = raw[1]\n distance = raw[2]\n # deg to rad\n rad = deg * math.pi / 180\n # calculate point\n x = distance * math.cos(rad)\n y = distance * math.sin(rad)\n # return\n return x, y\n\n\ndef _project_point_onto_origin(point, num, origin=np.array([0, 0])):\n \"\"\"\n :param point: 2D point\n :param num: number of points in line space\n :param origin: origin point which we want to project to\n :return: array pf point which represent line space\n \"\"\"\n # calculate slope\n slope = reduce(lambda a, b: b / a, map(lambda a, b: a - b, point, origin))\n c = origin[1] - slope * origin[0]\n # define line space for x axis\n x_space = (np.linspace(origin[0], point[0], num))[:-1]\n # calculate y space from x space\n y_space = np.array(list(map(lambda a: slope * a + c, x_space)))\n # wrap up result\n data = np.array([x_space, y_space])\n return data\n\n\ndef project_points_onto_origin(points_t, length, origin=np.array([0, 0])):\n \"\"\"\n :param points: 2D points array\n :param length: length between points in line space\n :param grid_x: the line space for x axis to make histogram\n :param grid_y: the line space for y axis to make histogram\n :param origin: the origin which we want to be projected onto\n :return: 2D points array of lines which are projection of inputs\n \"\"\"\n # find distances from origins\n distances = map(lambda point: math.sqrt((point[0]-origin[0])**2 + (point[1]-origin[1])**2), points_t)\n # find number of points for line space\n nums = map(lambda dist: int(dist//length), distances)\n # project all\n projections = reduce(lambda array0, array1: np.concatenate((array0, array1), axis=0), map(lambda p, n: _project_point_onto_origin(p, n, origin).T, points_t, nums)).T\n return projections\n\n\ndef cal_positive_grid(points, grid_x, grid_y, origin=np.array([0, 0]), rotation=IDENTITY):\n if len(points[0]) <= 0:\n transform = points\n else:\n transform_t = transform_origin(points, origin=origin, rotation=rotation)\n transform = transform_t.T\n positive_grid, _, _ = np.histogram2d(transform[0], transform[1], bins=[grid_x, grid_y])\n return positive_grid * 0.5\n\n\ndef cal_negative_grid(points, length, grid_x, grid_y, origin=np.array([0, 0]), rotation=IDENTITY):\n transform_t = transform_origin(points, origin=origin, rotation=rotation)\n projections = project_points_onto_origin(transform_t, length, origin)\n raw_grid, _, _ = np.histogram2d(projections[0], projections[1], bins=[grid_x, grid_y])\n negative_grid = raw_grid * -0.5\n return negative_grid\n\n\ndef _cal_prop(value):\n ten_expo = 10 ** value\n return ten_expo / (ten_expo + 1)\n\n\ndef cal_occupancy_grid(grid):\n return np.array(list(map(lambda x: x, map(_cal_prop, grid))))\n\n\ndef transform_raw(raw):\n return np.array(list(map(raw_to_point, raw)))\n\n\ndef update_grid(grid, points_t, length, grid_x, grid_y, origin=np.array([0, 0]), rotation=IDENTITY):\n return grid + cal_positive_grid(points_t, grid_x, grid_y, origin, rotation) + cal_negative_grid(points_t, length, grid_x, grid_y, origin, rotation)\n\n\ndef occupancy_grid_to_points(occupancy_grid, min_value, max_value, length, threshold=0.95):\n # TODO\n pass\n\n\ndef transform_origin(points, origin=np.array([0, 0]), rotation=IDENTITY):\n rotated = np.dot(rotation, points)\n transform_t = np.array(list(map(lambda point: point + origin, rotated.T)))\n return transform_t\n\n\n"} {"blob_id": "eb757bf908687f99e0e3ea952930478942c715bf", "repo_name": "ayushiagarwal99/leetcode-lintcode", "path": "/leetcode/hash_table/438.find_all_anagrams_in_a_string/438.FindAllAnagramsinaString_YipingPan.py", "length_bytes": 1774, "score": 3.984375, "int_score": 4, "content": "# Source : https://leetcode.com/problems/find-all-anagrams-in-a-string/\n# Author : YipingPan\n# Date : 2020-08-13\n\n##################################################################################################### \n#\n# Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.\n# \n# Strings consists of lowercase English letters only and the length of both strings s and p will not \n# be larger than 20,100.\n# \n# The order of output does not matter.\n# \n# Example 1:\n# \n# Input:\n# s: \"cbaebabacd\" p: \"abc\"\n# \n# Output:\n# [0, 6]\n# \n# Explanation:\n# The substring with start index = 0 is \"cba\", which is an anagram of \"abc\".\n# The substring with start index = 6 is \"bac\", which is an anagram of \"abc\".\n# \n# Example 2:\n# \n# Input:\n# s: \"abab\" p: \"ab\"\n# \n# Output:\n# [0, 1, 2]\n# \n# Explanation:\n# The substring with start index = 0 is \"ab\", which is an anagram of \"ab\".\n# The substring with start index = 1 is \"ba\", which is an anagram of \"ab\".\n# The substring with start index = 2 is \"ab\", which is an anagram of \"ab\".\n# \n#####################################################################################################\n\n\nclass Solution:\n def findAnagrams(self, s: str, p: str) -> List[int]:\n if len(s) rm = k-(n-k)/2\n n = 3k - 2m => n = 3k - 2rm \n\"\"\"\n_rsymsize=8 #default, cannot be greater than 8\nclass Rsolomon:\n def __init__(self, _rm = 127):\n self.rsymsize = _rsymsize\n self.rm = _rm # m correct matches will fix all,\n self.max_rn = 2 ** self.rsymsize - 1 # max 255\n self.min_rn = 2\n # n = 3*k - 2*m , taken from thesis paper\n self.kmax = int((self.max_rn + 2 * self.rm) / 3) # kmax is 169, so number of data part is 169 (k), parity part is 86\n if self.kmax > self.max_rn:\n raise (\"self.kmax > self.max_rn\", self.kmax , self.max_rn)\n #print \"max_rn: \", self.max_rn, \" symsize: \", self.rsymsize, \" kmax: \", self.kmax # n is max 255\n\n \"\"\"\n Encode reed solomon for a given list of minutia\n \"\"\"\n def encodeSolomon(self, l, prune_extra = False):\n l2 = l\n k = len(l2) # must be <= kmax\n if prune_extra and k > self.kmax:\n print \"In encodeSolomon number of list: \"+str(k)+ \" must be less than or equal to kmax: \" + str(self.kmax)\n print \"That is why we are pruning extra points beginning from last. need a splitting solution!!\"\n l2 = l[0:self.kmax]\n k = len(l2)\n if k > self.kmax:\n raise \"In encodeSolomon number of list: \"+str(k)+ \" must be less than or equal to kmax: \" + str(self.kmax)\n n = (3 * k) - (2 * self.rm)\n if n <= k:\n n = k*(self.rm)\n #print \"k: \", k, \" n: \", n, \" rm: \", self.rm\n rcodec = rdsolomonlib.Codec(n, k, self.rsymsize)\n encoded = rcodec.encodechunks(l2)\n #print \"encoded: \", encoded\n #checksums = list(encoded[k:]) # this is the parity list\n checksums = encoded[k:] # this is the parity list\n return k, checksums, n # returns the data part length, and parity\n\n \"\"\"\n Decode reed solomon for a given list of minutia / minutia list may not be correct\n \"\"\"\n def decodeSolomon(self, data_part, k, checksum, n):\n encoded = tuple(data_part)+checksum\n assert k <= self.kmax, \"In encodeSolomon length of list must be less than or equal to kmax: \" + self.kmax\n #print \"k: \", k, \" n: \", n, \" rm: \", self.rm\n rcodec = rdsolomonlib.Codec(n, k, self.rsymsize)\n decoded, corrections = rcodec.decodechunks(encoded)\n return (decoded, corrections)\n\n \"\"\"\n Test encode reed solomon for a given list of minutia\n \"\"\"\n def encodeSolomonTest(self, l):\n k = len(l) # must be <= kmax\n n = (3 * k) - (2 * self.rm)\n assert k <= self.kmax, \"In encodeSolomon length of list must be less than or equal to kmax: \"+self.kmax\n print \"k: \", k, \" n: \", n, \" rm: \", self.rm\n rcodec = rdsolomonlib.Codec(n, k, self.rsymsize)\n rcodec2 = rdsolomonlib.Codec(n, k, self.rsymsize)\n #for decoding either rcodec or rcodec2 can be used.\n\n # exit()\n encoded = rcodec.encodechunks(l)\n print \"encoded: \", encoded\n checksums = encoded[k:] # this is the parity list\n print \"checksum-parities: \", checksums\n decoded, corrections = rcodec.decodechunks(encoded)\n print \"decoded: \", decoded\n assert cmpT(decoded, l) == True, \" Cannot decode!\"\n brokenl = list(encoded)\n brokenl = brokenl[0:k]\n random.shuffle(brokenl)\n brokenl = brokenl + list(checksums)\n for i in range(0, len(l) - self.rm):\n #for i in range(0, len(l)):\n print \"i: \", i\n brokenl[i] = 'x' * 8\n broken = tuple(brokenl)\n print \"broken: \", broken\n #decoded, corrections = rcodec.decodechunks(broken)\n ereasures = range(0,i+1)\n decoded, corrections = rcodec2.decodechunks(broken, ereasures)\n print \"to-be-decoded: \", broken\n print \"corrections: \", corrections\n assert cmpT(decoded, l)== True, \"Cannot decode!\"\n print \"decoded[0:k]: \", decoded[0:k]\n print \"\"\n\n\n#n=k*2 + 8\n\n\"\"\"\nIf P is the number of parity symbols, R is the number of errors (corrupted bytes), \nand S is the number of erasures, RS coding guarantees recoverability if the following equation is true::\n\n2R + S <= P\n Codec c = Codec(7, 5)\n can recover if 2 bytes are missing\n P=2\n\n\"\"\"\n\n\n"} {"blob_id": "c795f6ac170f96b398121ddbbc9a22cf13835061", "repo_name": "AshwinBalaji52/Artificial-Intelligence", "path": "/N-Queen using Backtracking/N-Queen_comments.py", "length_bytes": 2940, "score": 4.125, "int_score": 4, "content": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Mar 1 00:42:23 2021\r\n@author: Ashwin Balaji\r\n\"\"\"\r\n\r\n\r\nclass chessBoard:\r\n def __init__(self, dimension):\r\n # board has dimensions dimension x dimension\r\n self.dimension = dimension\r\n # columns[r] is a number c if a queen is placed at row r and column c.\r\n # columns[r] is out of range if no queen is place in row r.\r\n # Thus after all queens are placed, they will be at positions\r\n # (columns[0], 0), (columns[1], 1), ... (columns[dimension - 1], dimension - 1)\r\n self.columns = []\r\n \r\n def matrixdimension(self):\r\n return self.dimension\r\n \r\n def evaluateQueens(self):\r\n return len(self.columns)\r\n \r\n def backtrackNextRow(self, column):\r\n self.columns.append(column)\r\n \r\n def popQueen(self):\r\n return self.columns.pop()\r\n \r\n def isSafe(self, column):\r\n # index of next row\r\n row = len(self.columns)\r\n \r\n # check column\r\n for queeninColumn in self.columns:\r\n if column == queeninColumn:\r\n return False\r\n \r\n # check diagonal\r\n for queeninRow, queeninColumn in enumerate(self.columns):\r\n if queeninColumn - queeninRow == column - row:\r\n return False\r\n \r\n # check other diagonal\r\n for queeninRow, queeninColumn in enumerate(self.columns):\r\n if ((self.dimension - queeninColumn) - queeninRow\r\n == (self.dimension - column) - row):\r\n return False\r\n \r\n return True\r\n \r\n def display(self):\r\n for row in range(self.dimension):\r\n for column in range(self.dimension):\r\n if column == self.columns[row]:\r\n print('Q', end=' ')\r\n else:\r\n print('.', end=' ')\r\n print()\r\n \r\n \r\ndef displaySolutions(dimension):\r\n \"\"\"Display a chessboard for each possible configuration of placing n queens\r\n on an n x n chessboard where n = dimension and print the number of such\r\n configurations.\"\"\"\r\n board = chessBoard(dimension)\r\n possibleSolutions = solutionBacktracker(board)\r\n print('Number of solutions:', possibleSolutions)\r\n \r\ndef solutionBacktracker(board):\r\n \"\"\"Display a chessboard for each possible configuration of filling the given\r\n board with queens and return the number of such configurations.\"\"\"\r\n dimension = board.matrixdimension()\r\n \r\n # if board is full, display solution\r\n if dimension == board.evaluateQueens():\r\n board.display()\r\n print()\r\n return 1\r\n \r\n possibleSolutions = 0\r\n \r\n for column in range(dimension):\r\n if board.isSafe(column):\r\n \r\n board.backtrackNextRow(column)\r\n possibleSolutions += solutionBacktracker(board)\r\n board.popQueen()\r\n \r\n return possibleSolutions\r\n \r\n \r\nsize = int(input('Dimensions : '))\r\ndisplaySolutions(size)"} {"blob_id": "67b9e880881a2b231209bafef1f036af80f00e6a", "repo_name": "owenmoogk/project-euler", "path": "/15.py", "length_bytes": 1016, "score": 3.953125, "int_score": 4, "content": "def recursion(x, y):\n # this solution is using a recursive method which takes a base case and counts possibilities from there\n # this takes way too long so we should find a better method.\n\n if x == 0 or y == 0:\n return 1\n else:\n return(solution(x-1, y) + solution(x, y-1))\n\ndef backwardCoords(x, y):\n # this solution starts by making an 2d array of points, and works backwards to solve for the point at the top left\n y += 1\n x += 1\n\n grid = [[0 for i in range(x)] for j in range(y)]\n\n # each side both bottom and right have a base case of 1\n for i in range(x):\n grid[y-1][i] = 1\n grid[i][x-1] = 1\n\n for xUpdater in reversed(range(x-1)):\n for yUpdater in reversed(range(y-1)):\n # here we just add the two possibilities of the two forks, and apply them to that grid\n grid[xUpdater][yUpdater] = grid[xUpdater+1][yUpdater] + grid[xUpdater][yUpdater+1]\n\n return(grid)\n\nif __name__ == '__main__':\n print(backwardCoords(20,20))"} {"blob_id": "561732cb8ca38a173ca1cf34d748a3fddd95e85c", "repo_name": "tianhongfeng/Lab_learn", "path": "/test_lab/test_lab_1.1.py", "length_bytes": 19043, "score": 3.984375, "int_score": 4, "content": "import random\nimport math\n# \u521d\u7ea7 1.1\n\n\n# \u968f\u673a\u751f\u6210N\u4e2a\u6570\u7684list\ndef random_list(n):\n # \u751f\u6210\u4e00\u4e2a\u7a7a\u7684 list\n nn = []\n for i in range(n):\n # \u751f\u6210 100 \u4ee5\u5185\u7684\u968f\u673a\u6570\n cc = random.randrange(100)\n nn.append(cc)\n return nn\n\n\n# 1.\u8f93\u5165\u6574\u6570N\uff0c\u968f\u673a\u751f\u6210N\u4e2a\u6570\u7684list\uff0c\u5199\u4e00\u4e2a\u51fd\u6570\uff0c\u8fd4\u56delist\u4e2d\u6700\u5927\u7684\u6570\n\ndef function1(n):\n # \u8c03\u7528\u65b9\u6cd5 \u751f\u6210n\u4e2a\u6570\u7684list\n nn = function1(n)\n # \u7528\u4e8e\u5b58\u50a8 list \u4e2d\u6700\u5927\u7684\u6570\n m = 0\n for i in range(len(nn)):\n # \u6bd4\u8f83\u5927\u5c0f\n if m < nn[i]:\n m = nn[i]\n return m\n\n\n# 2.1\u5efa\u7acb\u4e00\u4e2a\u7a7a\u7684list\uff0c\u501f\u52a9\u7a7a\u94fe\u8868\u7684\u8f85\u52a9\u7a7a\u95f4\uff0c\u5b9e\u73b0\u98981\u4e2d\u6240\u5efalist\u7684\u9006\u8f6c\ndef function2_1(n):\n # \u521b\u5efa\u4e00\u4e2a \u7a7alist \u7528\u4e8e\u8f85\u52a9\u7a7a\u95f4\n mm = []\n # \u8c03\u7528\u65b9\u6cd5 \u751f\u6210n\u4e2a\u6570\u7684list\n nn = function1(n)\n # \u83b7\u53d6 nn \u7684\u957f\u5ea6\n nl = len(nn)\n # \u904d\u5386 \u539f\u6765\u7684list\n for i in range(nl):\n mm.append(nn[-(i+1)])\n nn = mm\n return nn\n\n\n# 2.2\u7528\u5faa\u73af\u904d\u5386\u548c\u9012\u5f52\u904d\u5386\u4e24\u79cd\u65b9\u6cd5\uff0c\u5c06\u98981\u4e2d\u7684list\u539f\u5730\u9006\u8f6c\uff08\u6ce8\uff1a\u539f\u5730\u9006\u8f6c\u662f\u6307\u4e0d\u501f\u52a9\u8f85\u52a9\u7a7a\u95f4\u5c06list\u9006\u8f6c\uff09\ndef function2_2(n):\n # \u8c03\u7528\u65b9\u6cd5 \u751f\u6210n\u4e2a\u6570\u7684list\n nn = random_list(n)\n\n # \u5faa\u73af\u904d\u5386\n mm = literate(nn)\n print(mm)\n\n # \u9012\u5f52\u904d\u5386\n i = 0\n nl = len(nn)\n kk = recursion(nn, i, nl)\n print(kk[0])\n return\n\n\n\n'''\n\u7b97\u6cd5\u5b9e\u73b0\u539f\u7406: \u4e0d\u501f\u52a9 \u7b2c\u4e09\u4e2a\u53d8\u91cf\u5b9e\u73b0 \u4e24\u4e2a\u6570\u7684\u4f4d\u7f6e\u7684\u8c03\u6362\na = a + b\nb = a - b\na = a - b\n'''\n# \u5faa\u73af\u904d\u5386 \u5b9e\u73b0 list \u9006\u8f6c\ndef literate(nn):\n # \u8ba1\u7b97 list \u7684\u957f\u5ea6\n nl = len(nn)\n for i in range(int(nl/2)-1):\n nn[i] = nn[i] + nn[nl-1-i]\n nn[nl-1-i] = nn[i] - nn[nl-1-i]\n nn[i] = nn[i] - nn[nl-1-i]\n return nn\n\n\n# \u9012\u5f52\u904d\u5386\u5b9e\u73b0 list \u9006\u8f6c\ndef recursion(nn, i, nl):\n # \u9012\u5f52 \u51fa\u53e3\n if i <= int(nl/2)-1:\n nn[i] = nn[i] + nn[nl - 1 - i]\n nn[nl - 1 - i] = nn[i] - nn[nl - 1 - i]\n nn[i] = nn[i] - nn[nl - 1 - i]\n i += 1\n recursion(nn, i, nl)\n return nn, i, nl\n\n\n# 3.\u5199\u4e2a\u51fd\u6570\u68c0\u67e5\u6307\u5b9a\u7684\u5143\u7d20\u662f\u5426\u51fa\u73b0\u5728\u98981\u7684list\u4e2d\ndef function3(n, m):\n # \u8c03\u7528\u65b9\u6cd5 \u751f\u6210n\u4e2a\u6570\u7684list\n nn = random_list(n)\n # \u6807\u8bb0 \u662f\u5426\u5b58\u5728\u6307\u5b9a\u5143\u7d20\n kk = False\n for i in range(len(nn)):\n if m == nn[i]:\n kk = True\n break\n if kk is True:\n print(\"\u6307\u5b9a\u6570\u5b57\u5b58\u5728\u5217\u8868\u4e2d\")\n else:\n print(\"\u6307\u5b9a\u6570\u5b57\u4e0d\u5b58\u5728\u5217\u8868\u4e2d\")\n return\n\n\n# 4.\u5199\u4e2a\u51fd\u6570\u8fd4\u56de\u98981 list\u4e2d\u5947\u6570\u4f4d\u7f6e\u7684\u6240\u6709\u5143\u7d20\ndef function4(n):\n # \u8c03\u7528\u65b9\u6cd5 \u751f\u6210n\u4e2a\u6570\u7684list\n nn = random_list(n)\n # \u521b\u5efa\u4e00\u4e2a \u5b58\u50a8\u5947\u6570\u4f4d\u7f6e\u6240\u6709\u5143\u7d20\u7684list\n mm = []\n i = 0\n while i < len(nn):\n mm.append(nn[i])\n i += 2\n return mm\n\n\n# 5.\u5199\u4e09\u4e2a\u51fd\u6570\u6765\u8ba1\u7b97\u98981 list\u4e2d\u6570\u5b57\u7684\u548c\uff1a\u5206\u522b\u7528for\u5faa\u73af\uff0cwhile\u5faa\u73af\u548c\u9012\u5f52\u5b8c\u6210\u3002\ndef function5(n):\n # \u8c03\u7528\u65b9\u6cd5 \u751f\u6210n\u4e2a\u6570\u7684list\n nn = random_list(n)\n print(nn)\n # for \u5faa\u73af\n print(sum_for(nn))\n # while\u5faa\u73af\n print(sum_while(nn))\n # \u9012\u5f52\n i = 0\n sum_list = 0\n print(sum_recursion(nn, i, sum_list)[2])\n return\n\n\n# for \u5faa\u73af\u5b9e\u73b0 list\u4e2d\u6570\u5b57\u7684\u548c\ndef sum_for(nn):\n sum_list = 0\n for i in range(len(nn)):\n sum_list += nn[i]\n return sum_list\n\n\n# while \u5faa\u73af\u5b9e\u73b0 list\u4e2d\u6570\u5b57\u7684\u548c\ndef sum_while(nn):\n i = 0\n sum_list = 0\n while i < len(nn):\n sum_list += nn[i]\n i += 1\n return sum_list\n\n\n# \u9012\u5f52 \u5b9e\u73b0 list\u4e2d\u6570\u5b57\u7684\u548c\ndef sum_recursion(nn, i, sum_list):\n if i < len(nn):\n sum_list += nn[i]\n i += 1\n sum_list = sum_recursion(nn, i, sum_list)[2]\n return nn, i, sum_list,\n\n\n# 6.\u5199\u4e2a\u51fd\u6570on_all\u904d\u5386\u5217\u8868\u4e2d\u7684\u6bcf\u4e2a\u5143\u7d20\uff0c\u6253\u5370\u51fa\u5f00\u59cb\u768420\u4e2a\u5b8c\u5168\u5e73\u65b9\u6570\u3002\ndef function6(n):\n # \u8c03\u7528\u65b9\u6cd5 \u751f\u6210n\u4e2a\u6570\u7684list\n nn = random_list(n)\n for i in range(len(nn)):\n k = int(math.sqrt(nn[i]))\n m = k ** 2\n if m == nn[i]:\n print(nn[i])\n return\n\n\n# 7.\u968f\u673a\u751f\u6210\u4e00\u4e2alist\uff0c\u5bf9\u8be5list\u4f7f\u7528\u4e0b\u9762\u7684\u6392\u5e8f\u7b97\u6cd5\u8fdb\u884c\u6392\u5e8f\uff1a\n# TODO \u76f4\u63a5\u63d2\u5165\u6392\u5e8f\u3001\u5e0c\u5c14\u6392\u5e8f\u3001\u7b80\u5355\u9009\u62e9\u6392\u5e8f\u3001\u5806\u6392\u5e8f\u3001\u5192\u6ce1\u6392\u5e8f\u3001\u5feb\u901f\u6392\u5e8f\u3001\u5f52\u5e76\u6392\u5e8f\u3001\u5947\u5076\u6392\u5e8f\u3001\u81ed\u76ae\u5320\u6392\u5e8f\ndef function7(n):\n # \u8c03\u7528\u65b9\u6cd5 \u751f\u6210n\u4e2a\u6570\u7684list\n nn = random_list(n)\n print(nn)\n # \u5192\u6ce1\u6392\u5e8f\n # print(bubble_sort(nn))\n # \u76f4\u63a5\u63d2\u5165\u6392\u5e8f\n #print(insert_sort(nn))\n # \u7b80\u5355\u9009\u62e9\u6392\u5e8f\n #print(simple_select_sort(nn))\n # \u5e0c\u5c14\u6392\u5e8f\n # print(shell_sort(nn))\n # \u5806\u6392\u5e8f\n # print(heap_sort(nn))\n # \u5feb\u901f\u6392\u5e8f\n # print(quick_sort(nn))\n # \u5f52\u5e76\u6392\u5e8f\n # print(merge_sort(nn))\n # \u5947\u5076\u6392\u5e8f\n print(odd_even_sort(nn))\n\n return\n\n\n# \u76f4\u63a5\u63d2\u5165\u6392\u5e8f\ndef insert_sort(nn):\n # \u4ece\u5217\u8868\u7f16\u53f7\u4e3a1\u7684\u4f4d\u7f6e \u5f00\u59cb \u5faa\u73af\n for i in range(1, len(nn)):\n # j \u5b58\u50a8 \u7528\u4e8e\u4e0e \u524dj-1 \u4e2a \u6bd4\u8f83\u5927\u5c0f\u7684\u6570\u5b57\u7684\u4e0b\u6807\n j = i\n temp = nn[j]\n # \u4e0e \u524d j-1 \u4e2a \u6570\u5b57 \u6bd4\u8f83\u5927\u5c0f\n while j > 0 and temp < nn[j-1]:\n nn[j] = nn[j - 1]\n j -= 1\n nn[j] = temp\n return nn\n\n\n# \u7b80\u5355\u9009\u62e9\u6392\u5e8f\ndef simple_select_sort(nn):\n for i in range(len(nn)):\n k = i\n for j in range(i + 1, len(nn)):\n if nn[j] < nn[k]:\n k = j\n temp = nn[i]\n nn[i] = nn[k]\n nn[k] = temp\n return nn\n\n\n# \u5e0c\u5c14\u6392\u5e8f\ndef shell_sort(nn):\n # \u5b9a\u4e49 \u589e\u91cf\n d = int(len(nn)/2)\n # \u5224\u65ad \u589e\u91cf\n while d >= 1:\n # \u4ece d \u4f4d\u7f6e\u5f00\u59cb \u5faa\u73af\n for i in range(d, len(nn)):\n temp = nn[i]\n j = i\n # \u6309\u7167\u589e\u91cf\u5206\u7ec4\u4e4b\u540e \u8fdb\u884c \u76f4\u63a5\u63d2\u5165\u6392\u5e8f\n # \u56e0\u4e3a\u662f\u6309\u7167\u589e\u91cf\u5206\u7ec4 \u6240\u4ee5 j \u6bcf\u6b21 \u9700\u8981 \u5927\u4e8e \u589e\u91cf d \u7684\u503c\n while j >= d and temp < nn[j - d]:\n nn[j] = nn[j - d]\n j -= d\n nn[j] = temp\n # \u589e\u91cf\u6bcf\u6b21\u51cf\u5c11\u5230\u539f\u6765\u7684\u4e00\u534a\n d = int(d/2)\n return nn\n\n\n# \u5feb\u901f\u6392\u5e8f\ndef quick_sort(nn):\n # \u5de6\u6807\u8bb0\n left = 0\n # \u53f3\u6807\u8bb0\n right = len(nn) - 1\n return quick_part_sort(left, right, nn)\n\n\n# \u5feb\u901f\u6392\u5e8f\ndef quick_part_sort(i, j, nn):\n gg = i\n ll = j\n # \u9009\u53d6 \u5de6\u8fb9\u7b2c\u4e00\u4e2a\u6570\u4e3a\u57fa\u6570\n kk = nn[gg]\n if i < j:\n while i < j:\n\n # \u5224\u65ad\u5c0f\u4e8e\u57fa\u6570\u7684\u503c\n while i < j and kk <= nn[j]:\n j -= 1\n nn[i] = nn[j]\n\n # \u5224\u65ad\u5927\u4e8e\u57fa\u6570\u7684\u503c\n while i < j and nn[i] <= kk:\n i += 1\n nn[j] = nn[i]\n\n # \u5de6\u6807\u8bb0 \u4e0e \u53f3\u6807\u8bb0\u91cd\u5408\u65f6\n nn[j] = kk\n quick_part_sort(gg, j-1, nn)\n quick_part_sort(j + 1, ll, nn)\n return nn\n\n\n# \u5f52\u5e76\u6392\u5e8f\n# TODO \u53e6\u4e00\u79cd\u89e3\u6cd5\ndef merge_sort(nn):\n # \u5de6\u6807\u8bb0\n left = 0\n # \u53f3\u6807\u8bb0\n right = len(nn)\n merge_sort_divide(left, right - 1, nn)\n return nn\n\n\n# \u5206\u89e3\ndef merge_sort_divide(left, right, nn):\n # \u5de6\u53f3 \u6807\u8bb0\u76f8\u7b49\u65f6 \u8868\u660e\u65e0\u6cd5\u5206\u5272\n if left == right:\n return\n mid = int((left + right) / 2)\n # \u5206\u5272\u5de6\u8fb9\n merge_sort_divide(left, mid, nn)\n # \u5206\u5272\u53f3\u8fb9\n merge_sort_divide(mid + 1, right, nn)\n # \u5408\u5e76 \u5de6\u53f3 \u4e24\u90e8\u5206\n merge_sort_merge(left, mid, right, nn)\n return\n\n\n# \u5408\u5e76\ndef merge_sort_merge(left, mid, right, nn):\n # \u5b9a\u4e49\u4e00\u4e2a\u4e34\u65f6\u5217\u8868\n temp = []\n # \u5b9a\u4e49\u4e24\u4e2a \u6807\u8bb0 \u5206\u522b\u5728 \u5de6\u53f3 \u4e24\u90e8\u5206\u7684\u5934\u90e8\n p, q = left, mid + 1\n # \u6bd4\u8f83\u4e24\u4e2a\u5b50\u5e8f\u5217\u7684\u6570\u5b57\u7684\u5927\u5c0f \u628a\u8f83\u5c0f\u7684 \u52a0\u5165\u4e34\u65f6 \u5217\u8868\u4e2d\n while p <= mid and q <= right:\n if nn[p] <= nn[q]:\n temp.append(nn[p])\n p += 1\n else:\n temp.append(nn[q])\n q += 1\n\n # \u5224\u65ad \u54ea\u4e2a\u5b50\u5e8f\u5217\u4e2d \u8fd8\u6709\u6570\u5b57 \u672a\u52a0\u5165\u5230 \u4e34\u65f6\u5217\u8868\u4e2d\n if p <= mid:\n for i in range(p, left+1):\n temp.append(nn[p])\n p += 1\n\n if q <= right:\n for i in range(q, right + 1):\n temp.append(nn[p])\n p += 1\n\n # \u628a\u4e34\u65f6\u5217\u8868\u4e2d\u7684\u5143\u7d20\u590d\u5236\u5230 \u539f\u6765\u7684\u5217\u8868\u4e2d\n for i in range(len(temp)):\n nn[i + left] = temp[i]\n return\n\n\n# \u5947\u5076\u6392\u5e8f\ndef odd_even_sort(nn):\n # \u5076\u6392\u5e8f\u6807\u5fd7\n even_flag = False\n # \u5947\u6392\u5e8f\u6807\u5fd7\n odd_flag = False\n # \u5f53 \u5947\u6392\u5e8f \u548c \u5076\u6392\u5e8f \u90fd\u6392\u5e8f \u5b8c\u6210\u540e\n while (not even_flag) or (not odd_flag):\n even_flag = True\n odd_flag = True\n # \u5076\u6392\u5e8f\n for i in range(len(nn) - 1):\n if nn[i] > nn[i + 1]:\n temp = nn[i]\n nn[i] = nn[i + 1]\n nn[i + 1] = temp\n i += 2\n even_flag = False\n\n # \u5947\u6392\u5e8f\n for j in range(1, len(nn) - 1):\n if nn[j] > nn[j + 1]:\n temp = nn[j]\n nn[j] = nn[j + 1]\n nn[j + 1] = temp\n j += 2\n odd_flag = False\n\n return nn\n\n\n# \u5806\u6392\u5e8f\n# TODO\ndef heap_sort(nn):\n\n return\n\n\n# \u81ed\u76ae\u5320\u6392\u5e8f\n# TODO \u6700\u6162\u7684\u6392\u5e8f\ndef sort(nn):\n return\n\n\n# \u5192\u6ce1\u6392\u5e8f\ndef bubble_sort(nn):\n for i in range(len(nn)):\n for j in range(len(nn) - 1):\n if nn[j] > nn[j + 1]:\n temp = nn[j]\n nn[j] = nn[j + 1]\n nn[j + 1] = temp\n return nn\n\n\n# 8.\u5199\u4e2a\u51fd\u6570\uff0c\u8fd4\u56de\u6307\u5b9a\u6570\u5728\u6709\u5e8flist\u4e2d\u7684\u4f4d\u7f6e\uff0c\u4f7f\u7528\u4e8c\u5206\u67e5\u627e\uff08\u6298\u534a\u67e5\u627e\u5b9e\u73b0\uff09\ndef function8(nn, n):\n # \u8c03\u7528\u65b9\u6cd5 \u751f\u6210n\u4e2a\u6570\u7684list \u5e76\u4e14 \u6392\u5e8f\n mm = bubble_sort(random_list(nn))\n # \u5de6\u6807\u8bb0\n left = 0\n # \u53f3\u6807\u8bb0\n right = len(mm) - 1\n # \u8c03\u7528\u4e8c\u5206\u67e5\u627e\n kk = binary_search(left, right, n, mm)\n if kk == -1:\n print(\"\u6240\u6307\u5b9a\u6570\u5b57\u4e0d\u5b58\u5728list\u4e2d\")\n else:\n print(\"\u505a\u6307\u5b9a\u6570\u5b57\u5728list\u4e2d\u7684\u4f4d\u7f6e\u4e3a %d\" % kk)\n return\n\n\n# \u4e8c\u5206\u67e5\u627e\ndef binary_search(left, right, n, mm):\n if left <= right:\n mid = int((left + right)/2)\n if mm[mid] == n:\n return mid\n elif mm[mid] < n:\n left = mid + 1\n else:\n right = mid - 1\n return binary_search(left, right, n, mm)\n return -1\n\n\n# 9.\u5199\u4e2a\u51fd\u6570\u8fde\u63a5\u4e24\u4e2a\u5217\u8868\u3002\n# \u968f\u673a\u751f\u6210\u4e24\u4e2alist A,B\uff0c\u5199\u4e00\u4e2a\u51fd\u6570\uff0c\u8fde\u63a5A\u3001B\u4e24\u4e2alist\ndef function9(n, m):\n # \u8c03\u7528\u65b9\u6cd5 \u751f\u6210n\u4e2a\u6570\u7684list\n nn = random_list(n)\n mm = random_list(m)\n for i in range(len(mm)):\n nn.append(mm[i])\n return nn\n\n\n# 10.\u5199\u4e2a\u51fd\u6570\u4ea4\u66ff\u5408\u5e76\u4e24\u4e2a\u5217\u8868\uff0c\u4f8b\u5982\uff1a[a,b,c], [1,2,3] \u2192 [a,1,b,2,c,3]\u3002\n# \u5199\u4e2a\u51fd\u6570\u4ea4\u66ff\u5408\u5e76\u9898\u76ee9\u4e2d\u7684\u4e24\u4e2alist\uff0c\u4f8b\u5982\uff1aA:[a,b,c], B:[1,2,3] \u2192 [a,1,b,2,c,3]\u3002\ndef function10(n, m):\n # \u8c03\u7528\u65b9\u6cd5 \u751f\u6210n\u4e2a\u6570\u7684list\n nn = random_list(n)\n mm = random_list(m)\n # \u5b9a\u4e49\u4e00\u4e2a \u7a7a\u7684 list\n kk = []\n # \u5224\u65adnn \u548c mm \u4e24\u4e2a list \u7684 \u5927\u5c0f\n if len(nn) < len(mm):\n kk = merge_list(kk, nn, mm)\n else:\n kk = merge_list(kk, mm, nn)\n return kk\n\n\n# \u4ea4\u66ff \u5408\u5e76 \u4e24\u4e2a list\ndef merge_list(kk, nn, mm):\n # \u904d\u5386\u957f\u5ea6\u8f83\u5c0f\u7684 list\n for i in range(len(nn)):\n kk.append(nn[i])\n kk.append(mm[i])\n # \u628a \u957f\u5ea6\u5927\u7684 list \u5269\u4e0b\u7684 \u5143\u7d20 \u4f9d\u6b21\u52a0\u5165\u5230 \u65b0\u7684 list \u4e2d\n for i in range(len(nn), len(mm)):\n kk.append(mm[i])\n return kk\n\n\n# 11. \u5199\u4e2a\u51fd\u6570\u5408\u5e76\u4e24\u4e2a\u6709\u5e8f\u7684\u5217\u8868\u3002\ndef function11(n, m):\n # \u8c03\u7528\u65b9\u6cd5 \u751f\u6210n\u4e2a\u6570\u7684list \u5e76\u4e14 \u6392\u5e8f\n nn = bubble_sort(random_list(n))\n mm = bubble_sort(random_list(m))\n # \u5b9a\u4e49\u4e00\u4e2a \u7a7a\u7684 list\n kk = []\n\n # \u6bd4\u8f83\u4e24\u4e2alist\u7684\u9996\u4f4d\u5143\u7d20\u5927\u5c0f\uff0c\u628a\u5c0f\u7684\u52a0\u5230\u65b0\u7684list\u4e2d\u53bb \u5e76\u4e14\u5220\u9664\u539f\u6765list\u4e2d\u8be5\u5143\u7d20\n # \u5faa\u73af\u64cd\u4f5c \u76f4\u81f3 \u67d0\u4e00\u4e2a list \u957f\u5ea6\u4e3a0 \u7136\u540e \u628a\u4e0d\u4e3a0\u7684 \u90a3\u4e2alist \u5269\u4e0b\u7684\u5143\u7d20\u52a0\u5230 \u65b0\u7684list \u53bb\n while len(nn) > 0 and len(mm) > 0:\n if nn[0] > mm[0]:\n kk.append(mm[0])\n del mm[0]\n else:\n kk.append(nn[0])\n del nn[0]\n\n if len(nn) == 0:\n for i in range(len(mm)):\n kk.append(mm[i])\n else:\n for i in range(len(nn)):\n kk.append(nn[i])\n return\n\n\n# 12.\u5199\u4e2a\u51fd\u6570\u8ba1\u7b97\u524d100\u4e2aFibonacci\u6570\u7684\u5217\u8868\u3002\ndef function12(n):\n for i in range(1, n+1):\n print(fib(i))\n return\n\n\ndef fib(i):\n # \u7528\u4e8e\u5b58\u50a8 \u5df2\u7ecf\u8ba1\u7b97\u5b8c\u7684 \u6570\n aa = [0 for i in range(1, 200)]\n if i == 1 or i == 2:\n return 1\n else:\n # \u5df2\u7ecf\u8ba1\u7b97\u5b8c\u7684\u6570 \u5b58\u50a8\u5728\u6570\u7ec4\u4e2d\n aa[i] = fib(i-1) + fib(i-2)\n return aa[i]\n\n\n# 13.\u5199\u4e2a\u51fd\u6570\uff0c\u8fd4\u56de\u6307\u5b9a\u6570\u7684\u5404\u4f4d\u6570\u5b57\u7684\u5217\u8868\ndef function13(n):\n # \u5b9a\u4e49\u4e00\u4e2a \u7a7a\u7684 list\n kk = []\n while int(n / 10) != 0:\n kk .append(n % 10)\n n = int(n / 10)\n kk.append(n)\n return kk\n\n\n# 14.\u5199\u4e2a\u51fd\u6570\u5bf9\u4e24\u4e2a\u6570\u8fdb\u884c\u52a0\u51cf\u4e58\uff0c\u4f7f\u7528\u5404\u4e2a\u4f4d\u4e0a\u7684\u6570\u5b57\u8868\u793a\u7684\u5217\u8868\u5b9e\u73b0\u5e76\u8fd4\u56de\u4e00\u4e2a\u65b0\u7684\u6570\u5b57\u5217\u8868\uff0c\n# \u5982\u679c\u4f60\u6709\u4fe1\u5fc3\u53ef\u4ee5\u5b9e\u73b0Karatsuba\u4e58\u6cd5\u3002\u5c1d\u8bd5\u4e0d\u540c\u7684\u57fa\u6570\uff0c\u5982\u679c\u4f60\u5173\u5fc3\u901f\u5ea6\u53ef\u4ee5\u6bd4\u8f83\u4e0b\u54ea\u4e2a\u662f\u6700\u4f73\u57fa\u6570\u3002\ndef function14(n, m):\n # \u8fd4\u56de\u6307\u5b9a\u6570\u5b57\u7684\u5217\u8868\n kk = function13(n)\n ll = function13(m)\n\n # \u83b7\u53d6 \u6570\u5b57\u5217\u8868\u7684\u957f\u5ea6\n a_length = len(kk)\n b_length = len(ll)\n # \u4e58\u6cd5\n print(multiplication_num(n, a_length, m, b_length))\n\n # \u52a0\u6cd5\n print(add_num(kk, ll))\n # \u51cf\u6cd5\n print(subtract_num(kk, ll))\n\n return\n\n\n# \u6570\u5b57\u5217\u8868 \u52a0\u6cd5\ndef add_num(kk, ll):\n # \u521b\u5efa\u4e00\u4e2a\u7a7a\u5217\u8868\n gg = []\n # \u7ed9\u5217\u8868 \u586b\u51450\n kk, ll = padding_zero(kk, ll)\n # \u7528\u4e8e\u5b58\u50a8\u8fdb\u4f4d\n ff = 0\n\n for i in range(len(kk)):\n sum_num = kk[i] + ll[i] + ff\n if 9 < sum_num:\n ff = 1\n else:\n ff = 0\n gg.append(sum_num % 10)\n # \u5217\u8868\u53cd\u8f6c\n gg.reverse()\n return gg\n\n\n# \u6570\u5b57\u5217\u8868 \u51cf\u6cd5\ndef subtract_num(kk, ll):\n # \u521b\u5efa\u4e00\u4e2a\u7a7a\u5217\u8868\n gg = []\n # \u7ed9\u5217\u8868 \u586b\u51450\n kk, ll = padding_zero(kk, ll)\n # \u7528\u4e8e\u5b58\u50a8\u501f\u4f4d\n ff = 0\n\n for i in range(len(kk)):\n # \u5224\u65ad \u51cf\u6570 \u51cf\u53bb \u501f\u4f4d \u662f\u5426\u5c0f\u4e8e \u88ab\u51cf\u6570\n if kk[i] - ff < ll[i]:\n gg.append(10 + kk[i] - ll[i] - ff)\n ff = 1\n else:\n gg.append(kk[i] - ll[i] - ff)\n ff = 0\n # \u5217\u8868\u53cd\u8f6c\n gg.reverse()\n # \u53bb\u6389 \u9996\u4f4d 0\n if gg[0] == 0:\n return gg[1:]\n return gg\n\n\n# \u6570\u5b57\u5217\u8868 \u4e58\u6cd5\n# Karatsuba (ac*10^2n + ((a+b)(c+d)-ac_bd)*10^n + bd)\n# TODO \u65f6\u95f4\u590d\u6742\u5ea6\ndef multiplication_num(aa, aa_length, bb, bb_length):\n # \u5982\u679c \u5206\u89e3\u7684 a \u548c b \u7684\u5927\u5c0f\u4e3a\u4e24\u4f4d\u6570 \u5219\u53ef\u4ee5 \u76f4\u63a5 \u76f8\u4e58\n if aa < 10 or bb < 10:\n return aa * bb\n\n # \u8bbe\u5b9a \u57fa\u6570\u503c\n if aa_length < bb_length:\n n = int(bb_length/2)\n else:\n n = int(aa_length/2)\n\n # \u8bbe\u5b9a\u5206\u89e3\u7684 a b\n if aa_length < n:\n a = 0\n a_length = 0\n b = aa\n b_length = aa_length\n else:\n a = int(aa / math.pow(10, n))\n a_length = aa_length - n\n b = int(aa % math.pow(10, n))\n b_length = get_number_length(b)\n\n # \u8bbe\u5b9a\u5206\u89e3\u7684 c d\n if bb_length < n:\n c = 0\n c_length = 0\n d = bb\n d_length = bb_length\n else:\n c = int(bb / math.pow(10, n))\n c_length = bb_length - n\n d = int(bb % math.pow(10, n))\n d_length = get_number_length(d)\n\n # \u8ba1\u7b97 ac\n ac_multipl = multiplication_num(a, a_length, c, c_length)\n # \u8ba1\u7b97 bd\n bd_multipl = multiplication_num(b, b_length, d, d_length)\n # \u8ba1\u7b97 (a+b)(c+d)\n abcd_multipl = multiplication_num(a+b, get_number_length(a+b), d+c, get_number_length(d+c))\n\n # \u8ba1\u7b97\u7ed3\u679c ac*10^2n + ((a+b)(c+d)-ac-bd)*10^n + bd\n result = int(ac_multipl * math.pow(10, n*2) + (abcd_multipl - ac_multipl - bd_multipl) * math.pow(10, n) + bd_multipl)\n\n return result\n\n\n# \u7ed9\u5217\u8868 \u586b\u51450\ndef padding_zero(kk, ll):\n # \u5224\u65ad \u4e24\u4e2a list \u957f\u5ea6\u7684\u5927\u5c0f\n # \u957f\u5ea6\u5c0f\u7684 \u8865\u51450 \u81f3\u4e0e\u53e6\u4e00\u4e2alist\u957f\u5ea6\u76f8\u7b49\n if len(kk) < len(ll):\n for i in range(len(ll) - len(kk)):\n kk.append(0)\n return ll, kk\n else:\n for i in range(len(kk) - len(ll)):\n ll.append(0)\n return kk, ll\n\n\n# \u83b7\u53d6 \u6570\u5b57\u7684\u957f\u5ea6\ndef get_number_length(n):\n if n == 0:\n return 1\n else:\n m = n\n i = 0\n while m > 0:\n m = int(m / 10)\n i += 1\n return i\n\n\n# 15.\u5199\u4e2a\u51fd\u6570\u6d4b\u8bd5\u4e00\u4e2a\u5b57\u7b26\u4e32\u662f\u5426\u662f\u56de\u6587\u3002\ndef function15(mm):\n # \u5de6\u6807\u8bb0\n left = 0\n # \u53f3\u6807\u8bb0\n right = -1\n # \u662f\u5426\u56de\u6587\u7684\u6807\u5fd7\n flag = False\n # \u5faa\u73af\u5b57\u7b26\u4e32\u4e00\u534a\u7684\u957f\u5ea6\n while left < int(len(mm)/2):\n if mm[left] == mm[right]:\n left += 1\n right += -1\n flag = True\n else:\n flag = False\n break\n if flag is False:\n print(\"\u8be5\u5b57\u7b26\u4e32\u4e0d\u662f\u56de\u6587\")\n else:\n print(\"\u8be5\u5b57\u7b26\u4e32\u662f\u56de\u6587\")\n return\n\n\n# 16.\u5199\u4e00\u4e2a\u51fd\u6570\u5c06\u4e00\u6bb5\u6587\u672ctext\u5927\u5c0f\u5199\u4e92\u6362\ndef function16():\n # \u8bfb\u53d6\u4e00\u4e2a\u6587\u4ef6\n with open('./data/test', 'r+', encoding='utf8') as f:\n # \u8bfb\u53d6\u6587\u4ef6\u4e2d\u7684\u591a\u884c\u5185\u5bb9\n data = f.readlines()\n # \u79fb\u52a8\u6587\u4ef6\u8bfb\u53d6\u6307\u9488\u5230 \u6587\u4ef6\u5f00\u59cb\u4f4d\u7f6e\n f.seek(0)\n # \u6e05\u7a7a\u6587\u4ef6\n f.truncate()\n for i in range(len(data)):\n f.write(data[i].lower())\n return\n\n\n# 17.\u5199\u4e2a\u51fd\u6570\uff0c\u7ed9\u5b9a\u4e00\u4e2a\u5b57\u7b26\u4e32\u5217\u8868\u5e76\u6309\u4e0b\u9762\u8868\u793a\u6253\u5370\u51fa\u6765\uff0c\u4e00\u884c\u4e00\u4e2a\u6253\u5370\u5728\u77e9\u5f62\u6846\u4e2d\n'''\n# \u4f8b\u5982\u5217\u8868[\"Hello\", \"World\", \"in\", \"a\", \"frame\"] \u6253\u5370\u7684\u7ed3\u679c\u662f\uff1a\n# *********\n# * Hello *\n# * World *\n# * in *\n# * a *\n# * frame *\n# *********\n'''\n\n\ndef function17(kk):\n # \u5b58\u50a8 \u5217\u8868\u4e2d\u6700\u5927\u7684\u5b57\u7b26\u4e32\u7684\u957f\u5ea6\n mm = 0\n for i in range(len(kk)):\n # \u83b7\u53d6\u5b57\u7b26\u4e32\u7684\u957f\u5ea6\n nn = len(kk[i])\n if mm < nn:\n mm = nn\n # \u6253\u5370 \u4e0a\u8fb9\u6846\n print(\"*\"*(mm+4))\n j = 0\n # \u5faa\u73af \u5217\u8868\n while j < len(kk):\n print(\"* %s\" % kk[j], end=\"\")\n print(\" \"*(mm-len(kk[j])+1) + \"*\")\n j += 1\n # \u6253\u5370 \u4e0b\u8fb9\u6846\n print(\"*\"*(mm + 4))\n return\n\n\n# 18.\u5199\u51fd\u6570\u5c06\u4e00\u6bb5\u6587\u672ctext\u7ffb\u8bd1\u4e3aPig Latin\u8fd4\u56de\u3002\n'''\n\u82f1\u8bed\u7ffb\u8bd1\u4e3aPig Latin\u7684\u89c4\u5219\u662f\uff1a\u53d6\u51fa\u6bcf\u4e2a\u5355\u8bcd\u7684\u9996\u4e2a\u5b57\u6bcd\uff0c\u8ffd\u52a0\u2019ay\u2019\u540e\u518d\u653e\u5230\u8be5\u5355\u8bcd\u7684\u672b\u5c3e\n\u4f8b\u5982\u201cThe quick brown fox\u201d \u7ffb\u8bd1\u540e\u5c31\u53d8\u6210\u4e86 \u201cHetay uickqay rownbay oxfay\u201d\u3002\n'''\ndef function18():\n # \u8bfb\u53d6\u4e00\u4e2a\u6587\u4ef6\n with open('./data/test', 'r+', encoding='utf8') as f:\n # \u8bfb\u53d6\u6587\u4ef6\u4e2d\u7684\u591a\u884c\u5185\u5bb9\n data = f.readlines()\n # \u79fb\u52a8\u6587\u4ef6\u8bfb\u53d6\u6307\u9488\u5230 \u6587\u4ef6\u5f00\u59cb\u4f4d\u7f6e\n f.seek(0)\n # \u6e05\u7a7a\u6587\u4ef6\n f.truncate()\n # \u7528\u4e8e\u5b58\u50a8 \u7ffb\u8bd1\u540e\u7684 \u7684\u5185\u5bb9\n content = \"\"\n\n for i in range(len(data)):\n kk = data[i]\n # \u4ee5\u7a7a\u683c\u5206\u5272\n gg = kk.split(\" \")\n for j in range(len(gg)):\n ll = gg[j]\n content += (ll[1:len(ll)] + ll[0] + \"ay\") + \" \"\n f.write(content.capitalize())\n return\n\n\nif __name__ == '__main__':\n function7(10)\n\n"} {"blob_id": "c644c148c271250fd557d967f8f0ca53e486618a", "repo_name": "mehmetyaylacci/CS461-Hws", "path": "/hw-1/main.py", "length_bytes": 10614, "score": 4.0625, "int_score": 4, "content": "# @authors: \n# Burak Turksever\n# Mehmet Yaylaci\n# Eralp Kumbasar\nimport graph\n\nchoice = str(input(\"Would you like to run the program with the default data? (yes/no)\"))\nif choice.upper() == 'YES':#the program solves the 3 questions as default\n solver = graph.Graph()\n print(\"3 Cannibals 3 Missionaries and a Boat of Capacity 2\")\n solver.DFS_start(3, 2)\n # Question 1 answer\n print(\"5 Cannibals 5 Missionaries and a Boat of Capacity 3\")\n solver.DFS_start(5, 3)\n # Question 2a answer\n print(\"6 Cannibals 6 Missionaries and a Boat of Capacity 4\")\n # Question 2b answer \n solver.DFS_start(6, 4)\n print(\"6 Cannibals 6 Missionaries and a Boat of Capacity 5\")#optionally solves both of the choices in the 2nd question\n solver.DFS_start(6, 5)\nelif choice.upper() == 'NO':\n while True:\n input_one = str(input('\\nPlease enter the number of Missionaries and Cannibals (EXIT to exit): '))\n if input_one.upper() == 'EXIT':\n break\n else:\n if input_one.isnumeric() and int(input_one) <= 494:#check if number is above the most number of iterations possible in python\n number = int(input_one)\n input_two = str(input('Please enter the capacity of the boat: '))\n if input_two.isnumeric():\n capacity = int(input_two)\n if (capacity >= 2 and number <= 3) or ((number == 4 or number == 5) and capacity == 3) or (capacity >= 4 and number >= 6):#other combinations aren't possible as referenced in the pdf\n solver = graph.Graph() \n solver.DFS_start(number, capacity)\n else:\n print('\\nThis combination will not work! See why on https://arxiv.org/pdf/1802.09369.pdf\\n')\n else:\n print('Please enter a valid number.') \n elif input_one.isnumeric() and int(input_one)>494:\n print(\"The entered number is too large (recursion limit of Python is reached when executed.)\")\n else:\n print('Please enter a valid number.')\nelse:\n print('Unrecognized input')\n\n\n\n'''\n-------------------------------------------------------\n OUTPUT THAT ANSWERS THE QUESTIONS\n-------------------------------------------------------\n\n5 Cannibals 5 Missionaries and a Boat of Capacity 3 (Question 1)\n\nDepth:1\nSend 1 Cannibal(s) 1 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 4 Missionaries: 4)\nRight:(Cannibals: 1 Missionaries: 1)\nCurrent Boat Position: right\n\n\nDepth:2\nReturn 0 Cannibal(s) 1 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 4 Missionaries: 5)\nRight:(Cannibals: 1 Missionaries: 0)\nCurrent Boat Position: left\n\n\nDepth:3\nSend 1 Cannibal(s) 2 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 3 Missionaries: 3)\nRight:(Cannibals: 2 Missionaries: 2)\nCurrent Boat Position: right\n\n\nDepth:4\nReturn 0 Cannibal(s) 2 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 3 Missionaries: 5)\nRight:(Cannibals: 2 Missionaries: 0)\nCurrent Boat Position: left\n\n\nDepth:5\nSend 2 Cannibal(s) 0 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 1 Missionaries: 5)\nRight:(Cannibals: 4 Missionaries: 0)\nCurrent Boat Position: right\n\n\nDepth:6\nReturn 1 Cannibal(s) 0 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 2 Missionaries: 5)\nRight:(Cannibals: 3 Missionaries: 0)\nCurrent Boat Position: left\n\n\nDepth:7\nSend 0 Cannibal(s) 3 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 2 Missionaries: 2)\nRight:(Cannibals: 3 Missionaries: 3)\nCurrent Boat Position: right\n\n\nDepth:8\nReturn 1 Cannibal(s) 1 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 3 Missionaries: 3)\nRight:(Cannibals: 2 Missionaries: 2)\nCurrent Boat Position: left\n\n\nDepth:9\nSend 0 Cannibal(s) 3 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 3 Missionaries: 0)\nRight:(Cannibals: 2 Missionaries: 5)\nCurrent Boat Position: right\n\n\nDepth:10\nReturn 1 Cannibal(s) 0 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 4 Missionaries: 0)\nRight:(Cannibals: 1 Missionaries: 5)\nCurrent Boat Position: left\n\n\nDepth:11\nSend 2 Cannibal(s) 0 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 2 Missionaries: 0)\nRight:(Cannibals: 3 Missionaries: 5)\nCurrent Boat Position: right\n\n\nDepth:12\nReturn 0 Cannibal(s) 2 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 2 Missionaries: 2)\nRight:(Cannibals: 3 Missionaries: 3)\nCurrent Boat Position: left\n\n\nDepth:13\nSend 1 Cannibal(s) 2 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 1 Missionaries: 0)\nRight:(Cannibals: 4 Missionaries: 5)\nCurrent Boat Position: right\n\n\nDepth:14\nReturn 0 Cannibal(s) 1 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 1 Missionaries: 1)\nRight:(Cannibals: 4 Missionaries: 4)\nCurrent Boat Position: left\n\n\nDepth:15\nSend 1 Cannibal(s) 1 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 0 Missionaries: 0)\nRight:(Cannibals: 5 Missionaries: 5)\nCurrent Boat Position: right\n\n-------------------------------------------------------\n\n6 Cannibals 6 Missionaries and a Boat of Capacity 4 (Question 2a)\n\nDepth:1\nSend 1 Cannibal(s) 1 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 5 Missionaries: 5)\nRight:(Cannibals: 1 Missionaries: 1)\nCurrent Boat Position: right\n\n\nDepth:2\nReturn 0 Cannibal(s) 1 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 5 Missionaries: 6)\nRight:(Cannibals: 1 Missionaries: 0)\nCurrent Boat Position: left\n\n\nDepth:3\nSend 1 Cannibal(s) 2 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 4 Missionaries: 4)\nRight:(Cannibals: 2 Missionaries: 2)\nCurrent Boat Position: right\n\n\nDepth:4\nReturn 0 Cannibal(s) 2 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 4 Missionaries: 6)\nRight:(Cannibals: 2 Missionaries: 0)\nCurrent Boat Position: left\n\n\nDepth:5\nSend 1 Cannibal(s) 3 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 3 Missionaries: 3)\nRight:(Cannibals: 3 Missionaries: 3)\nCurrent Boat Position: right\n\n\nDepth:6\nReturn 0 Cannibal(s) 3 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 3 Missionaries: 6)\nRight:(Cannibals: 3 Missionaries: 0)\nCurrent Boat Position: left\n\n\nDepth:7\nSend 2 Cannibal(s) 0 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 1 Missionaries: 6)\nRight:(Cannibals: 5 Missionaries: 0)\nCurrent Boat Position: right\n\n\nDepth:8\nReturn 1 Cannibal(s) 0 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 2 Missionaries: 6)\nRight:(Cannibals: 4 Missionaries: 0)\nCurrent Boat Position: left\n\n\nDepth:9\nSend 0 Cannibal(s) 4 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 2 Missionaries: 2)\nRight:(Cannibals: 4 Missionaries: 4)\nCurrent Boat Position: right\n\n\nDepth:10\nReturn 1 Cannibal(s) 1 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 3 Missionaries: 3)\nRight:(Cannibals: 3 Missionaries: 3)\nCurrent Boat Position: left\n\n\nDepth:11\nSend 0 Cannibal(s) 3 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 3 Missionaries: 0)\nRight:(Cannibals: 3 Missionaries: 6)\nCurrent Boat Position: right\n\n\nDepth:12\nReturn 1 Cannibal(s) 0 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 4 Missionaries: 0)\nRight:(Cannibals: 2 Missionaries: 6)\nCurrent Boat Position: left\n\n\nDepth:13\nSend 2 Cannibal(s) 0 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 2 Missionaries: 0)\nRight:(Cannibals: 4 Missionaries: 6)\nCurrent Boat Position: right\n\n\nDepth:14\nReturn 0 Cannibal(s) 2 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 2 Missionaries: 2)\nRight:(Cannibals: 4 Missionaries: 4)\nCurrent Boat Position: left\n\n\nDepth:15\nSend 1 Cannibal(s) 2 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 1 Missionaries: 0)\nRight:(Cannibals: 5 Missionaries: 6)\nCurrent Boat Position: right\n\n\nDepth:16\nReturn 0 Cannibal(s) 1 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 1 Missionaries: 1)\nRight:(Cannibals: 5 Missionaries: 5)\nCurrent Boat Position: left\n\n\nDepth:17\nSend 1 Cannibal(s) 1 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 0 Missionaries: 0)\nRight:(Cannibals: 6 Missionaries: 6)\nCurrent Boat Position: right\n\n-------------------------------------------------------\n\n6 Cannibals 6 Missionaries and a Boat of Capacity 5 (Question 2b)\n\nDepth:1\nSend 1 Cannibal(s) 1 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 5 Missionaries: 5)\nRight:(Cannibals: 1 Missionaries: 1)\nCurrent Boat Position: right\n\n\nDepth:2\nReturn 0 Cannibal(s) 1 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 5 Missionaries: 6)\nRight:(Cannibals: 1 Missionaries: 0)\nCurrent Boat Position: left\n\n\nDepth:3\nSend 1 Cannibal(s) 2 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 4 Missionaries: 4)\nRight:(Cannibals: 2 Missionaries: 2)\nCurrent Boat Position: right\n\n\nDepth:4\nReturn 0 Cannibal(s) 2 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 4 Missionaries: 6)\nRight:(Cannibals: 2 Missionaries: 0)\nCurrent Boat Position: left\n\n\nDepth:5\nSend 1 Cannibal(s) 3 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 3 Missionaries: 3)\nRight:(Cannibals: 3 Missionaries: 3)\nCurrent Boat Position: right\n\n\nDepth:6\nReturn 0 Cannibal(s) 3 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 3 Missionaries: 6)\nRight:(Cannibals: 3 Missionaries: 0)\nCurrent Boat Position: left\n\n\nDepth:7\nSend 1 Cannibal(s) 4 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 2 Missionaries: 2)\nRight:(Cannibals: 4 Missionaries: 4)\nCurrent Boat Position: right\n\n\nDepth:8\nReturn 0 Cannibal(s) 4 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 2 Missionaries: 6)\nRight:(Cannibals: 4 Missionaries: 0)\nCurrent Boat Position: left\n\n\nDepth:9\nSend 2 Cannibal(s) 0 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 0 Missionaries: 6)\nRight:(Cannibals: 6 Missionaries: 0)\nCurrent Boat Position: right\n\n\nDepth:10\nReturn 1 Cannibal(s) 0 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 1 Missionaries: 6)\nRight:(Cannibals: 5 Missionaries: 0)\nCurrent Boat Position: left\n\n\nDepth:11\nSend 0 Cannibal(s) 5 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 1 Missionaries: 1)\nRight:(Cannibals: 5 Missionaries: 5)\nCurrent Boat Position: right\n\n\nDepth:12\nReturn 1 Cannibal(s) 1 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 2 Missionaries: 2)\nRight:(Cannibals: 4 Missionaries: 4)\nCurrent Boat Position: left\n\n\nDepth:13\nSend 0 Cannibal(s) 2 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 2 Missionaries: 0)\nRight:(Cannibals: 4 Missionaries: 6)\nCurrent Boat Position: right\n\n\nDepth:14\nReturn 1 Cannibal(s) 0 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 3 Missionaries: 0)\nRight:(Cannibals: 3 Missionaries: 6)\nCurrent Boat Position: left\n\n\nDepth:15\nSend 2 Cannibal(s) 0 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 1 Missionaries: 0)\nRight:(Cannibals: 5 Missionaries: 6)\nCurrent Boat Position: right\n\n\nDepth:16\nReturn 0 Cannibal(s) 1 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 1 Missionaries: 1)\nRight:(Cannibals: 5 Missionaries: 5)\nCurrent Boat Position: left\n\n\nDepth:17\nSend 1 Cannibal(s) 1 Missionary(ies)\nCurrent State: \nLeft:(Cannibals: 0 Missionaries: 0)\nRight:(Cannibals: 6 Missionaries: 6)\nCurrent Boat Position: right\n\n-------------------------------------------------------\n\n'''"} {"blob_id": "c2809bed33b4b240c301addd72ab785e92922759", "repo_name": "joeblackwaslike/codingbat", "path": "/recursion-1/count8.py", "length_bytes": 868, "score": 3.90625, "int_score": 4, "content": "\"\"\"\ncount8\n\nGiven a non-negative int n, compute recursively (no loops) the count of the\noccurrences of 8 as a digit, except that an 8 with another 8 immediately to\nits left counts double, so 8818 yields 4. Note that mod (%) by 10 yields the\nrightmost digit (126 % 10 is 6), while divide (/) by 10 removes the rightmost\ndigit (126 / 10 is 12).\n\n\ncount8(8) \u2192 1\ncount8(818) \u2192 2\ncount8(8818) \u2192 4\n\"\"\"\n\n\ndef count8(n):\n def rec(num, lastVal=None):\n if num < 10:\n curVal = 1 if num == 8 else 0\n if lastVal == 8:\n curVal *= 2\n return curVal\n else:\n rightMostDigit = num % 10\n curSum = rec(rightMostDigit)\n return curSum + rec(num // 10, lastVal=rightMostDigit)\n\n return rec(n)\n\n\nif __name__ == \"__main__\":\n for val in [8, 818, 8818]:\n print(val, count8(val))\n"} {"blob_id": "bfddd2af9f51e15b2245208cfda079c5619f7682", "repo_name": "izabelaguiar/class", "path": "/hw0/npdes_AS00.py", "length_bytes": 6455, "score": 4.15625, "int_score": 4, "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Sep 10 10:46:07 2017\n\n@author: izabelaguiar\n\nnPDES AS00\nHomework 0, due 2017-09-13\n\nFork the class repository, clone, and create a directory hw0 inside the repository.\nAdd your source file(s) to that directory.\n\nWrite a function diffmat(x) that returns a matrix $D$ that computes first derivatives.\n\nWrite a function diff2mat(x) that returns a matrix $D_2$ that computes second derivatives.\n\nUse test solutions to determine the order of accuracy of your methods for evenly and\n non-evenly spaced points. Which norm did you use?\n\nAdd README.md in the hw0 directory and summarize your results\n (one paragraph or a few bullet items is fine).\n\nYou may assume that the points x are monotonically increasing.\n\nYou'll need to think about what to do at the endpoints.\n\n\"\"\"\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\ndef diffmat(x):\n \"\"\"Compute first derivative matrix operator.\n \n Parameters\n ----------\n x : ndarray\n 1-by-m array of x values for which the solution, u, is evaluated\n Returns\n -------\n D : ndarray\n m-by-m matrix that computes first derivatives for the system, u'=Du\n \n Notes\n -----\n Note that matrix used here to compute first derivatives is a second order accurate\n centered approximation. At the first and last points we implement a second order \n accurate forward and backward approximation, respectively. \n All approximations are derived in \n \n [1] LeVeque, R. \"Finite Difference Methods for Ordinary and Partial Differential\n Equations\". SIAM (2007), Philadelphia, PA.\n \n The centered approximation is given by eq. (1.3) and the for/back(wards) by eq. (1.11)\n \"\"\"\n m = len(x)\n \n h = np.ones(m-1)\n \n for i in range(m-1): \n h[i] = x[i+1]-x[i]\n \n D = np.eye(m, k=1) - np.eye(m, k=-1)\n \n D[0, 0:3] = (1. / (h[0] + h[1])) * np.array([1., -4., 3. ]) #by 1.11\n \n #mth row\n D[-1, -3:] = (1. / (h[-1] + h[-2])) * np.array([1., -4. , 3. ]) #by 1.11\n \n #ith row\n for i in range(1, m-1):\n D[i, :] *= (1. / (h[i] + h[i-1]))\n #D *= (1. / (2*h) )\n return D\n\n\n\n\ndef diff2mat(x):\n \"\"\"Compute first derivative matrix operator.\n \n Parameters\n ----------\n x : ndarray\n 1-by-m array of x values for which the solution, u, is evaluated\n Returns\n -------\n D_2 : ndarray\n m-by-m matrix that computes first derivatives for the system, u'=Du\n \n Notes\n -----\n Note that matrix used here to compute second derivatives is a second order accurate\n centered approximation. At the first and last points we implement a second order \n accurate forward and backward approximation, respectively. \n All approximations are derived in \n \n [1] LeVeque, R. \"Finite Difference Methods for Ordinary and Partial Differential\n Equations\". SIAM (2007), Philadelphia, PA.\n \n The centered approximation is given by eq. (1.14) and the for/back(wards) by eq. (1.11)\n \"\"\" \n m = len(x)\n h = np.ones(m-1)\n\n for i in range(m-1): \n h[i] = x[i+1]-x[i]\n \n D_2 = np.zeros((m,m))\n \n for i in range(1, m-1):\n c_1 = 2. / (h[i-1]*(h[i-1] + h[i]))\n c_2 = -2. / (h[i-1] * h[i])\n c_3 = 2. / (h[i]*(h[i-1] + h[i]))\n D_2[i, i-1] = c_1\n D_2[i, i] = c_2\n D_2[i, i+1] = c_3\n \n r = 1./(h[0]+h[1])\n a = 9./(h[0]+h[1])\n b = 12./(h[0]+h[1]) + 12./(h[1]+h[2])\n c = 3./(h[0]+h[1]) + 16./(h[1]+h[2]) + 3./(h[2]+h[3])\n d = 4./(h[1]+h[2]) + 4./(h[2]+h[3])\n e = 1./(h[2]+h[3])\n \n D_2[0, 0:5] = np.array([r*a, -r*b, r*c, -r*d, r*e])\n \n r = 1./(h[-1]+h[-2])\n a = 9./(h[-1]+h[-2])\n b = 12./(h[-1]+h[-2]) + 12./(h[-2]+h[-3])\n c = 3./(h[-1]+h[-2]) + 16./(h[-2]+h[-3]) + 3./(h[-3]+h[-4])\n d = 4./(h[-2]+h[-3]) + 4./(h[-3]+h[-4])\n e = 1./(h[-3]+h[-4])\n \n D_2[-1, -5:] = np.array([r*e, -r*d, r*c, -r*b, r*a])\n\n \n return D_2\n \n\"\"\" Test function: u(x) = sin(x), u'(x) = cos(x), u''(x) = -sin(x) \"\"\"\n\n\n#Compute the errors \nns = 2 ** np.arange(3, 9)\nerrors_1 = np.zeros(len(ns))\nerrors_2 = np.zeros(len(ns)) \nh = np.zeros(len(ns)) \ni = 0\nfor n in ns:\n x = np.linspace(0, 2.*np.pi, n)\n h[i] = 1. / n\n du_analytic = np.cos(x)\n d2u_analytic = -np.sin(x)\n u = np.sin(x)\n D = diffmat(x)\n du_numerical = D.dot(u)\n D_2 = diff2mat(x)\n d2u_numerical = D_2.dot(u)\n errors_1[i] = np.linalg.norm(du_analytic - du_numerical, np.inf)\n errors_2[i] = np.linalg.norm(d2u_analytic - d2u_numerical, np.inf)\n i += 1\n \n\"\"\"Test order of convergence for both methods\"\"\"\n \nplt.loglog(h, errors_1, 'o', label='numerical') \nplt.loglog(h, h**2, label =r'$\\mathcal{O}(h^2)$') \nplt.legend(loc='best') \nplt.xlabel('h')\nplt.ylabel('Error')\nplt.title('Cost vs. Accuracy, First Derivative')\n\n\nplt.loglog(h, errors_2, 'o', label='numerical') \nplt.loglog(h, h**2, label =r'$\\mathcal{O}(h^2)$') \nplt.legend(loc='best') \nplt.xlabel('h')\nplt.ylabel('Error')\nplt.title('Cost vs. Accuracy, Second Derivative') \n\n\n\"\"\" Plot the numerical vs. analytic solutions for even h \"\"\" \n\nn=2**4\nx = np.linspace(0, 2.*np.pi, n)\ndu_analytic = np.cos(x)\nd2u_analytic = -np.sin(x)\nu = np.sin(x)\nD = diffmat(x)\ndu_numerical = D.dot(u)\nD_2 = diff2mat(x)\nd2u_numerical = D_2.dot(u)\n \nplt.plot(x, du_analytic, label= '$\\cos(x)$')\nplt.plot(x, du_numerical, 'o', label= '$Du$')\nplt.plot(x, d2u_analytic, label='$-\\sin(x)$')\nplt.plot(x, d2u_numerical, 'o', label = r'$D_2u$')\nplt.legend(loc='best')\nplt.title('Numerical vs. Analytic Solution, even h') \n \n\"\"\" Plot the numerical vs. analytic solutions for uneven h\"\"\"\n \nuneven_h = (1./5.)*np.ones(12)\nuneven_h[0] *= 1/4\nuneven_h[1] *= 1/4\nuneven_h[2] *= 1/4\nuneven_h[3] *= 1/4\n\nuneven_h[5] *=1/2\nuneven_h[4] *=3/4\nuneven_h[6] *= 2/3\n\nuneven_h[8] *= 1/5\nuneven_h[9] *= 1/5\nuneven_h[10] *= 1/5\nuneven_h[11] *= 1/5\n\nx = np.zeros(13)\nfor i in range(0, 12):\n x[i+1] = x[i] + uneven_h[i]\n\ndu_analytic = np.cos(x)\nd2u_analytic = -np.sin(x)\nu = np.sin(x)\nD = diffmat(x)\ndu_numerical = D.dot(u)\nD_2 = diff2mat(x)\nd2u_numerical = D_2.dot(u)\n \nplt.plot(x, du_analytic, label= '$\\cos(x)$')\nplt.plot(x, du_numerical, 'o', label= '$Du$')\nplt.plot(x, d2u_analytic, label='$-\\sin(x)$')\nplt.plot(x, d2u_numerical, 'o', label = r'$D_2u$')\nplt.legend(loc='best')\nplt.title('Numerical vs. Analytic Solution, uneven h') \n \n "} {"blob_id": "8de6fa814facca8c47c5af4889fca2a44d8d73f0", "repo_name": "jordiori/aoc-2020", "path": "/day16/exercise_part2.py", "length_bytes": 3067, "score": 3.8125, "int_score": 4, "content": "import argparse\nfrom typing import List, Dict\nfrom itertools import permutations\n\n\ndef parse_ticket(line_ticket: str) -> List[int]:\n \"\"\"Parse a string ticket.\"\"\"\n return [int(x) for x in line_ticket.split(',')]\n\n\ndef parse_restrictions(lines_restrictions: List[str]) -> Dict[str, List[int]]:\n \"\"\"Parse restrictions.\"\"\"\n restrictions = {}\n for r in lines_restrictions:\n r_name = r.split(':')[0]\n restrictions[r_name] = []\n values = r.split(':')[1].strip()\n ranges = [[int(v.split('-')[0]), int(v.split('-')[1])] for v in values.split('or')]\n for x in ranges:\n restrictions[r_name].extend(list(range(x[0], x[1] + 1)))\n return restrictions\n\n\ndef filter_invalid_tickets(\n nearby_tickets: List[List[int]], restrictions: Dict[str, List[int]]\n) -> List[List[int]]:\n \"\"\"Filter invalid tickets.\"\"\"\n valid_tickets = nearby_tickets.copy()\n for ticket in nearby_tickets:\n for ticket_value in ticket:\n valid = False\n for r in restrictions.values():\n if ticket_value in r:\n valid = True\n break\n else:\n if not valid:\n valid_tickets.remove(ticket)\n break\n return valid_tickets\n\n\ndef find_field_order(\n valid_tickets: List[List[int]], restrictions: Dict[str, List[int]]\n) -> List[str]:\n \"\"\"Find valid field order.\"\"\"\n invalid_pos = {}\n for order_id, r_order in enumerate(permutations(restrictions.keys())):\n # check that permutation is valid\n for idx, invalid_value in invalid_pos.items():\n if r_order[idx] in invalid_value:\n break\n else:\n order_valid = True\n for ticket in valid_tickets:\n for idx, r in enumerate(r_order):\n if ticket[idx] not in restrictions[r]:\n order_valid = False\n break\n if not order_valid:\n if idx in invalid_pos:\n invalid_pos[idx].append(r)\n else:\n invalid_pos[idx] = [r]\n break\n if order_valid:\n return list(r_order)\n return list(r_order)\n\n\ndef solve(input_txt: str) -> int:\n \"\"\"Solve exercise.\"\"\"\n sections = input_txt.split('\\n\\n')\n restrictions = parse_restrictions(sections[0].splitlines())\n my_ticket = parse_ticket(sections[1].splitlines()[1])\n nearby_tickets = [parse_ticket(t) for t in sections[2].splitlines()[1:]]\n valid_tickets = filter_invalid_tickets(nearby_tickets, restrictions)\n field_order = find_field_order(valid_tickets, restrictions)\n print(field_order)\n return 0\n\n\ndef main() -> int:\n parser = argparse.ArgumentParser()\n parser.add_argument('input_file')\n args = parser.parse_args()\n\n if not args.input_file:\n raise ValueError('Missing input_file!')\n\n with open(args.input_file) as f:\n print(solve(f.read()))\n\n\nif __name__ == '__main__':\n main()"} {"blob_id": "6ac3812a821c44633538de9f98d50fe153864946", "repo_name": "matthewwardrop/python-qubricks", "path": "/qubricks/wall/systems.py", "length_bytes": 2595, "score": 3.5625, "int_score": 4, "content": "from ..system import QuantumSystem\n\n\nclass SimpleQuantumSystem(QuantumSystem):\n '''\n `SimpleQuantumSystem` is a subclass of `QuantumSystem` that enables you to \n initialise a `QuantumSystem` instance in one line, by passing keyword arguments\n to the constructor. Otherwise, it is indistinguishable.\n \n :param hamiltonian: The Hamiltonian to use for this QuantumSystem. Can be an Operator or an array.\n :type hamiltonian: Operator or numpy.array or list\n :param bases: A dictionary of bases to add to the QuantumSystem.\n :type bases: dict of Basis\n :param states: A dictionary of states to add to the QuantumSystem.\n :type states: dict of arrays\n :param measurements: A dictionary of `Measurement`s to add to the QuantumSystem.\n :type measurements: dict of Measurement\n :param derivative_ops: A dictionary of `StateOperator`s to add to the QuantumSystem.\n :type derivative_ops: dict of StateOperator\n \n For more documentation, see `QuantumSystem`.\n '''\n\n def init(self, hamiltonian=None, bases=None, states=None, measurements=None, derivative_ops=None):\n '''\n Configure any custom properties/attributes using kwargs passed\n to __init__.\n '''\n self.kwargs = {\n 'hamiltonian': hamiltonian,\n 'bases': bases if bases != None else {},\n 'states': states if states != None else {},\n 'measurements': measurements if measurements != None else {},\n 'derivative_ops': derivative_ops if derivative_ops != None else {},\n }\n\n def init_hamiltonian(self):\n if self.kwargs.get('hamiltonian') is None:\n raise ValueError(\"A Hamiltonian was not specified (and is required) for this system.\")\n return self.Operator(self.kwargs['hamiltonian'])\n\n def init_bases(self):\n for name, basis in self.kwargs.get('bases', {}).items():\n self.add_basis(name, basis)\n\n def init_states(self):\n for name, state in self.kwargs.get('states', {}).items():\n self.add_state(name, state)\n\n def init_measurements(self):\n for name, meas in self.kwargs.get('measurements', {}).items():\n self.add_measurement(name, meas)\n\n def init_derivative_ops(self, components=None):\n '''\n Setup the derivative operators to be implemented on top of the\n basic quantum evolution operator.\n '''\n for name, op in self.kwargs.get('derivative_ops', {}).items():\n self.add_derivative_op(name, op)\n"} {"blob_id": "6f040cb256208d842d3bf4bee6814acae4bdcacc", "repo_name": "antunesleo/tic-tac-toe-ai", "path": "/ai_services.py", "length_bytes": 1064, "score": 3.5625, "int_score": 4, "content": "from math import inf as infinity\n\n\nclass MinimaxService(object):\n\n @classmethod\n def minimax_tic_tac_toe(cls, simulation_match, depth, marker_value):\n if marker_value == 1:\n best = [-1, -1, -infinity]\n else:\n best = [-1, -1, +infinity]\n\n if depth == 0 or simulation_match.check_if_games_ended():\n score = simulation_match.who_wins_x_or_o()\n return [-1, -1, score]\n\n for cell in simulation_match.board.empty_cells:\n x, y = cell[0], cell[1]\n simulation_match.board.cells[x][y] = marker_value\n score = cls.minimax_tic_tac_toe(simulation_match, depth - 1, -marker_value)\n simulation_match.board.cells[x][y] = 0\n score[0], score[1] = x, y\n\n if marker_value == 1:\n if score[2] > best[2]:\n best = score\n else:\n if score[2] < best[2]:\n best = score\n\n return best"} {"blob_id": "133b1bae43ca4008d25cbfc2069aaf2855afc611", "repo_name": "ramsestein/Aprendizaje_automatico", "path": "/red_neuronal.py", "length_bytes": 4517, "score": 3.546875, "int_score": 4, "content": "#------------------------------------------------------------\n# --------------------------\n# | Red Neuronal en Python |\n# --------------------------\n#------------------------------------------------------------\n#Importamos las librerias necesarias\n#------------------------------------------------------------\n\nimport math\nimport random\n#import pyoo\n\n#------------------------------------------------------------\n#Funciones de la neurona\n#------------------------------------------------------------\n\ndef valores_ramdom_w(n):\n\t#Random de valores w de las neuronas\n\tfor i in range(len(n)):\n\t\tif i = 0:\n\t\t\tpass\n\t\telse:\n\t\t\tfor m in range (1,n[i]):\n\t\t\t\tfor j in range (1,n[i+1]):\n\t\t\t\t\tw[i][m][j] = random.random()\n\treturn w\n\ndef valores_ramdom_u(n):\n\t#Random de valores de las neuronas\n\tfor i in range(len(n)):\n\t\tif i = 0:\n\t\t\tpass\n\t\telse:\n\t\t\tfor m in range (1,n[i]):\n \t\t\tu[i][m] = random.random ()\n\treturn u\n\ndef calculo_neuronas(w,u,z,n):\n\t#Calculo de los valores de neuronas\n\t#y es a[4][1]\n\tfor r in range(len(n)):\n\t\tif r = 0:\n\t\t\tpass\n\t\telse:\n\t\t\tfor e in range (1,n[r+1]):\n\t\t\t\tfor q in range(len(z)):\n\t\t\t\t\tx[r][e] = x[e] + z[q]*w[r][q][e]\n\t\t\t\tx[r][e] = x[r][e] + u[r][e]\n\t\t\t\ta[r][e] = (1 - math.e**x[r][e])**-1\n\treturn a\n\ndef calculo_funcion_error(s,y):\n\terr = -(s-y)\n\treturn err\n\ndef nueva_w_nivel1(w,a,y,n,alfa,err,z):\n\tfor r in range(1,n[2]):\n\t\tfor t in range(1,n[3]):\n\t\t\tgamma = gamma + (w[2][r][t]*a[3][t]*(1-a[3][t])*w[3][t][1])\n\tfor i in range(1,n[1]):\n\t\tfor j in range(1,n[2]):\n\t\t\tw[1][i][j] = w[1][i][j] - alfa*(err*(z[i]*a[2][j]*(1-a[2][j])*gamma*y*(1-y)))\n\treturn w\n\ndef nueva_u_nivel1(u,a,y,n,alfa,err,z):\n\tfor r in range(1,n[2]):\n\t\tfor t in range(1,n[3]):\n\t\t\tgamma = gamma + (w[2][r][t]*a[3][t]*(1-a[3][t])*w[3][t][1])\n\tfor j in range(1,n[2]):\n\t\tu[1][j] = u[1][j] - alfa*(err*(a[2][j]*(1-a[2][j])*gamma*y*(1-y)))\n\treturn u\n\ndef nueva_w_nivel2(w,a,y,n,alfa,err):\n\tfor i in range(1,n[1]):\n\t\tfor j in range(1,n[2]):\n\t\t\tw[2][i][j] = w[2][i][j] - alfa*(err*(a[2][i]*a[3][j]*(1-a[3][j])*w[3][j][1]*y*(1-y)))\n\treturn w\n\ndef nueva_u_nivel2(u,a,y,n,alfa,err):\n\tfor r in range(1,n[2]):\n\t\tfor j in range(1,n[2]):\n\t\t\tu[2][j] = u[2][j] - alfa*(err*(a[3][j]*(1-a[3][j])*w[3][j][1]*y*(1-y)))\n\treturn u\n\ndef nueva_w_nivel3(w,a,y,n,alfa,err):\n\tfor i in range(1,n[1]):\n\t\tfor j in range(1,n[2]):\n\t\t\tw[3][i][j] = w[3][i][j] - alfa*(err*(a[3][j]*y*(1-y)))\n\treturn w\n\ndef nueva_u_nivel3(u,a,y,n,alfa,err):\n\tfor r in range(1,n[2]):\n\t\tfor j in range(1,n[2]):\n\t\t\tu[3][j] = u[3][j] - alfa*(err*(y*(1-y)))\n\treturn u\n\n#------------------------------------------------------------\n#Inicio de la neurona\n#------------------------------------------------------------\n#------------------------------------------------------------\n#Datos a modificar para cambiar la red\n#------------------------------------------------------------\n\n#Valor deseable como resultado\ns = 1\n#Numero de neuronas por linea\n#El valor 0 inicial no se ha de tomar en cuenta\nn = [0,5,6,3,1]\n#Valor de alfa\nalfa = 0.05\n\n#------------------------------------------------------------\n#Inicio de constantes globales\n#------------------------------------------------------------\n\nz = []\nj = 0\nw = [[[[[for e in range(0,n[4])]for d in range(0,n[3])]for c in range(0,n[2])]for b in range(0,n[1])]for a in range(0,n)]\nu = [[[[[for e1 in range(0,n[4])]for d1 in range(0,n[3])]for c1 in range(0,n[2])]for b1 in range(0,n[1])]for a1 in range(0,n)]\n#Iniciamos la comunicacion con OpenOffice\n#desktop = pyoo.Desktop(\"localhost\", 2002)\n#Abrimos el documento de datos\n#doc = desktop.open_spreadsheet(base_datos.ods)\n\n#Lectura de los datos\n#sheet = doc.sheets[0]\n#while dato = \"\":\n#\tdato = sheet[j,0].value\n#\tj = j + 1\n\t#Leemos los datos del .ods\n#for r in range(0,j-1):\n#\tfor i in range(0,n[1]-1):\n#\t\tz[r+1][i+1] = sheet[r,i].value\n\n#-------------------------------------------------------------\n#Inicio del codigo de la neurona\n#-------------------------------------------------------------\n\nw = valores_ramdom_w(n)\nu = valores_ramdom_u(n)\nfor h in range(1,len(z)-1):\n\ta = calculo_neuronas(w,u,z[h],n)\n\terr = calculo_funcion_error(s,a[4][1])\n\terr_mod = -err/a[4][1]\n\twhile err_mod > 0.05:\n\t\tw = nueva_w_nivel3(w,a,a[4][1],n,alfa,err)\n\t\tw = nueva_w_nivel2(w,a,a[4][1],n,alfa,err)\n\t\tw = nueva_w_nivel1(w,a,a[4][1],n,alfa,err,z[h])\n\t\tu = nueva_u_nivel3(u,a,a[4][1],n,alfa,err)\n\t\tu = nueva_u_nivel2(u,a,a[4][1],n,alfa,err)\n\t\tu = nueva_u_nivel1(u,a,a[4][1],n,alfa,err,z[h])\n\t\ta = calculo_neuronas(w,u,z[h])\n\t\terr = calculo_funcion_error(s,a[4][1])\n\t\terr_mod = -err/a[4][1]"} {"blob_id": "44f768df7f8fdf4e777ff9262c7338a7542d7d91", "repo_name": "A432-git/Leetcode_in_python3", "path": "/106_\u4ece\u4e2d\u5e8f\u4e0e\u540e\u5e8f\u904d\u5386\u5e8f\u5217\u6784\u9020\u4e8c\u53c9\u6811.py", "length_bytes": 656, "score": 3.734375, "int_score": 4, "content": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jun 20 09:03:47 2020\n\n@author: leiya\n\"\"\"\n\n\nclass Solution:\n def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:\n if not postorder or not inorder:\n return None\n root = TreeNode(postorder[-1])\n index = inorder.index(root.val)\n #left + root = index+1\u4e2a\uff0c\u90a3\u4e48\u5728postorder\u4e2d\u4ece\u96f6\u5f00\u59cb\u5230index\u6b63\u597d\u6709index\u4e2aleft nodes\n left_node = self.buildTree(inorder[:index],postorder[:index])\n right_node = self.buildTree(inorder[index+1:],postorder[index:-1])\n root.left = left_node\n root.right = right_node\n return root"} {"blob_id": "62f9f166001eee5820763c9f96a02e26068367a8", "repo_name": "chenxu0602/LeetCode", "path": "/355.design-twitter.py", "length_bytes": 3438, "score": 4.1875, "int_score": 4, "content": "#\n# @lc app=leetcode id=355 lang=python3\n#\n# [355] Design Twitter\n#\n# https://leetcode.com/problems/design-twitter/description/\n#\n# algorithms\n# Medium (27.39%)\n# Likes: 483\n# Dislikes: 139\n# Total Accepted: 35K\n# Total Submissions: 127.3K\n# Testcase Example: '[\"Twitter\",\"postTweet\",\"getNewsFeed\",\"follow\",\"postTweet\",\"getNewsFeed\",\"unfollow\",\"getNewsFeed\"]\\n' +\n#\n# Design a simplified version of Twitter where users can post tweets,\n# follow/unfollow another user and is able to see the 10 most recent tweets in\n# the user's news feed. Your design should support the following methods:\n# \n# \n# \n# postTweet(userId, tweetId): Compose a new tweet.\n# getNewsFeed(userId): Retrieve the 10 most recent tweet ids in the user's news\n# feed. Each item in the news feed must be posted by users who the user\n# followed or by the user herself. Tweets must be ordered from most recent to\n# least recent.\n# follow(followerId, followeeId): Follower follows a followee.\n# unfollow(followerId, followeeId): Follower unfollows a followee.\n# \n# \n# \n# Example:\n# \n# Twitter twitter = new Twitter();\n# \n# // User 1 posts a new tweet (id = 5).\n# twitter.postTweet(1, 5);\n# \n# // User 1's news feed should return a list with 1 tweet id -> [5].\n# twitter.getNewsFeed(1);\n# \n# // User 1 follows user 2.\n# twitter.follow(1, 2);\n# \n# // User 2 posts a new tweet (id = 6).\n# twitter.postTweet(2, 6);\n# \n# // User 1's news feed should return a list with 2 tweet ids -> [6, 5].\n# // Tweet id 6 should precede tweet id 5 because it is posted after tweet id\n# 5.\n# twitter.getNewsFeed(1);\n# \n# // User 1 unfollows user 2.\n# twitter.unfollow(1, 2);\n# \n# // User 1's news feed should return a list with 1 tweet id -> [5],\n# // since user 1 is no longer following user 2.\n# twitter.getNewsFeed(1);\n# \n# \n#\n\nimport itertools\nfrom collections import defaultdict, deque\nimport heapq\n\nclass Twitter:\n\n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n self.timer = itertools.count(step=-1)\n self.tweets = defaultdict(deque)\n self.followees = defaultdict(set)\n \n def postTweet(self, userId: int, tweetId: int) -> None:\n \"\"\"\n Compose a new tweet.\n \"\"\"\n self.tweets[userId].appendleft((next(self.timer), tweetId))\n\n def getNewsFeed(self, userId: int) -> List[int]:\n \"\"\"\n Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent.\n \"\"\"\n tweets = heapq.merge(*(self.tweets[u] for u in self.followees[userId] | {userId}))\n return [t for _, t in itertools.islice(tweets, 10)]\n \n\n def follow(self, followerId: int, followeeId: int) -> None:\n \"\"\"\n Follower follows a followee. If the operation is invalid, it should be a no-op.\n \"\"\"\n self.followees[followerId].add(followeeId)\n\n def unfollow(self, followerId: int, followeeId: int) -> None:\n \"\"\"\n Follower unfollows a followee. If the operation is invalid, it should be a no-op.\n \"\"\"\n self.followees[followerId].discard(followeeId)\n\n\n# Your Twitter object will be instantiated and called as such:\n# obj = Twitter()\n# obj.postTweet(userId,tweetId)\n# param_2 = obj.getNewsFeed(userId)\n# obj.follow(followerId,followeeId)\n# obj.unfollow(followerId,followeeId)\n\n"} {"blob_id": "7eeb6216d5fb56ed73fe6667de37e05fb95379b3", "repo_name": "raghus100/Algorithm-Implementation", "path": "/String_Algorithms.py", "length_bytes": 1215, "score": 3.5625, "int_score": 4, "content": "class Solution:\n res = []\n def permutate(self, soFar, rest):\n if (len(rest) <=0):\n print(soFar+rest)\n self.res.append((soFar+rest))\n return\n else:\n for i in range(len(rest)):\n rest_string = rest[0:i]+rest[i+1:len(rest)]\n self.permutate(soFar+rest[i], rest_string)\n\n def permutate_iterate(self, str):\n count = 0\n for i in range(len(str)):\n for j in range(len(str)):\n tmp = str[0:i]+str[j]+str[i+1:j]+str[i]+str[j+1:len(str)]\n print(tmp)\n count += 1\n print(count)\n\n def permutation(self, rest, so_far):\n if not rest:\n print(so_far)\n return\n for i, j in enumerate(rest):\n remain = rest[0:i] + rest[i+1:len(rest)]\n self.permutation(remain, so_far + [j])\n\n\n def getPermutation(self, n: int, k: int) -> str:\n in_list = list(range(1, n+1))\n so_far = []\n self.permutation(in_list, [])\n\nif __name__ == '__main__':\n str = 'abcd'\n sol = Solution()\n # sol.permutate('', str)\n #print(len(sol.res))\n # sol.permutate_iterate(str)\n sol.getPermutation(3, 3)\n"} {"blob_id": "99b2566ef247b94245253783ba9720f402d383d6", "repo_name": "nilax97/leetcode-solutions", "path": "/solutions/Validate Binary Search Tree/solution.py", "length_bytes": 569, "score": 3.84375, "int_score": 4, "content": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def isValidBST(self, root: TreeNode) -> bool:\n def preorder(root):\n if root == None:\n return []\n return preorder(root.left) + [root.val] + preorder(root.right)\n tree = preorder(root)\n for i in range(1,len(tree)):\n if tree[i] <= tree[i-1]:\n return False\n return True\n"} {"blob_id": "2134ff797134585d45133bff0d381d3a150ee3e3", "repo_name": "chenxu0602/LeetCode", "path": "/1759.count-number-of-homogenous-substrings.py", "length_bytes": 1482, "score": 3.828125, "int_score": 4, "content": "#\n# @lc app=leetcode id=1759 lang=python3\n#\n# [1759] Count Number of Homogenous Substrings\n#\n# https://leetcode.com/problems/count-number-of-homogenous-substrings/description/\n#\n# algorithms\n# Medium (41.21%)\n# Likes: 106\n# Dislikes: 15\n# Total Accepted: 7.9K\n# Total Submissions: 19.2K\n# Testcase Example: '\"abbcccaa\"'\n#\n# Given a string s, return the number of homogenous substrings of s. Since the\n# answer may be too large, return it modulo 10^9 + 7.\n# \n# A string is homogenous if all the characters of the string are the same.\n# \n# A substring is a contiguous sequence of characters within a string.\n# \n# \n# Example 1:\n# \n# \n# Input: s = \"abbcccaa\"\n# Output: 13\n# Explanation: The homogenous substrings are listed as below:\n# \"a\" appears 3 times.\n# \"aa\" appears 1 time.\n# \"b\" appears 2 times.\n# \"bb\" appears 1 time.\n# \"c\" appears 3 times.\n# \"cc\" appears 2 times.\n# \"ccc\" appears 1 time.\n# 3 + 1 + 2 + 1 + 3 + 2 + 1 = 13.\n# \n# Example 2:\n# \n# \n# Input: s = \"xy\"\n# Output: 2\n# Explanation: The homogenous substrings are \"x\" and \"y\".\n# \n# Example 3:\n# \n# \n# Input: s = \"zzzzz\"\n# Output: 15\n# \n# \n# \n# Constraints:\n# \n# \n# 1 <= s.length <= 10^5\n# s consists of lowercase letters.\n# \n#\n\n# @lc code=start\nimport itertools\n\nclass Solution:\n def countHomogenous(self, s: str) -> int:\n res = 0\n for c, s in itertools.groupby(s):\n n = len(list(s))\n res += n * (n + 1) // 2\n return res % (10**9 + 7)\n \n# @lc code=end\n\n"} {"blob_id": "29ce07cfbb0c84442a92e1e199db4ba35eb11229", "repo_name": "ArjunPraveen/YeetCode", "path": "/Strings/longestPalindrome_5.py", "length_bytes": 957, "score": 3.5625, "int_score": 4, "content": "class Solution:\n def checkCentres(self, s, l, r):\n if l>r:\n return 0\n while (l>=0 and r str:\n if s==\"\" or len(s)<2:\n return s\n start = 0\n end = 0\n for i in range(len(s)):\n l1 = self.checkCentres(s,i,i)\n l2 = self.checkCentres(s,i,i+1)\n length = max(l1,l2)\n print(str(l1) + str(l2))\n #print(str(start) + \" \"+str(end) + \" \" + str(length))\n if length > (end-start):\n #print(length)\n start = i - ((length-1)//2 )\n end = i + (length//2)\n \n print(\" --- \")\n return s[start:end+1]\n \n \n \n \n \n \n \n \n"} {"blob_id": "4bea2aa9f65dc46094022529b2666bd0ebd4a252", "repo_name": "chinatsui/DimondDog", "path": "/algorithm/exercise/hash_table/find_two_squares_sum.py", "length_bytes": 943, "score": 4.3125, "int_score": 4, "content": "\"\"\"\nGiven a number 'num', find another two numbers 'a' and 'b' to make pow(a,2) + pow(b,2) = num, then return [a,b]\nIf there doesn't exist such a pair of numbers, return an empty array.\n\nExample 1:\nInput: 58.\nOutput: [3, 7]\nExplanation: 3^2 + 7^2 = 58\n\nExample 2:\nInput: 12.\nOutput: []\nExplanation: There doesn't exist a pair of numbers to make pow(a,2) + pow(b,2) == 12\n\"\"\"\n\n\nclass Solution:\n\n def find_two_square_nums(self, num):\n if num < 0:\n return []\n\n max_sqrt = self._max_sqrt(num)\n i, j = 0, max_sqrt\n while i <= j:\n sum = pow(i, 2) + pow(j, 2)\n if sum == num:\n return [i, j]\n elif sum < num:\n i += 1\n else:\n j -= 1\n return []\n\n @staticmethod\n def _max_sqrt(n):\n i = 0\n while pow(i, 2) <= n:\n i += 1\n return i - 1\n\n\nprint(Solution().find_two_square_nums(12))\n"} {"blob_id": "bfd415ff430d3508421c04dc3139a6a2438719a2", "repo_name": "anatu/CS221-Fall2018", "path": "/1_foundations/submission_v3.py", "length_bytes": 6120, "score": 4.03125, "int_score": 4, "content": "import collections\nimport math\n\n############################################################\n# Problem 3a\n\ndef findAlphabeticallyLastWord(text):\n \"\"\"\n Given a string |text|, return the word in |text| that comes last\n alphabetically (that is, the word that would appear last in a dictionary).\n A word is defined by a maximal sequence of characters without whitespaces.\n You might find max() and list comprehensions handy here.\n \"\"\"\n # BEGIN_YOUR_CODE (our solution is 1 line of code, but don't worry if you deviate from this)\n return max(text.split(\" \"))\n # END_YOUR_CODE\n\n############################################################\n# Problem 3b\n\ndef euclideanDistance(loc1, loc2):\n \"\"\"\n Return the Euclidean distance between two locations, where the locations\n are pairs of numbers (e.g., (3, 5)).\n \"\"\"\n # BEGIN_YOUR_CODE (our solution is 1 line of code, but don't worry if you deviate from this)\n return math.sqrt(sum([(a - b)**2 for a,b in zip(loc1, loc2)]))\n # END_YOUR_CODE\n\n############################################################\n# Problem 3c\n\ndef mutateSentences(sentence):\n \"\"\"\n Given a sentence (sequence of words), return a list of all \"similar\"\n sentences.\n We define a sentence to be similar to the original sentence if\n - it as the same number of words, and\n - each pair of adjacent words in the new sentence also occurs in the original sentence\n (the words within each pair should appear in the same order in the output sentence\n as they did in the orignal sentence.)\n Notes:\n - The order of the sentences you output doesn't matter.\n - You must not output duplicates.\n - Your generated sentence can use a word in the original sentence more than\n once.\n Example:\n - Input: 'the cat and the mouse'\n - Output: ['and the cat and the', 'the cat and the mouse', 'the cat and the cat', 'cat and the cat and']\n (reordered versions of this list are allowed)\n \"\"\"\n # BEGIN_YOUR_CODE (our solution is 20 lines of code, but don't worry if you deviate from this)\n def compute_mutations(starter, candidates):\n if (len(starter) == len(candidates) + 1):\n return starter\n for candidate in candidates:\n if starter[-1] == candidate[0]:\n result = starter + [candidate[1]]\n return compute_mutations(result, candidates) \n \n bigrams = []\n split_sent = sentence.lower().split(\" \")\n for i in range(0, len(split_sent)-1):\n bigrams.append([split_sent[i], split_sent[i + 1]])\n\n mutated_sents = []\n mutated_sents.append(sentence.lower())\n for starter in bigrams:\n final = compute_mutations(starter, bigrams)\n if final is not None:\n mutated_sents.append(\" \".join(final))\n\n return mutated_sents\t\t \n # END_YOUR_CODE\n\n############################################################\n# Problem 3d\n\ndef sparseVectorDotProduct(v1, v2):\n \"\"\"\n Given two sparse vectors |v1| and |v2|, each represented as collections.defaultdict(float), return\n their dot product.\n You might find it useful to use sum() and a list comprehension.\n This function will be useful later for linear classifiers.\n \"\"\"\n # BEGIN_YOUR_CODE (our solution is 4 lines of code, but don't worry if you deviate from this)\n dot_prod = 0\n for key in set.intersection(set(v1.keys()), set(v2.keys())):\n dot_prod = dot_prod + (v1[key] * v2[key])\n return dot_prod\n # END_YOUR_CODE\n\n############################################################\n# Problem 3e\n\ndef incrementSparseVector(v1, scale, v2):\n \"\"\"\n Given two sparse vectors |v1| and |v2|, perform v1 += scale * v2.\n This function will be useful later for linear classifiers.\n \"\"\"\n # BEGIN_YOUR_CODE (our solution is 2 lines of code, but don't worry if you deviate from this)\n for key in v2.keys():\n v1[key] = v1[key] + scale*v2[key]\n return v1\n # END_YOUR_CODE\n\n############################################################\n# Problem 3f\n\ndef findSingletonWords(text):\n \"\"\"\n Splits the string |text| by whitespace and returns the set of words that\n occur exactly once.\n You might find it useful to use collections.defaultdict(int).\n \"\"\"\n # BEGIN_YOUR_CODE (our solution is 4 lines of code, but don't worry if you deviate from this)\n splittext = text.split(\" \")\n return set([i for i in splittext if splittext.count(i) == 1])\n # END_YOUR_CODE\n\n############################################################\n# Problem 3g\n\ndef computeLongestPalindromeLength(text):\n \"\"\"\n A palindrome is a string that is equal to its reverse (e.g., 'ana').\n Compute the length of the longest palindrome that can be obtained by deleting\n letters from |text|.\n For example: the longest palindrome in 'animal' is 'ama'.\n Your algorithm should run in O(len(text)^2) time.\n You should first define a recurrence before you start coding.\n \"\"\"\n # BEGIN_YOUR_CODE (our solution is 19 lines of code, but don't worry if you deviate from this) \n def recurse(text):\n if len(text) >= 3:\n if text.count(text[0]) % 2 > 0: text = text.replace(text[0], \"\")\n if text.count(text[-1]) % 2 > 0: text = text.replace(text[-1], \"\")\n if text == text[::-1]: return text\n for letter in text:\n if text.count(letter) == 1:\n text = text.replace(letter, \"\")\n if text == text[::-1]:\n return text\n else:\n return recurse(text) \n elif text == text[::-1]:\n return text\n else:\n continue\n \n result = recurse(text)\n return len(result)\n # END_YOUR_CODE\n \n\n \t# Start in the middle, check letters on either side of middle for even digits of frequency.\n \t# Delete the one with odd freq. number, and start deleting odds until you have a palindrome.\n \t# Have one function \"run\" clean the string of all the odds and then check the palindrome condition.\n\n # END_YOUR_CODE\n"} {"blob_id": "bc5559a1bc290be5e955e226699ab8856998f97e", "repo_name": "xz1082/assignment5", "path": "/wl1207/assignment5.py", "length_bytes": 2934, "score": 3.828125, "int_score": 4, "content": "#Q1\nclass interval():\n def __init__(self, string):\n self.string = string\n self.lbd = string[0]\n self.ubd = string[-1]\n self.index = string.find(',')\n self.value1 = int(string[1:self.index])\n self.value2 = int(string[self.index+1:-1])\n if self.lbd == '[' and self.ubd == ']' and self.value1 <=self.value2:\n self.lower = self.value1\n self.upper = self.value2\n elif self.lbd == '[' and self.ubd == ')' and self.value1 <= self.value2-1:\n self.lower = self.value1\n self.upper = self.value2-1\n elif self.lbd == '(' and self.ubd == ']' and self.value1+1 <= self.value2:\n self.lower = self.value1+1\n self.upper = self.value2\n elif self.lbd == '(' and self.ubd == ')' and self.value1+1 <= self.value2-1:\n self.lower = self.value1+1\n self.upper = self.value2-1\n else:\n raise Exception(\"invalid value\")\n \n def __repr__(self):\n return self.string\n\n#Q2\ndef mergeIntervals(int1, int2):\n merge_interval = \"\"\n if int1.upper < (int2.lower -1) or int2.upper < (int1.lower-1):\n raise Exception(\"The intervals do not overlap! \")\n \n if int1.lower < int2.lower or (int1.lower == int2.lower and int1.value1 <= int2.value1):\n merge_interval = merge_interval + int1.lbd + str(int1.lower) + \",\"\n else:\n merge_interval = merge_interval + int2.lbd +str(int2.value1) + \",\"\n \n if int1.upper < int2.upper or (int1.upper == int2.upper and int1.value2 <= int2.value2):\n merge_interval = merge_interval + str(int2.value2) + int2.ubd\n else:\n merge_interval = merge_interval + str(int1.value2) + int1.ubd\n \n merged_interval = interval(merge_interval)\n return merged_interval\n\n#Q3\ndef mergeOverlapping(intlist):\n intlist = sorted(intlist, key=lambda int:(int.lower))\n merged_list = []\n while len(intlist)>0:\n try:\n intlist[0] = mergeIntervals(intlist[0],intlist[1])\n del intlist[1]\n except:\n merged_list.append(intlist[0])\n del intlist[0]\n return merged_list \n\n#Q4\ndef insert(intlist, newint):\n intlist.append(newint)\n return mergeOverlapping(intlist)\n\n#Q5\ndef main():\n input_string = raw_input(\"List of intervals? \")\n input_list = input_string.split(', ')\n merged_list = []\n for item in input_list:\n merged_list.append(interval(item))\n merged_list = mergeOverlapping(merged_list)\n while True:\n add_string = raw_input(\"Interval? \")\n if add_string != 'quit':\n try:\n merged_list.append(interval(add_string))\n print \"...result of inserting into list...\"\n print mergeOverlapping(merged_list)\n except:\n print \"Invalid interval\"\n else:\n break\n\nif __name__ == '__main__':\n main()\n"} {"blob_id": "4ea6e28f72e677046c82e365a70e6abae94cb828", "repo_name": "sugia/leetcode", "path": "/Remove Invalid Parentheses.py", "length_bytes": 1412, "score": 4.0, "int_score": 4, "content": "'''\n\nRemove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results.\n\nNote: The input string may contain letters other than the parentheses ( and ).\n\nExample 1:\n\nInput: \"()())()\"\nOutput: [\"()()()\", \"(())()\"]\nExample 2:\n\nInput: \"(a)())()\"\nOutput: [\"(a)()()\", \"(a())()\"]\nExample 3:\n\nInput: \")(\"\nOutput: [\"\"]\n'''\n\nclass Solution(object):\n def removeInvalidParentheses(self, s):\n \"\"\"\n :type s: str\n :rtype: List[str]\n \"\"\"\n vec = set([s])\n while len(vec):\n next_vec = set()\n for item in vec:\n if self.valid(item) and item not in next_vec:\n next_vec.add(item)\n \n if next_vec:\n return list(next_vec)\n \n for item in vec:\n for i in xrange(len(item)):\n tmp = item[:i] + item[i+1:]\n if tmp not in next_vec:\n next_vec.add(tmp)\n \n vec = next_vec\n \n return []\n \n def valid(self, item):\n count = 0\n for c in item:\n if c == '(':\n count += 1\n elif c == ')':\n count -= 1\n if count < 0:\n return False\n \n if count == 0:\n return True\n return False\n"} {"blob_id": "9c10af82a82570c919d83811dff2802a6f708e03", "repo_name": "anguszxd/leetcode2", "path": "/PermutationsII.py", "length_bytes": 738, "score": 3.859375, "int_score": 4, "content": "#coding:utf-8\n\n#Given a collection of numbers that might contain duplicates, return all possible unique permutations.\n\n\n#For example,\n#[1,1,2] have the following unique permutations:\n#[1,1,2], [1,2,1], and [2,1,1].\n\n#Solution:\u8ddf\u524d\u9762\u7684\u5168\u6392\u5217\u7c7b\u4f3c\uff0c\u6539\u8fdb\u7684\u5730\u65b9\u5728\u4e8e\u5148\u5224\u65ad\u653e\u5728\u7b2c\u4e00\u4f4d\u7684\u5143\u7d20\u6709\u6ca1\u6709\u51fa\u73b0\u8fc7\uff0c\n#\u5982\u679c\u5df2\u7ecf\u4f7f\u7528\u8fc7\u4e86\uff0c\u5c31\u8df3\u8fc7\u8be5\u5faa\u73af\ndef permute(nums,ans,path):\n\tif len(nums) == 1:\n\t\t#if path+nums not in ans:\n\t\tans.append(path+nums)\n\t\treturn\n\tused = []\n\tfor i in range(len(nums)):\n\t\tif nums[i] not in used:\n\t\t\tused.append(nums[i])\n\t\t\tpermute(nums[0:i]+nums[i+1:],ans,path+[nums[i]])\n\t\t\t#used.append(nums[i])\n\n\nA = [1,1,0,0,1,-1,-1,1]\nans = []\npath = []\npermute(A,ans,path)\n\nprint ans,len(ans)"} {"blob_id": "2124ae018076b8ed8a380ac613ded46ba9c50ed1", "repo_name": "tingleshao/leetcode", "path": "/interleaving_string/main.py", "length_bytes": 1200, "score": 3.765625, "int_score": 4, "content": "\nclass Solution:\n # @return a boolean\n def isInterleave(self, s1, s2, s3):\n # print len(s1)\n # print len(s2)\n #s print len(s3)\n if len(s3) != (len(s1) + len(s2)):\n return False\n\n table = [[False for i in range(len(s2)+1)] for j in range(len(s1)+1)]\n # print table\n \n for i in xrange(len(s1)+1):\n for j in xrange(len(s2)+1):\n if i == 0 and j == 0:\n table[i][j] = True\n elif i == 0:\n # print \"i:\"+str(i) \n # print \"j:\"+str(j)\n # print \"a1\"+str(s3[i+j-1]) \n # print \"xx\"\n table[i][j] = table[i][j-1] and s2[j-1] == s3[i+j-1]\n elif j == 0:\n table[i][j] = table[i-1][j] and s1[i-1] == s3[i+j-1]\n else:\n table[i][j] = (table[i-1][j] and s1[i-1] == s3[i+j-1]) or (table[i][j-1] and s2[j-1] == s3[i+j-1])\n # print table\n return table[len(s1)][len(s2)]\n \ndef main():\n s = Solution()\n s1 = \"aabcc\"\n s2 = \"dbbca\"\n s3 = \"aadbbcbcac\"\n s4 = \"aadbbbaccc\"\n print s.isInterleave(s1,s2,s3)\n print \"======\"\n print s.isInterleave(s1,s2,s4)\n \nif __name__ == \"__main__\":\n main()"} {"blob_id": "907c008de30d2238a729f5245af0623721d5f96e", "repo_name": "leon0241/adv-higher-python", "path": "/Project Euler/Resources/prime_algorithms.py", "length_bytes": 1225, "score": 4.21875, "int_score": 4, "content": "import math\n\ndef find_primes(n): #Finds primes below n\n primeList = [2]\n for i in range(3, n, 2):\n primeList.append(i) #Makes array of odd number to number n(even numbers are not prime)\n\n for i in range(3, (int(math.sqrt(n)) + 1), 2):\n #cycle for i = 3\n for j in primeList:\n if j % i == 0 and j > i:\n primeList.remove(j)\n return primeList\n\ndef find_max_prime(n): #Finds the largest prime below n\n list = find_primes(n)\n return max(list)\n\ndef check_prime(n): #Checks if n is a prime\n if n == 1: #Checks if n = 1\n return False #Is not prime\n elif n <= 3: #Checks if n = 2 or 3\n return True #Is prime\n\n i = 5\n while i * i <= n: #k\u00b11 shows prime number idk\n if n % i == 0 or n % (i + 2) == 0:\n return False\n i += 6\n return True #Returns true if it is prime\n\ndef find_nth_prime(n): #Finds nth prime\n #Inequality for nth prime\n #pn > n*ln(n*ln(n)) for n \u2265 6.\n upperBound = n * math.log(n * math.log(n)) #Sets upper boundary\n intUpper = round(upperBound) #Rounds to nearest integer\n primeList = find_primes(intUpper) #Finds of primes below boundary\n return primeList[n - 1] #Return nth prime\n"} {"blob_id": "6a488674fc998c0b8c5c68aa5fb35201d01c9487", "repo_name": "sc4599/LeetCode", "path": "/231/__init__.py", "length_bytes": 1403, "score": 3.828125, "int_score": 4, "content": "# coding=utf-8\n__author__ = 'songchao'\n\n # \u5c062\u7684\u5e42\u6b21\u65b9\u5199\u6210\u4e8c\u8fdb\u5236\u5f62\u5f0f\u540e\uff0c\u5f88\u5bb9\u6613\u5c31\u4f1a\u53d1\u73b0\u6709\u4e00\u4e2a\u7279\u70b9\uff1a\u4e8c\u8fdb\u5236\u4e2d\u53ea\u6709\u4e00\u4e2a1\uff0c\u5e76\u4e141\u540e\u9762\u8ddf\u4e86n\u4e2a0\uff1b\n # \u56e0\u6b64\u95ee\u9898\u53ef\u4ee5\u8f6c\u5316\u4e3a\u5224\u65ad1\u540e\u9762\u662f\u5426\u8ddf\u4e86n\u4e2a0\u5c31\u53ef\u4ee5\u4e86\u3002\n # \u5982\u679c\u5c06\u8fd9\u4e2a\u6570\u51cf\u53bb1\u540e\u4f1a\u53d1\u73b0\uff0c\u4ec5\u6709\u7684\u90a3\u4e2a1\u4f1a\u53d8\u4e3a0\uff0c\u800c\u539f\u6765\u7684\u90a3n\u4e2a0\u4f1a\u53d8\u4e3a1\uff1b\n # \u56e0\u6b64\u5c06\u539f\u6765\u7684\u6570\u4e0e\u53bb\u51cf\u53bb1\u540e\u7684\u6570\u5b57\u8fdb\u884c\u4e0e\u8fd0\u7b97\u540e\u4f1a\u53d1\u73b0\u4e3a\u96f6\u3002\n # \u6700\u5feb\u901f\u7684\u65b9\u6cd5\uff1a\n #\n # (number & number - 1) == 0\n #\n # \u539f\u56e0\uff1a\u56e0\u4e3a2\u7684N\u6b21\u65b9\u6362\u7b97\u662f\u4e8c\u8fdb\u5236\u4e3a10\u2026\u20260\u8fd9\u6837\u7684\u5f62\u5f0f(0\u9664\u5916)\u3002\u4e0e\u4e0a\u81ea\u5df1-1\u7684\u4f4d\u6570\uff0c\u8fd9\u4eec\u5f97\u5230\u7ed3\u679c\u4e3a0\u3002\n # \u4f8b\u5982\u30028\u7684\u4e8c\u8fdb\u5236\u4e3a1000\uff1b8-1=7\uff0c7\u7684\u4e8c\u8fdb\u5236\u4e3a111\u3002\u4e24\u8005\u76f8\u4e0e\u7684\u7ed3\u679c\u4e3a0\u3002\u8ba1\u7b97\u5982\u4e0b\uff1a\n # 1000\n # & 0111\n # -------\n # 0000\n #\n # \u4f7f\u7528\u9012\u5f52\u6765\u5b9e\u73b0\u7684\u4ee3\u7801\u5982\u4e0b\uff1a\n\n\nclass Solution(object):\n def isPowerOfTwo(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n\n return n&(n-1) == 0\n\n\nimport unittest\n\n\nclass TestSolution(unittest.TestCase):\n def test_isPowerOfTwo(self):\n cls = Solution()\n r = cls.isPowerOfTwo(1)\n self.assertEqual(r, True)\n self.assertEqual(cls.isPowerOfTwo(2), True)\n self.assertEqual(cls.isPowerOfTwo(6), False)\n self.assertEqual(cls.isPowerOfTwo(8), True)\n"} {"blob_id": "aa5d5322d84d8c10d9a5c9ccb2cebc5173caf933", "repo_name": "arogovoy/leetcode", "path": "/py/permutations.py", "length_bytes": 1820, "score": 3.84375, "int_score": 4, "content": "# 46. Permutations\n# Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.\n#\n# Example 1:\n# Input: nums = [1,2,3]\n# Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]\n#\n# Example 2:\n# Input: nums = [0,1]\n# Output: [[0,1],[1,0]]\n#\n# Example 3:\n# Input: nums = [1]\n# Output: [[1]]\nfrom typing import List\n\n\nclass Solution1:\n def combinations(self, arr: List[int], v: int):\n result = []\n for i in range(len(arr) + 1):\n t, k = [], 0\n for j in range(len(arr) + 1):\n if i != j:\n t.append(arr[k])\n k += 1\n else:\n t.append(v)\n\n result.append(t)\n return result\n\n def append(self, i: int, nums: List[int], variants: List[List[int]]):\n if i >= len(nums):\n return variants\n result = []\n for j in range(len(variants)):\n result += self.combinations(variants[j], nums[i])\n return self.append(i + 1, nums, result)\n\n def permute(self, nums: List[int]) -> List[List[int]]:\n return self.append(1, nums, [[nums[0]]])\n\nclass Solution:\n def permute(self, nums: List[int]) -> List[List[int]]:\n result = []\n if len(nums) == 1:\n return [[nums[0]]]\n\n for i in range(len(nums)):\n v = nums.pop(0)\n combinations = self.permute(nums)\n for j in range(len(combinations)):\n combinations[j].append(v)\n result.extend(combinations)\n nums.append(v)\n\n return result\n\n\nif __name__ == '__main__':\n res = Solution().permute([1, 2, 3])\n print(res)\n\n # res = Solution().permute([0, 1])\n # print(res)\n #\n # res = Solution().permute([1])\n # print(res)\n"} {"blob_id": "93e0bfcf6a17fcbeafca3b7af962534000140c58", "repo_name": "mkoryor/Python", "path": "/arrays & strings/unsortedSub.py", "length_bytes": 1227, "score": 4.09375, "int_score": 4, "content": "\n\n\n\n\n''' (Traverse Both Ends [M]): Given an array of integers, find the continuous \nsubarray, which when sorted, results in the entire array being sorted.For example: \nA = [0,2,3,1,8,6,9], result is the subarray [2,3,1,8,6]'''\n\ndef unsorted_sub(arr):\n\n start = 0\n end = len(arr) - 1\n\n # find start of dip\n while start <= len(arr) - 1:\n if arr[start + 1] < arr[start]:\n break\n start += 1\n\n # no dip found \n if start == len(arr) - 1:\n return None\n\n # find bump from end\n while end >= 0:\n if arr[end - 1] > arr[end]:\n break\n end -= 1\n\n # subarray from arr[start:end + 1]\n sub = arr[start: end + 1]\n\n # find max and min in sub\n max_val = min(sub)\n min_val = max(sub)\n k = start \n\n while k <= end:\n if arr[k] > max_val:\n max_val = arr[k]\n\n if arr[k] < min_val:\n min_val = arr[k]\n k += 1\n\n # expand start and end outward\n while start > 0 and arr[start - 1] > min_val:\n start -= 1\n while end < len(arr) - 1 and arr[end + 1] < max_val:\n end += 1\n\n return arr[start: end + 1]\n\nprint(unsorted_sub([0,2,3,1,8,6,9]))\n\n\n# Output: [2,3,1,8,6]\n# Time: O(n) Space: O(1)\n\n\n"} {"blob_id": "0da9a31255de863a9ec641b724b63dcbe32fe68e", "repo_name": "skamens/advent_of_code_2020", "path": "/day22/crab.py", "length_bytes": 3915, "score": 3.671875, "int_score": 4, "content": "#!/usr/bin/python3\n\nimport sys\nimport re\nimport math\nimport functools\nimport copy\n\nfilename = 'day22/input.txt'\n\nclass Deck:\n \n def __init__(self):\n self.cards = []\n self.playerNum = 0\n\n def load(self, file_obj):\n line = f_obj.readline()\n a = re.match(r'^Player (\\d+).*', line)\n self.playerNum = int(a.group(1))\n\n line = f_obj.readline()\n while (line and (line != '\\n')):\n self.cards.append(int(line))\n line = f_obj.readline()\n print(self.playerNum, \":\", self.cards)\n\n def top(self):\n return self.cards[0]\n\n def hasLost(self):\n return len(self.cards) == 0\n\n def play(self, other):\n if (self.top() > other.top()):\n self.cards.append(self.cards.pop(0))\n self.cards.append(other.cards.pop(0))\n else: \n other.cards.append(other.cards.pop(0))\n other.cards.append(self.cards.pop(0))\n\n def score(self):\n total = 0\n for mult in range(len(self.cards), 0, -1):\n total += mult * self.cards[(len(self.cards) - mult)]\n\n return total\n \n\ndef game1(deck1, deck2):\n while (not (deck1.hasLost() or deck2.hasLost())) :\n deck1.play(deck2)\n\n\n\ndef game2(deck1, deck2):\n rounds = []\n \n while (not (deck1.hasLost() or deck2.hasLost())):\n\n # Before either player deals a card, if there was a previous round in this game that had exactly \n # the same cards in the same order in the same players' decks, the game instantly ends in a win for player 1. \n # Previous rounds from other games are not considered. (This prevents infinite games of \n # Recursive Combat, which everyone agrees is a bad idea.)\n\n for r in rounds:\n if ((r[deck1.playerNum] == deck1.cards) and \n (r[deck2.playerNum] == deck2.cards)) :\n return 1\n\n # Add this round to the list of rounds\n arr = []\n arr.append([])\n arr.append(deck1.cards.copy())\n arr.append(deck2.cards.copy())\n rounds.append(arr)\n\n # Otherwise, this round's cards must be in a new configuration; the players begin the round\n # by each drawing the top card of their deck as normal.\n\n # If both players have at least as many cards remaining in their deck as the value of\n # the card they just drew, the winner of the round is determined by playing \n # a new game of Recursive Combat (see below).\n\n if (deck1.top() <= len(deck1.cards)) and (deck2.top() <= len(deck2.cards)) :\n newDeck1 = Deck()\n newDeck1.playerNum = deck1.playerNum\n newDeck1.cards = deck1.cards[1:deck1.top() + 1]\n\n newDeck2 = Deck()\n newDeck2.playerNum = deck2.playerNum\n newDeck2.cards = deck2.cards[1:deck2.top() + 1]\n\n winner = game2(newDeck1, newDeck2)\n if (winner == deck1.playerNum):\n deck1.cards.append(deck1.cards.pop(0))\n deck1.cards.append(deck2.cards.pop(0))\n else: \n deck2.cards.append(deck2.cards.pop(0))\n deck2.cards.append(deck1.cards.pop(0)) \n \n else:\n deck1.play(deck2)\n\n print (deck1.playerNum, \":\", deck1.cards)\n print (deck2.playerNum, \":\", deck2.cards, \"\\n\")\n\n if deck1.hasLost():\n return deck2.playerNum\n else:\n return deck1.playerNum\n\n\n \n\nwith open(filename) as f_obj:\n # Assume the matrix starts at 0,0 (z is 0)\n # Read the list and add it to the space\n\n deck1 = Deck()\n deck2 = Deck()\n deck1.load(f_obj)\n deck2.load(f_obj)\n\nd1 = copy.deepcopy(deck1)\nd2 = copy.deepcopy(deck2)\ngame1(d1, d2)\n\nd3 = copy.deepcopy(deck1)\nd4 = copy.deepcopy(deck2)\nwinner = game2(d3, d4)\n\nprint (\"winner: \", winner)\nprint (deck1.playerNum, \":\", d3.score())\nprint (deck2.playerNum, \":\", d4.score())\n"} {"blob_id": "80d6b89657bef8e1198450b623c0270058017aa2", "repo_name": "Kirilodius/interview_tasks", "path": "/deijkstra.py", "length_bytes": 1189, "score": 3.6875, "int_score": 4, "content": "def dijkstras(graph, S):\n distance = [float(\"inf\") for g in graph]\n distance[S] = 0\n \n parents = [None for g in graph]\n \n path = set()\n sptSet = [False for g in graph]\n \n notVisited = [i for i in range(len(graph))]\n while len(notVisited) > 0:\n minIndx = getMinDist(distance, notVisited)\n for v in range(len(graph)):\n if (v in notVisited\n and distance[minIndx] != float(\"inf\")\n and graph[minIndx][v] != 0\n and distance[v] > graph[minIndx][v] + distance[minIndx]):\n distance[v] = graph[minIndx][v] + distance[minIndx]\n parents[v] = minIndx\n \n del notVisited[notVisited.index(minIndx)]\n return path\n \ndef getMinDist(distance, notVisited):\n mind = float(\"inf\")\n mIdx = 0\n for idx, vDist in enumerate(distance):\n if idx in notVisited and vDist != float(\"inf\") and vDist < mind:\n mind = vDist\n mIdx = idx\n \n return mIdx\n \n# S T Y X Z\ndijkstras([[0, 10, 5, 0, 0],\n [0, 0, 2, 1, 0], \n [0, 3, 0, 9, 2], \n [0, 0, 0, 0, 4], \n [0, 0, 0, 0, 0]], 0)\n"} {"blob_id": "7cd1b1d8bc85b30db5346d51bf84a6e11d35a5ca", "repo_name": "oskip/IB_Algorithms", "path": "/AddNum.py", "length_bytes": 1010, "score": 3.765625, "int_score": 4, "content": "# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution:\n # @param A : head node of linked list\n # @param B : head node of linked list\n # @return the head node in the linked list\n def addTwoNumbers(self, A, B):\n if self.length(A) > self.length(B): A, B = B, A\n head = A\n carry = 0\n while A and B:\n res = A.val + B.val + carry\n A.val = res%10\n carry = 1 if res > 9 else 0\n if A.next is None: tail = A\n A = A.next\n B = B.next\n A = tail\n while B:\n res = B.val + carry\n A.next = ListNode(res%10)\n carry = 1 if res > 9 else 0\n A = A.next\n B = B.next\n if carry == 1:\n A.next = ListNode(1)\n return head\n\n def length(self, A):\n i = 0\n while A is not None:\n A = A.next\n i += 1\n return i"} {"blob_id": "e66528ae9602fba2ca810c94e4779ab199772392", "repo_name": "jahidhasanshuvo/problem-solving-python", "path": "/graph/cycleDetection.py", "length_bytes": 729, "score": 3.625, "int_score": 4, "content": "def cycleDetect(node, parent):\n visited[node] = True\n print(node)\n for child in graph[node]:\n if not visited[child]:\n if cycleDetect(str(child), node):\n return True\n elif child!=parent:\n return True\n return False\nnumberofNodes, numberOfEdges = [int(x) for x in input().split(' ')]\ngraph = {}\nvisited = {}\nwhile numberOfEdges:\n x,y = input().split(' ')\n if x not in graph.keys():\n graph[x] = []\n visited[x] = False\n if y not in graph.keys():\n graph[y] = []\n visited[y] = False\n graph[x].append(y)\n graph[y].append(x)\n numberOfEdges-=1\nprint(graph, visited)\nprint(cycleDetect('1','-1'))"} {"blob_id": "bec45309121a94713a587bff02b5f153a71d5c16", "repo_name": "orenlivne/euler", "path": "/rosalind/indc/rosalind_indc.py", "length_bytes": 1673, "score": 4.0, "int_score": 4, "content": "'''\n============================================================\nhttp://rosalind.info/problems/indc\n\nConsider a collection of coin flips. One of the most natural\nquestions we can ask is if we flip acoin 92 times, what is the\nprobability of obtaining 51 \"heads\", vs. 27 \"heads\", vs. 92 \"heads\"?\n\nEach coin flip can be modeled by a uniform random variable in which each of the two outcomes\n(\"heads\" and \"tails\") has probability equal to 1/2. We may assume that these random variables\nare independent (see \"Independent Alleles\"); in layman's terms, the outcomes of the two coin flips\ndo not influence each other.\n\nA binomial random variable X takes a value of k if n consecutive \"coin flips\" result in k total \"heads\" and n-k total \"tails.\" We write that X ~ Bin(n,1/2).\n\nGiven: A positive integer n<=50.\n\nReturn: An array A of length 2n in which A[k] represents the common logarithm of the probability that two diploid siblings share at least k of their 2n chromosomes (we do not consider recombination for now).\n============================================================\n'''\nimport rosalind.rosutil as ro, numpy as np, itertools as it\n\ndef indc(f):\n '''Main driver to solve this problem. We use exact arithmetic for binomials\n instead of the betainc function to avoid round-off.'''\n n = 2 * ro.read_int(f)\n # return ro.join_list('%.5f' % (np.log10(1 - ro.cumbin(n, 0.5, k - 1)),) for k in xrange(1, n + 1))\n return ro.join_list('%.3f' % (x,) for x in np.log10(map(float, np.cumsum(it.islice(ro.binom(), n, n + 1).next())))[-2::-1] - n * np.log10(2))\n\nif __name__ == \"__main__\":\n print indc('rosalind_indc_sample.dat')\n print indc('rosalind_indc.dat')\n"} {"blob_id": "5d9adbe2a7041bb3ced833b0596c2754a6f30517", "repo_name": "nunomota/spatial-inequality", "path": "/spatial_inequality/core/greedy_algorithm.py", "length_bytes": 23911, "score": 3.5625, "int_score": 4, "content": "\"\"\"\nGreedy implementation of our school redistricting algorithm (i.e.,\n`Greedy Partitioning`).\n\"\"\"\nimport os\nimport logging\nimport numpy as np\n\nfrom time import time\nfrom datetime import datetime, timedelta\n\nfrom auxiliary.functions import *\n\nfrom optimization.early_stopper import EarlyStopper\nfrom optimization.entity_nodes import District, School\nfrom optimization.holdout import HoldoutQueue\nfrom optimization.lazy_heap import LazyHeap\nfrom optimization.lookup import Lookup\nfrom optimization.run_metrics import RunMetrics\n\n# Initialize logger\nif not os.path.exists('../logs'):\n os.makedirs('../logs')\nlogging.basicConfig(filename='../logs/debug.log', level=logging.INFO)\n\ndef greedily_pick_redistricting_moves(district, lookup, min_schools_per_district, max_schools_per_district):\n \"\"\"\n Greedily calculates all schools that should be redistricted from a selected\n district to one of its neighbors, such that the whole neighborhood's\n inequality is reduced.\n\n To do this, this function arbitrarily iterates over all schools at the\n selected district's border (with its neighboring districts) and evaluates\n whether a given move would be a good (local) move or not. It does this by:\n (i) 'virtually' redistricting the school to another potential district; and\n (ii) comparing both districts' per-student funding after this move was made.\n If funding is closer between the districts, the move is registered and the\n overall iteration process proceeds. Otherwise, the move is reverted before\n proceeding.\n\n Args:\n district (optimization.entity_nodes.District): Target District to redistrict\n schools from.\n lookup (optimization.lookup.Lookup): Lookup instance for fast information\n querying.\n min_schools_per_district (int): Minimum number of schools to preserve in\n each district, upon redistricting. A number equal to (or lesser than)\n zero will allow districts to merge.\n max_schools_per_district (int): Maximum number of schools to be preserved in\n each district, upon redistricting.\n\n Returns:\n list of tuple: List of all greedy School redistricting moves that would\n reduce the selected District neighborhood's inequality (i.e., tuples\n comprised of a redistricted school's standardized NCES ID, its source\n district's standardized NCES ID and its destination district's\n standardized NCES ID).\n \"\"\"\n # Auxiliary functions to make/revert virtual moves\n def make_move(school, from_district, to_district):\n from_district[\"total_funding\"] -= school.get_total_funding()\n from_district[\"total_students\"] -= school.get_total_students()\n from_district[\"n_schools\"] -= 1\n to_district[\"total_funding\"] += school.get_total_funding()\n to_district[\"total_students\"] += school.get_total_students()\n to_district[\"n_schools\"] += 1\n def revert_move(school, from_district, to_district):\n make_move(school, to_district, from_district)\n # Auxiliary function to test if move is good\n def is_good_greedy_move(school, from_district, to_district):\n # Auxiliary functions\n funding_per_student = lambda x: x[\"total_funding\"] / x[\"total_students\"]\n funding_per_student_abs_diff = lambda x,y: abs(funding_per_student(x) - funding_per_student(y))\n # Check if number of schools is allowed\n if from_district[\"n_schools\"] <= min_schools_per_district or to_district[\"n_schools\"] >= max_schools_per_district:\n return False\n # Handle case where no schools would remain in district\n if from_district[\"n_schools\"] == 1:\n return True\n # Calculate stats before/after move\n abs_funding_diff_before = funding_per_student_abs_diff(from_district, to_district)\n make_move(school, from_district, to_district)\n abs_funding_diff_after = funding_per_student_abs_diff(from_district, to_district)\n revert_move(school, from_district, to_district)\n # Return result\n return abs_funding_diff_after < abs_funding_diff_before\n\n # Create auxiliary data structures for (fast) move simulation\n neighboring_districts = lookup.get_neighboor_districts_by_district_id(district.get_id())\n acc_local_values = {\n district.get_id(): {\n \"n_schools\": len(district.get_schools()),\n \"total_students\": district.get_total_students(),\n \"total_funding\": district.get_total_funding()\n } for district in [*neighboring_districts, district]\n }\n # Calculate greedy moves\n greedy_moves = []\n bordering_schools = lookup.get_bordering_schools_by_district_id(district.get_id())\n for school in bordering_schools:\n for neighbor in school.get_neighbors():\n connected_district = lookup.get_district_by_school_id(neighbor.get_id())\n if connected_district.get_id() == district.get_id():\n continue\n elif not is_good_greedy_move(\n school,\n acc_local_values[district.get_id()],\n acc_local_values[connected_district.get_id()]):\n continue\n else:\n # Register move in local accumulators\n make_move(\n school,\n acc_local_values[district.get_id()],\n acc_local_values[connected_district.get_id()]\n )\n # Add new move to move list\n greedy_moves.append((\n school.get_id(),\n district.get_id(),\n connected_district.get_id()\n ))\n # Prevent school multiple assignment\n break\n return greedy_moves\n\ndef apply_redistricting_moves(moves, lookup, heap):\n \"\"\"\n Performs all registered greedy moves and updates both\n optimization.lookup.Lookup and otimization.lazy_heap.LazyHeap instances\n according to the new school/district assignments.\n\n NOTE: Since some of the districts involved in the registered moves may have\n been moved to the holdout queue, updating the lazy heap may raise a KeyError\n exception. In this case, it's safe to skip this step as it will not\n interfere with the heap's order.\n\n Args:\n moves (list of tuple): Greedy moves to apply.\n lookup (optimization.lookup.Lookup): Lookup instance for fast\n information querying.\n heap (otimization.lazy_heap.LazyHeap): LazyHeap of districts to update.\n \"\"\"\n for move in moves:\n # Get all necessary instances\n school = lookup.get_school_by_id(move[0])\n from_district = lookup.get_district_by_id(move[1])\n to_district = lookup.get_district_by_id(move[2])\n # Update \"from\" and \"to\" districts (& update lookup)\n logging.debug(f\"Moving school '{school.get_id()}': '{from_district.get_id()}' > '{to_district.get_id()}'\")\n from_district.remove_school(school)\n to_district.add_school(school)\n lookup.assign_school_to_district_by_id(school.get_id(), to_district.get_id())\n # Try to update heap (elements may be in holdout queue)\n def attempt_heap_update(district):\n try:\n heap.update(district)\n except KeyError:\n pass\n attempt_heap_update(from_district)\n attempt_heap_update(to_district)\n\ndef calculate_inequality(districts, lookup):\n \"\"\"\n Calculate spatial inequality based on a school/district assignment and\n defined districts' neighborhoods, following the (latex) definition:\n\n \\\\[\n \\\\frac{\n \\\\sum_{j=1}^{N} \\\\sum_{i=1}^{N} \\\\left| y_i - y_j \\\\right|\n }{\n 2 N \\\\sum_{i=1}^{N} y_i\n }\n \\\\]\n\n Args:\n districts (list of optimization.entity_nodes.District): List of all\n District instances.\n lookup (optimization.lookup.Lookup): Lookup instance for fast\n information querying.\n\n Returns:\n float: Spatial inequality for a school/district assignment.\n \"\"\"\n get_per_student_funding = lambda district: district.get_total_funding() / district.get_total_students()\n abs_funding_diff = lambda x,y: abs(get_per_student_funding(x) - get_per_student_funding(y))\n overall_inequality = 0\n normalization_factor = 0\n for district in districts:\n neighboring_districts = lookup.get_neighboor_districts_by_district_id(district.get_id())\n full_neighborhood = [*neighboring_districts, district]\n ineq_contribution = sum(map(\n lambda x: abs_funding_diff(district, x),\n full_neighborhood\n ))\n overall_inequality += ineq_contribution / len(full_neighborhood)\n normalization_factor += get_per_student_funding(district)\n return overall_inequality / normalization_factor\n\ndef refill_heap(heap, holdout_queue):\n \"\"\"\n Refills `optimization.lazy_heap.LazyHeap` with any Districts successfully\n dequeued from `optimization.holdout.HoldoutQueue`.\n\n Args:\n heap (optimization.lazy_heap.LazyHeap): LazyHeap instance to refill\n using Districts from the holdout queue.\n holdout_queue (optimization.holdout.HoldoutQueue): HoldoutQueue instance\n containing all districts previously exhausted greedy moves.\n \"\"\"\n # Pop all elements from holdout queue\n is_running = True\n while is_running is True:\n holdout_district = holdout_queue.dequeue()\n # Holdout queue is empty\n if holdout_district is None:\n logging.info(\"No more districts in holdout queue.\")\n holdout_queue.recycle()\n logging.info(\"Recycling holdout queue.\")\n is_running = False\n # Holdout queue had a valid district\n else:\n logging.info(\"Pushing district into heap.\")\n heap.push(holdout_district)\n logging.debug(f\"Pushed district '{holdout_district.get_id()}' into heap.\") \n\ndef greedy_algo(target_state, aug_school_info, school_assignment, min_schools_per_district, max_schools_per_district, early_stopper_it, early_stopper_tol, callbacks):\n \"\"\"\n Applies the greedy partitioning algorithm to a given school/district\n assignment - for a specific state - and attempts to minimize its spatial\n inequality by redistricting schools.\n\n Args:\n target_state (str): Capitalized full state name (e.g., 'Alabama').\n aug_school_info (pandas.DataFrame): Target augmented school information\n (as formatted by `auxiliary.data_handler.DataHandler`).\n school_assignment (pandas.DataFrame): Target school assignment (as\n formatted by `auxiliary.data_handler.DataHandler`).\n min_schools_per_district (int): Minimum number of schools to preserve in\n each district, upon redistricting. A number equal to (or lesser\n than) zero will allow districts to merge.\n max_schools_per_district (int): Maximum number of schools to be\n preserved in each district, upon redistricting.\n early_stopper_it (int): Number of allowed iterations without improvement\n for early stopping.\n early_stopper_tol (float): Tolerance for floating point inequality\n improvement measurement.\n callbacks (dict): Dictionary of (optional) callback functions that will\n be called - by key - at specific stages of the algorithm's\n execution. 'on_init' will be called once, right after variables'\n initialization and before any computation takes place. 'on_update'\n will be called at the beginning of every iteration of the algorithm.\n 'on_end' will be called once, right before the algorithm terminates\n its execution and after all computations are done. 'on_move' will be\n called whenever greedy school redistricting moves are made, right\n after they are applied. Each callback will then be passed\n corresponding arguments, regarding the status of execution. More\n specifically, 'on_init', 'on_update', and 'on_end' will have access\n to (i) the list of all `optimization.entity_nodes.School` instances,\n (ii) the list of all `optimization.entity_nodes.District` instances,\n and (iii) an updated `optimization.lookup.Lookup` instance. On the\n other hand, 'on_move' will only be passed (i) the current\n iteration's index, and (ii) the list of all moves that were\n performed.\n\n Returns:\n float: Minimal spatial inequality index achieved for the specified\n state.\n \"\"\"\n # Instantiate all schools\n school_ids_in_state = get_schools_in_state(target_state, school_assignment)\n schools = [School(\n school_id,\n get_school_total_students(school_id, aug_school_info),\n get_school_total_funding(school_id, aug_school_info)\n ) for school_id in school_ids_in_state]\n\n # Instantiate all districts\n district_ids_in_state = get_districts_in_state(target_state, school_assignment)\n districts = [District(\n district_id\n ) for district_id in district_ids_in_state]\n\n # Instantiate lookup\n lookup = Lookup(schools, districts)\n\n # Populate schools' neighbors\n for school in schools:\n school_id = school.get_id()\n neighbor_ids = get_neighbouring_schools(school_id, aug_school_info)\n for neighbor_id in neighbor_ids:\n neighbor = lookup.get_school_by_id(neighbor_id)\n school.add_neighbor(neighbor)\n\n # Populate school districts\n for district in districts:\n district_id = district.get_id()\n school_ids = get_schools_in_district(district_id, school_assignment)\n for school_id in school_ids:\n school = lookup.get_school_by_id(school_id)\n district.add_school(school)\n lookup.assign_school_to_district_by_id(school_id, district_id)\n\n # Calculate state-wide funding per student\n state_total_students = 0\n state_total_funding = 0\n for district in districts:\n state_total_students += district.get_total_students()\n try:\n int(district.get_total_funding())\n except Exception as exception:\n print(district)\n state_total_funding += district.get_total_funding()\n state_funding_per_student = state_total_funding / state_total_students\n\n # Auxiliary function for funding calculation\n def abs_diff_from_state(district):\n district_funding_per_student = district.get_total_funding() / district.get_total_students()\n return abs(district_funding_per_student - state_funding_per_student)\n\n # Initialize (max) heap to extract districts that deviate from state average\n heap = LazyHeap(\n item_id=lambda x: x.get_id(),\n gt=lambda x,y: abs_diff_from_state(x) > abs_diff_from_state(y),\n max_elems=2*len(districts)\n )\n\n # Populate heap with all districts\n for district in districts:\n heap.push(district)\n\n # Initalize holdout queue\n holdout_queue = HoldoutQueue(\n get_item_tag=lambda x: lookup.get_neighboorhood_changes_by_district_id(x.get_id()),\n is_valid=lambda x: lookup.get_neighboorhood_changes_by_district_id(x.get_data().get_id()) > x.get_tag()\n )\n \n # Auxiliary function to execute provided callbacks\n def execute_callback(label, **kwargs):\n callback = callbacks.get(label, None)\n if callback is None:\n pass\n else:\n callback(**kwargs)\n \n # Main algorithm\n is_running = True\n is_retrying = False\n iteration_idx = 0\n \n # Initialize EarlyStopper\n early_stopper = EarlyStopper(\n early_stopper_it,\n tolerance=early_stopper_tol\n )\n # Initialize greedy parameters\n greedy_params = {\n \"min_schools_per_district\": min_schools_per_district,\n \"max_schools_per_district\": max_schools_per_district\n }\n \n # Execute on_init callback\n execute_callback(\n \"on_init\",\n schools=schools,\n districts=districts,\n lookup=lookup\n )\n \n # Start greedy algorithm\n logging.info(\"Starting greedy algorithm.\")\n while is_running is True:\n # To always execute at start of iteration\n logging.info(\"-\"*30)\n iteration_idx += 1\n \n # Execute on_update callback\n execute_callback(\n \"on_update\",\n schools=schools,\n districts=districts,\n lookup=lookup\n )\n \n try:\n # Try to pop district from queue\n logging.info(\"Popping district from heap.\")\n district = heap.pop()\n logging.debug(f\"District popped: '{district.get_id()}'\")\n # Reset retry flag\n is_retrying = False\n # Greedily select districts with which to equalize funding\n logging.info(\"Calculating greedy moves.\")\n greedy_moves = greedily_pick_redistricting_moves(district, lookup, **greedy_params)\n logging.debug(f\"Number of possible moves: {len(greedy_moves)}\")\n logging.debug(f\"Possible moves' list: {greedy_moves}\")\n # Handle all existing greedy moves\n if len(greedy_moves) == 0:\n logging.info(\"No moves available.\")\n # No moves are available, add district to holdout queue\n logging.info(\"Moving district to holdout queue.\")\n holdout_queue.enqueue(district)\n logging.debug(f\"Moved district '{district.get_id()}' to holdout queue.\")\n else:\n logging.info(\"At least one available move.\")\n # If some moves are available, perform all\n logging.info(\"Redistricting schools.\")\n apply_redistricting_moves(greedy_moves, lookup, heap)\n execute_callback(\"on_move\", iteration_idx=iteration_idx, moves=greedy_moves)\n # Push district back into heap (or eliminate it if it has no more schools)\n if len(district.get_schools()) > 0:\n logging.info(\"Pushing district back into heap.\")\n heap.push(district)\n logging.debug(f\"Pushed district '{district.get_id()}' to heap.\")\n else:\n logging.info(\"Disposing of district.\")\n districts.remove(district)\n logging.debug(f\"Disposed of district '{district.get_id()}'\")\n # Update inequality calculation\n current_inequality = calculate_inequality(districts, lookup)\n logging.info(f\"Current inequality: {current_inequality}\")\n early_stopper.update(current_inequality)\n except IndexError:\n logging.info(\"Could not pop district from heap.\")\n # First time retrying, attempt to refill heap (and retry algorithm)\n if is_retrying is False:\n logging.info(\"Flushing holdout queue into heap.\")\n refill_heap(heap, holdout_queue)\n logging.info(\"Retrying algorithm.\")\n is_retrying = True\n # The heap has no elements even after refill, stop algorithm\n else:\n logging.info(\"No available districts after retry... Terminating.\")\n is_running = False\n except StopIteration:\n # EarlyStopper has not detected any inequality improvement\n logging.info(\"No improvement detected for overall inequality.\")\n is_running = False\n logging.info(\"Greedy algorithm done.\") \n # Execute on_end callback\n execute_callback(\n \"on_end\",\n schools=schools,\n districts=districts,\n lookup=lookup\n )\n # retun final inequality value\n return calculate_inequality(districts, lookup)\n\ndef get_expectable_run_for_state(target_state, aug_school_info, school_assignment, n_runs, greedy_params, early_stopper_params):\n \"\"\"\n Performs multiple runs of the greedy partitioning algorithm for a given\n state, to get an 'expectation' of its performance and measure uncertainty\n associated with the spatial inequality index's minimization process. It then\n extracts a single 'expectable' run (alongside benchmarking statistics) and\n returns them.\n\n NOTE: Parallelizing iterations over the same state would be possible to\n speedup this benchmarking process.\n\n Args:\n target_state (str): Capitalized full state name (e.g., 'Alabama').\n aug_school_info (pandas.DataFrame): Target augmented school information\n (as formatted by `auxiliary.data_handler.DataHandler`).\n school_assignment (pandas.DataFrame): Target school assignment (as\n formatted by `auxiliary.data_handler.DataHandler`).\n n_runs (int): Number of runs to perform for the greedy partitioning\n algorithm.\n greedy_params (kwargs): Keyword arguments for the greedy partitioning\n algorithm's parameterization. Two values can be specified through\n this parameter, namely (i) 'min_schools_per_district' and (ii)\n 'max_schools_per_district'. These respectively refer to the minimum\n and maximum number of schools to preserve in each district, upon\n redistricting.\n early_stopper_params (kwargs): Keyword arguments for the early stopper's\n parameterization. Two values can be specified through this\n parameter, namely (i) 'early_stopper_it' and (ii)\n 'early_stopper_tol'. These respectively refer to the number of\n maximum iterations allowed without noticeable improvements to\n inequality and the tolerance for floating point comparisons on\n inequality.\n\n Returns:\n tuple: Triplet containing (i) the spatial inequality index's standard\n deviation, (ii) the spatial inequality index's mean, and (iii) an\n `optimization.run_metrics.RunMetrics` instance with all information\n on the algorithm's average run (i.e., the run whose spatial\n inequality index came closest to the average).\n \"\"\"\n # Initialize container variables\n inequalities = []\n metrics = []\n # Progress-related\n start_time = datetime.now()\n start_timestamp = time()\n for i in range(n_runs):\n # Print progress\n try:\n total_time_estimate = lambda: n_runs * ((time() - start_timestamp) / i)\n eta = (start_time + timedelta(seconds=total_time_estimate())).strftime(\"%Y-%m-%d %H:%M:%S\")\n print(f\"State: {target_state}\\nProgress: {i+1}/{n_runs}\\nETA: {eta}\")\n except Exception:\n print(f\"State: {target_state}\\nProgress: {i+1}/{n_runs}\\nETA: ???\")\n # Initialize metrics\n cur_metrics = RunMetrics()\n callbacks = {\n \"on_init\": cur_metrics.on_init,\n \"on_update\": cur_metrics.on_update,\n \"on_move\": cur_metrics.on_move,\n \"on_end\": cur_metrics.on_end\n }\n # Single algorithm run\n cur_inequality = greedy_algo(\n target_state,\n aug_school_info,\n school_assignment,\n **greedy_params,\n **early_stopper_params,\n callbacks=callbacks\n )\n # Add to lists & clear screen\n metrics.append(cur_metrics)\n inequalities.append(cur_inequality)\n # Clear print with status\n print(f\"State: {target_state}\\nProgress: Done!\")\n # Select expectable run\n avg_inequality = np.mean(inequalities)\n average_metric_idx = next(\n idx for idx in np.argsort(inequalities) if inequalities[idx] >= avg_inequality\n )\n # Return mean, standard deviation and a representative metric\n return np.mean(inequalities), np.std(inequalities), metrics[average_metric_idx]"} {"blob_id": "323d6a7fec566957e2cf4b0ab225c0f57ed09843", "repo_name": "jordanaron22/Weighted-Voting-Comps-Winter-Spring-2018", "path": "/4Search.py", "length_bytes": 4499, "score": 3.9375, "int_score": 4, "content": "def main():\r\n\r\n #These lists will have the final answers in them\r\n winning_combos = []\r\n winning_combos_power =[]\r\n\r\n def summary():\r\n print(\"The possible winning combinations are:\")\r\n print(winning_combos)\r\n print(\"\")\r\n print(\"There are \", len(winning_combos_power), \" different power distributions\")\r\n print(\"\")\r\n print(\"The possible power distributions are: \")\r\n print(winning_combos_power)\r\n\r\n #Calculates power from list of winning combinations\r\n def power_calc(local_winning_combo):\r\n #Used later to tally\r\n list_a = []\r\n list_b = []\r\n list_c = []\r\n list_d = []\r\n\r\n #iterates through each winning coalition\r\n for combo in local_winning_combo:\r\n #iterates through each member of a winning coalition\r\n for i in range(0, len(combo)):\r\n #iteratively removes each member and checks if winning coalition goes to losing\r\n check = combo.replace(combo[i], \"\")\r\n if check not in local_winning_combo:\r\n if combo[i] == \"A\":\r\n list_a.append(1)\r\n elif combo[i] == \"B\":\r\n list_b.append(1)\r\n elif combo[i] == \"C\":\r\n list_c.append(1)\r\n else:\r\n list_d.append(1)\r\n\r\n denom = len(list_a) + len(list_b) + len(list_c) + len(list_d)\r\n power_a = len(list_a)/denom\r\n power_b = len(list_b)/denom\r\n power_c = len(list_c)/denom\r\n power_d = len(list_d)/denom\r\n\r\n power_list = [power_a, power_b, power_c, power_d]\r\n return power_list\r\n\r\n #Calculates every possible combination of values for ABCD\r\n for a in range(1, 101):\r\n for b in range(0, 100 - a + 1):\r\n for c in range(0, 100 - a - b + 1):\r\n for d in range(0,100 - a - b - c +1):\r\n\r\n #Only look at valid combinations\r\n if a + b + c + d == 100 and a >= b >= c >= d:\r\n #Every possible threshold value\r\n for i in range(1, 100):\r\n local_winning_combo = []\r\n #Checks if coalition is a winning one\r\n if a + b + c + d > i:\r\n local_winning_combo.append(\"ABCD\")\r\n if a + b + c > i:\r\n local_winning_combo.append(\"ABC\")\r\n if a + b + d > i:\r\n local_winning_combo.append(\"ABD\")\r\n if a + c + d > i:\r\n local_winning_combo.append(\"ACD\")\r\n if b + c + d > i:\r\n local_winning_combo.append(\"BCD\")\r\n if a + b > i:\r\n local_winning_combo.append(\"AB\")\r\n if a + c > i:\r\n local_winning_combo.append(\"AC\")\r\n if a + d > i:\r\n local_winning_combo.append(\"AD\")\r\n if b + c > i:\r\n local_winning_combo.append(\"BC\")\r\n if b + d > i:\r\n local_winning_combo.append(\"BD\")\r\n if c + d > i:\r\n local_winning_combo.append(\"CD\")\r\n if a > i:\r\n local_winning_combo.append(\"A\")\r\n if b > i:\r\n local_winning_combo.append(\"B\")\r\n if c > i:\r\n local_winning_combo.append(\"C\")\r\n if d > i:\r\n local_winning_combo.append(\"D\")\r\n\r\n\r\n\r\n #adds to list of winning coalitions\r\n if not local_winning_combo in winning_combos:\r\n winning_combos.append(local_winning_combo)\r\n\r\n #adds to list of power distributions\r\n power_dist = power_calc(local_winning_combo)\r\n if power_dist not in winning_combos_power:\r\n winning_combos_power.append(power_dist)\r\n\r\n\r\n summary()\r\n\r\nmain()\r\n"} {"blob_id": "f47e0a404ee9c531f82b657c0cc4ecc987e9279c", "repo_name": "2flcastro/python-exercises", "path": "/solutions/2flcastro/intermediate/smallest_common_multiple.py", "length_bytes": 2773, "score": 4.375, "int_score": 4, "content": "# ----------------------------------\n# Smallest Commom Multiple\n# ----------------------------------\n# Find the smallest common multiple of the provided parameters that can be\n# evenly divided by both, as well as by all sequential numbers in the range\n# between these parameters.\n#\n# The range will be a list of two numbers that will not necessarily be in\n# numerical order.\n#\n# e.g. for 1 and 3, find the lowest common multiple of both 1 and 3 that is\n# evenly divisible by all numbers BETWEEN 1 and 3.\n#\n# Helpful Links:\n# - https://www.mathsisfun.com/least-common-multiple.html\n# - https://www.artofproblemsolving.com/wiki/index.php/Least_common_multiple\n# ----------------------------------\n\nimport unittest\n\n# Using a while loop to test multiples of the largest number in list,\n# incrementing the largest value on itself until it reaches a value all numbers\n# in the range can evenly divide into.\ndef smallest_common(lst):\n lst.sort()\n largest_num = lst[len(lst) - 1]\n scm = largest_num\n while True:\n for number in range(lst[0], largest_num + 1):\n if scm % number != 0:\n scm += largest_num\n break\n else:\n # break out of the while-loop if scm found\n break\n return scm\n\n\n\n# There is another formula for finding the SCM of a pair of numbers:\n# LCM(a, b) = a * b / GCD(a, b)\n# You first need to find the GCD (greatest common divisor), which is done Using\n# the Euclidean Algorithm (euclidean_gcd() function).\ndef smallest_common_2(lst):\n def euclidean_gcd(a, b):\n if b == 0:\n return a\n else:\n return euclidean_gcd(b, a%b)\n\n lst.sort()\n scm = lst[0]\n for i in range(lst[0] + 1, lst[len(lst) - 1] + 1):\n scm = scm * i / euclidean_gcd(scm, i)\n return scm\n\n\n# ----------------------------------\n# Unit Tests\n# ----------------------------------\nclass Test_Smallest_Common(unittest.TestCase):\n def test_1(self):\n self.assertEqual(smallest_common([1, 5]), 60)\n\n def test_2(self):\n self.assertEqual(smallest_common([5, 1]), 60)\n\n def test_3(self):\n self.assertEqual(smallest_common([1, 13]), 360360)\n\n def test_4(self):\n self.assertEqual(smallest_common([23, 18]), 6056820)\n\n\nclass Test_Smallest_Common_2(unittest.TestCase):\n def test_1(self):\n self.assertEqual(smallest_common_2([1, 5]), 60)\n\n def test_2(self):\n self.assertEqual(smallest_common_2([5, 1]), 60)\n\n def test_3(self):\n self.assertEqual(smallest_common_2([1, 13]), 360360)\n\n def test_4(self):\n self.assertEqual(smallest_common_2([23, 18]), 6056820)\n\n\n# ----------------------------------\n# Run Tests\n# ----------------------------------\nif __name__ == \"__main__\":\n unittest.main()\n"} {"blob_id": "ba4c47cae4c90f8d2f7353dcca53cbee5039049e", "repo_name": "ghydric/05-Python-Programming", "path": "/Class_Practice_Exercises/Serialization/hangman_exercise.py", "length_bytes": 11429, "score": 4.59375, "int_score": 5, "content": "\"\"\"\nTask:\n Your task is to implement the Hangman game in Python.\n\u200b\nProgram Specifications:\n 1) Output a brief description of the game of hangman and how to play\n 2) Ask the user to enter the word or phrase that will be guessed (have a friend enter the phrase \n for you if you want to be surprised)\n 3) Output the appropriate number of dashes and spaces to represent the phrase (make sure it\u2019s clear \n how many letters are in each word and how many words there are)\n 4) Continuously read guesses of a letter from the user and fill in the corresponding blanks if the \n letter is in the word, otherwise report that the user has made an incorrect guess.\n 5) Each turn you will display the phrase as dashes but with any already guessed letters filled in, \n as well as which letters have been incorrectly guessed so far and how many guesses the user has remaining.\n 6) Your program should allow the user to make a total of k=6 guesses.\n\u200b\nAssignment Notes:\nIf the letter has already been guessed, output a message to the player and ask for input again.\nIf the guess entered is not an alphabetic letter, output a message and ask for input again.\n\u200b\nIf the letter is present in the word to be guessed, fill in the blanks appropriately with this particular letter. \nIf the complete name has been guessed, the game is over - player wins the game. Output a message telling the \nplayer they have won and quit the game.\n\u200b\nIf the letter/digit is not present in the word to be guessed, give a message to the player indicating that the \nguess is incorrect and remaining number of chances is one less. If remaining number of chances is 0 (zero), \nthe game is over - player loses the game. Output a message that they have lost and what the correct word was. Quit the game.\n\u200b\nBonus:\n You can do one or both of the following:\n\u200b\n 1) Using a file:\n Instead of asking for user input for the word, make a word bank in a file named hangman_words.txt. \n Read in the contents of the file and choose a word at random.\n\u200b\n 2) Forever alone option:\n You enter the word (or it is randomly chosen from the word bank) and have the computer try to guess the letters.\n\u200b\n 3) Add some more functionality: \n - Persist user profiles with scores\n - Prompt for which user is playing\n - Ask if the user wants to play a set of games\n - Build a leader board\n \n Have fun, get creative, and demonstrate what you've come up with.\n\"\"\"\n### Import Libraries\nimport random\nfrom os import path\n\n### Define Global CONSTANTS\n# file path to word bank\nWORD_BANK_PATH = r\"C:\\Users\\student\\Documents\\myGitStuff\\05-Python-Programming\\Class_Practice_Exercises\\Serialization\\hangman_words.txt\"\n# list of available choices\nALPHABET = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']\n\n### Define Global Variables\n\n### Start of Functions\n#-----------------------#\n# function that creates the hangman_words.txt file with a list of words\ndef create_word_bank(filepath):\n # Open a file named hangman_words.txt\n f = open(filepath, 'w')\n # list of words to become the word bank\n words = ['DISTRIBUTOR ROTOR','PRESSURE PLATE','THROW-OUT BEARING','LIMITED-SLIP DIFFERENTIAL','INNER TIE-ROD END']\n # write each of the words in list to the file\n for word in words:\n f.write(f\"{word}\\n\")\n # close the file\n f.close()\n\n# function that reads a text file (input as argument) and returns the word list\ndef get_word_bank(filepath):\n # open file at filepath\n f = open(filepath, 'r')\n # create empty words list\n words = [] \n # loop through the file reading each line,\n # then append that line to the words list\n for line in f.readlines():\n words.append(line.rstrip('\\n'))\n # close the file\n f.close()\n #return the list\n return words\n\n# function that returns an underscore version of a word.\n# word and underscore version are passed in as arguments.\n# this word created as underscores is what is to be shown to user to guess.\ndef make_spooky_word(chosen, spooky):\n \n # loop through each letter in input word\n for letter in chosen:\n # if the letter is a dash or a space,\n # output the letter as it is with a space added\n if letter == '-' or letter == ' ':\n spooky += (f'{letter} ')\n\n # output the letter as an underscore\n else:\n spooky += (f'_ ')\n # strip the last space off the end of the encoded word\n spooky = spooky.rstrip(' ')\n # return the encoded word\n return spooky\n\n# function that returns a spaced version of the chosen word.\n# chosen word is passed in as an argument.\n# update_spooky_word uses this version for index reference to update the spooky word.\ndef make_spaced_chosen_word(chosen):\n # initialize spaced version of chosen word to null string\n spaced_chosen = ''\n # loop through each letter of chosen word and add letter\n # with a space to spaced version\n for letter in chosen:\n spaced_chosen += f'{letter} '\n # remove the final space off of spaced version\n spaced_chosen = spaced_chosen.rstrip(' ')\n # return the spaced version of chosen word\n return spaced_chosen\n\n# function that updates the spooky word shown to player to guess\ndef update_spooky_word(guess, spooky, chosen):\n # make spooky a list to modify based on index\n spooky_list = list(spooky)\n # loop through each letter in chosen word\n for index, value in enumerate(chosen):\n # skip letters that are spaces\n if chosen[index] == ' ':\n continue\n # if guess matches letter,\n # then replace the same index of spooky word with guess\n elif guess == chosen[index]:\n spooky_list[index] = guess\n # otherwise skip the letter\n else:\n continue\n # change spooky list back into string\n spooky = \"\".join(spooky_list)\n print(spooky)\n # return spooky word\n return spooky\n\n# function that displays the game\ndef display_game(menu, spooky = '', incorrect = ''):\n \n if menu == 'launch':\n print(' HANGMAN')\n print('----------------------------------------------')\n print('Guess a letter of the alphabet to see if it')\n print('is in the below mystery word that was chosen')\n print('randomly. If your guess is not in the mystery')\n print('word, you are that much closer to being hung!')\n print('Guess incorrectly too many times and you lose!')\n print('To win, guess all the letters in the mystery')\n print('word without getting hung!')\n print('')\n print('To play: Enter \"1\"')\n print('To exit: Enter \"2\"')\n while True:\n try:\n choice = input('Choice: ')\n if choice != '1' and choice != '2':\n print('Invalid choice.')\n continue\n else:\n break\n except:\n continue\n if choice == '1':\n return True\n else:\n return False\n\n elif menu == 'game_play':\n print(' HANGMAN')\n print('----------------------------------------------')\n print('')\n print(f' {spooky}')\n print('')\n print(f'Incorrect Guesses: {str(incorrect).strip(\"[]\")}')\n print('----------------------------------------------')\n\n elif menu == 'won':\n print(' HANGMAN')\n print('----------------------------------------------')\n print('')\n print(f' {spooky}')\n print('')\n print('YOU WIN!!')\n print('')\n \n elif menu == 'lost':\n print(' HANGMAN')\n print('----------------------------------------------')\n print('')\n print(' The mystery word was:')\n print(f' {spooky}')\n print('')\n print('YOU DUN GOT HANGED!!')\n print('')\n\n# function that gets the player's guess and validates it is\n# a single alphabetic character, then returns the uppercase version\ndef get_player_guess():\n # get a guess from the player\n guess = input('Guess a single letter: ')\n # loop while the guess is not a character\n while guess.isalpha() == False:\n print('Guess must be a letter of the alphabet!')\n guess = input('Guess a single letter: ')\n # loop while length of guess is not equal to 1\n while len(guess) != 1:\n guess = input('Too many letters, enter a single letter: ')\n # return the uppercase version of the guess\n return guess.upper()\n\n# function that takes the player's guess as input and checks\n# whether the guess is in the mystery word\ndef check_guess_correct(guess, chosen):\n if guess in chosen:\n return True\n else:\n return False\n\n# main function\ndef main():\n # play game until player chooses to exit at launch menu\n while True:\n # display the launch menu for the game\n play = display_game(menu = 'launch')\n \n # exit the game if player chose not to play\n if not play:\n exit()\n \n # check if the word bank file exists already\n # if not, create the word bank text file\n if not path.exists(WORD_BANK_PATH):\n try:\n create_word_bank(WORD_BANK_PATH)\n except:\n print('An error occured creating the wordbank, exiting')\n exit()\n \n # try to retrieve the word bank\n try:\n word_bank = get_word_bank(WORD_BANK_PATH)\n except:\n print('An error occured retrieving the wordbank, exiting')\n exit()\n \n # let computer choose a word from the word bank\n chosen_word = random.choice(word_bank)\n \n # create spaced version of chosen_word\n spaced_chosen_word = make_spaced_chosen_word(chosen_word)\n \n # initialize spooky_word\n spooky_word = ''\n \n # create spooky version (letters replaced with underscores) of chosen word\n spooky_word = make_spooky_word(chosen_word, spooky_word)\n\n # create empty list of incorrect guesses\n list_inc_guesses = []\n\n # testing\n #print(chosen_word)\n #print(spaced_chosen_word)\n #print(spooky_word)\n\n # while the spooky word contains at least 1 underscore or\n # the length of the incorrect guesses becomes greater than 7\n # loop through game play\n while '_' in spooky_word and len(list_inc_guesses) <= 7:\n \n display_game(menu = 'game_play', spooky = spooky_word, incorrect = list_inc_guesses)\n user_input = get_player_guess()\n valid = check_guess_correct(user_input, chosen_word)\n if valid:\n spooky_word = update_spooky_word(user_input, spooky_word, spaced_chosen_word)\n elif user_input in list_inc_guesses:\n print('Already guessed that.')\n continue\n else:\n list_inc_guesses += user_input\n \n if len(list_inc_guesses) == 8:\n display_game(menu = 'lost', spooky = spaced_chosen_word)\n input('Press enter')\n \n else:\n display_game(menu = 'won', spooky = spooky_word)\n input('Press enter')\n\nmain()"} {"blob_id": "37f69158f54c60244fff0b3979e6d28c9e8b7020", "repo_name": "akimi-yano/algorithm-practice", "path": "/lc/600.Non-negativeIntegersWithoutCon.py", "length_bytes": 2111, "score": 3.6875, "int_score": 4, "content": "# 600. Non-negative Integers without Consecutive Ones\n# Hard\n\n# 828\n\n# 96\n\n# Add to List\n\n# Share\n# Given a positive integer n, return the number of the integers in the range [0, n] whose binary representations do not contain consecutive ones.\n\n \n\n# Example 1:\n\n# Input: n = 5\n# Output: 5\n# Explanation:\n# Here are the non-negative integers <= 5 with their corresponding binary representations:\n# 0 : 0\n# 1 : 1\n# 2 : 10\n# 3 : 11\n# 4 : 100\n# 5 : 101\n# Among them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule. \n# Example 2:\n\n# Input: n = 1\n# Output: 2\n# Example 3:\n\n# Input: n = 2\n# Output: 3\n \n\n# Constraints:\n\n# 1 <= n <= 109\n\n# This solution works:\n\nclass Solution:\n def findIntegers(self, n: int) -> int:\n highest_bit = 1\n while highest_bit << 1 <= n:\n highest_bit <<= 1\n \n '''\n n = 8\n 1 0 0 0\n 1 0 0...\n 1 0 1... x\n 0 0...\n 0 1...\n \n n = 10\n 1 0 1 0\n \n 1 0 0...\n 1 0 1... o\n 1 0 0 0 o\n 1 0 0 1 ?\n \n \n 95\n 90 o\n ...\n 95 o\n 96 x\n '''\n @lru_cache(None)\n # prev = the last bit value chosen\n def helper(prev, bit):\n nonlocal n\n # base case\n if not bit:\n return 1\n \n if prev:\n if bit & n:\n return helper2(0, bit >> 1)\n else:\n return helper(0, bit >> 1)\n else:\n if bit & n:\n return helper(1, bit >> 1) + helper2(0, bit >> 1)\n else:\n return helper(0, bit >> 1)\n \n \n @lru_cache(None)\n def helper2(prev, bit):\n if not bit:\n return 1\n if prev:\n return helper2(0, bit >> 1)\n else:\n return helper2(1, bit >> 1) + helper2(0, bit >> 1)\n \n return helper(0, highest_bit)"} {"blob_id": "437b204b3e9898dd0335703657f81c8a14a21854", "repo_name": "omritz/Checkers-Board-Search", "path": "/main.py", "length_bytes": 20155, "score": 3.828125, "int_score": 4, "content": "import random as random\r\nimport copy as copy\r\nimport math\r\nimport numpy as np\r\nimport sys\r\n\r\n# This script contains 5 Algorithms to search a path from a Starting board, \r\n# according to the rules of Checkers, to a goal board.\r\n# you can simply insert the boards under this lines or while runing the main.\r\n\r\n\r\n\r\nstartBoard = [[1,0,1,0,1,0],\r\n [0,0,0,1,0,1],\r\n [0,0,0,0,0,0],\r\n [0,0,0,0,0,0],\r\n [1,0,0,0,0,0],\r\n [0,0,0,0,0,0]]\r\n\r\ngoalBoard = [[1,0,1,0,1,0],\r\n [0,0,0,1,0,0],\r\n [0,0,0,0,1,0],\r\n [0,0,0,0,0,0],\r\n [0,0,0,0,0,0],\r\n [0,0,0,0,0,0]]\r\n\r\n\r\ndef makeBoard(b):\r\n ''' Preparing The board for printing '''\r\n board = []\r\n for r in range(7):\r\n brow = []\r\n for c in range(7):\r\n if r == c == 0:\r\n brow.append('# ') \r\n elif r == 0:\r\n brow.append(str(c))\r\n elif c == 0:\r\n brow.append(str(r)+':')\r\n else:\r\n brow.append(' ')\r\n board.append(brow)\r\n for i in range(6):\r\n for j in range(6):\r\n if b[i][j] == 1 or b[i][j] == 2 :\r\n board[i+1][j+1]='*'\r\n return board\r\n\r\ndef printBoard(b):\r\n ''' Print each row of the board '''\r\n for row in b:\r\n print (' '.join(row))\r\n\r\ndef initBoard(b1, b2):\r\n '''Initialized the board for the huristic score'''\r\n tempBoard = [[0 for x in range(6)] for y in range(6)] \r\n for i in range(6):\r\n for j in range(6):\r\n if b1[i][j] == b2[i][j] == 1:\r\n tempBoard[i][j] = 2 # thers is one and it should be there\r\n if b1[i][j] == 1 and b2[i][j] == 0:\r\n tempBoard[i][j] = 1 # thers is one and it shouldnt be there\r\n if b1[i][j] == 0 and b2[i][j] == 1:\r\n tempBoard[i][j] = 3 # there isnt one and it should be there\r\n return tempBoard\r\n\r\ndef printMyWay(listOfBoards,sBoard, gBoard):\r\n '''Print the final path '''\r\n c = 0\r\n for b in listOfBoards:\r\n c += 1\r\n output = \"Board \" + str(c)\r\n if (np.array_equal(b, sBoard)):\r\n print(output + \" (starting position):\")\r\n elif (np.array_equal(b, gBoard)):\r\n print (output + \" (goal position):\")\r\n else:\r\n print(output+ \":\")\r\n printBoard(makeBoard(b))\r\n print (\"-----\") \r\n\r\ndef printMyWayDetail(listOfBoards,sBoard, gBoard):\r\n '''Print the final path with details '''\r\n c = 0\r\n for b in listOfBoards:\r\n c += 1\r\n output = \"Board \" + str(c) + \" heuristic value = \" + str(b[1])\r\n if (np.array_equal(b[0], sBoard)):\r\n print(output + \" (starting position):\")\r\n elif (np.array_equal(b[0], gBoard)):\r\n print (output + \" (goal position):\")\r\n else:\r\n print(output+ \":\")\r\n printBoard(makeBoard(b[0]))\r\n print (\"-----\") \r\n\r\ndef printBag(bag, counter, key):\r\n ''' Print each bag in locl beam search '''\r\n c = 0\r\n for b in bag:\r\n c += 1\r\n output = \"Board \" + key + \" in Bag, level \" + str(counter)\r\n print(output+ \":\")\r\n printBoard(makeBoard(b))\r\n print (\"-----\")\r\n\r\n\r\ndef score(t):\r\n ''' Huristic score for each board '''\r\n ones = []\r\n threes = []\r\n twos = 0\r\n target = 0\r\n tempScore = 0\r\n for i in range(6):\r\n for j in range(6):\r\n if goalBoard[i][j] == 1:\r\n target += 1\r\n for i in range(6):\r\n for j in range(6):\r\n if t[i][j] == 1:\r\n ones.append([i,j])\r\n if t[i][j] == 3:\r\n threes.append([i,j])\r\n if t[i][j] == 2:\r\n twos +=1 \r\n if len(ones) == len(threes) != 0:\r\n for i in range(len(ones)):\r\n if (threes[i][0]<=ones[i][0]):\r\n return 50\r\n tempScore += (threes[i][0] - ones[i][0])\r\n elif len(ones) == len(threes) == 0:\r\n if twos == target:\r\n return 0\r\n else:\r\n return 50 \r\n else:\r\n if not ones:\r\n return 50\r\n if len(ones) < len(threes):\r\n return 50 \r\n if(len(threes) == 0):\r\n for i in range(len(ones)): \r\n tempScore += (6 - ones[i][0])\r\n else: \r\n for i in range(len(ones)-len(threes), len(ones)): \r\n tempScore += (6 - ones[i][0])\r\n if len(ones) < len(threes):\r\n return 50 \r\n for i in range(len(threes)):\r\n if (threes[i][0]<=ones[i][0]):\r\n return 50 \r\n tempScore += (threes[i][0] - ones[i][0])\r\n \r\n return tempScore\r\n\r\ndef isLegal(i, j, temp): \r\n ''' Check if step is legal '''\r\n if i == 6:\r\n return True\r\n if j >= 0 and j < 6 and i < 6 and temp[i][j] != 1:\r\n return True\r\n else:\r\n return False\r\n\r\n\r\ndef makeMove(temp, current, restart):\r\n ''' Get the next state with random steps '''\r\n noMove = 0 \r\n x = 0\r\n if(restart != 0):\r\n x = random.random()\r\n if(current[0] != [0,0]): \r\n if current[0][1] == 5:\r\n current[0][1] = 0\r\n current[0][0] += 1\r\n else:\r\n current[0][1] += 1\r\n for i in range(current[0][0], 6): \r\n for j in range(current[0][1],6):\r\n current[0][1] = 0\r\n if temp[i][j] == 1:\r\n if i == 5:\r\n temp[i][j] = 0\r\n return temp \r\n if(isLegal(i+1, j+1, temp) and temp[i+1][j+1] != 2 and x <= 0.5 ):\r\n current.pop()\r\n current.append([i,j])\r\n temp[i][j] = 0\r\n if(temp[i+1][j+1] != 3):\r\n temp[i+1][j+1] = 1\r\n else:\r\n temp[i+1][j+1] = 2 \r\n return temp\r\n elif(isLegal(i+1, j-1, temp) and temp[i+1][j-1] != 2): \r\n temp[i][j] = 0\r\n current.pop()\r\n current.append([i,j])\r\n if(temp[i+1][j-1] != 3):\r\n temp[i+1][j-1] = 1\r\n else:\r\n temp[i+1][j-1] = 2 \r\n return temp\r\n elif isLegal(i+1, j+1, temp) and temp[i+1][j+1] == 2 and x <= 0.5:\r\n if isLegal(i+2, j, temp):\r\n current.pop()\r\n current.append([i,j]) \r\n if i == 4:\r\n pass\r\n elif(temp[i+2][j] != 3 != 2):\r\n temp[i+2][j] = 1\r\n else:\r\n temp[i+2][j] = 2\r\n temp[i+1][j+1] = 0 \r\n return temp\r\n elif isLegal(i+2, j+2, temp):\r\n current.pop()\r\n current.append([i,j])\r\n if i == 4:\r\n pass\r\n elif(temp[i+2][j+2] != 3 != 2):\r\n temp[i+2][j+2] = 1\r\n else:\r\n temp[i+2][j+2] = 2\r\n temp[i+1][j+1] = 0 \r\n return temp\r\n elif isLegal(i+1, j-1, temp) and temp[i+1][j-1] == 2:\r\n if isLegal(i+2, j, temp):\r\n current.pop()\r\n current.append([i,j])\r\n if i == 4:\r\n pass\r\n elif(temp[i+2][j] != 3 != 2):\r\n temp[i+2][j] = 1\r\n else:\r\n temp[i+2][j] = 2\r\n temp[i+1][j-1] = 0 \r\n return temp\r\n elif isLegal(i+2, j-2, temp):\r\n current.pop()\r\n current.append([i,j])\r\n if i == 4:\r\n pass\r\n elif(temp[i+2][j-2] != 3 != 2):\r\n temp[i+2][j-2] = 1\r\n else:\r\n temp[i+2][j-2] = 2\r\n temp[i+1][j-1] = 0 \r\n return temp \r\n \r\n current.pop()\r\n current.append([5,5]) \r\n return None\r\n\r\ndef hillClimbing(b1, b2):\r\n ''' Hill climbing search algorithm '''\r\n restartCounter = 0\r\n boards = []\r\n minS=50\r\n while restartCounter != 5 and minS !=0:\r\n board = initBoard(b1, b2)\r\n temp = copy.deepcopy(board)\r\n boards.append(copy.deepcopy(board))\r\n minS = score(board)\r\n S = 50\r\n while minS != 0:\r\n currnetCheck = [[0,0]]\r\n while S >= minS and currnetCheck != [[5,5]]:\r\n temp = makeMove(copy.deepcopy(board), currnetCheck, restartCounter)\r\n if not temp:\r\n S = 50\r\n else: \r\n S = score(temp)\r\n if S == 50:\r\n restartCounter +=1\r\n break\r\n if restartCounter == 5:\r\n break\r\n if (S < minS):\r\n board = copy.deepcopy(temp)\r\n minS = S\r\n if minS == 0:\r\n boards.append(copy.deepcopy(board)) \r\n break\r\n else:\r\n boards.append(copy.deepcopy(board)) \r\n \r\n printMyWay(boards,initBoard(b1, b2),initBoard(b2, b2)) \r\n if minS != 0:\r\n print(\"No path Found\") \r\n\r\n \r\n\r\ndef SA(b1, b2, isDetail):\r\n ''' Simulated annealing search algorithm '''\r\n T = 50\r\n boards = []\r\n badBoards = []\r\n board = initBoard(b1, b2)\r\n temp = copy.deepcopy(board)\r\n boards.append(copy.deepcopy(temp))\r\n minS = score(temp)\r\n S = 50\r\n if minS == 0:\r\n printMyWay(boards,initBoard(b1, b2),initBoard(b2, b2))\r\n while T >= 1 and minS != 0:\r\n currnetCheck = [[0,0]]\r\n temp = makeMove(copy.deepcopy(temp),currnetCheck, 1)\r\n if not temp:\r\n S = 50\r\n temp = copy.deepcopy(board)\r\n boards.append(copy.deepcopy(temp))\r\n else:\r\n S = score(temp)\r\n if minS - S > 0:\r\n minS = S\r\n boards.append(copy.deepcopy(temp))\r\n if minS == 0:\r\n printMyWay(boards,initBoard(b1, b2),initBoard(b2, b2)) \r\n break \r\n else:\r\n prob = math.exp((minS - S)/T) \r\n x = random.random()\r\n if prob > x:\r\n boards.append(copy.deepcopy(temp)) \r\n else:\r\n badBoards.append(copy.deepcopy(temp))\r\n T = T - T*(1/(minS+S)) # Cooling function\r\n if isDetail:\r\n a = boards + badBoards\r\n printMyWay(a,initBoard(b1, b2),initBoard(b2, b2)) \r\n if minS != 0:\r\n printMyWay(boards,initBoard(b1, b2),initBoard(b2, b2))\r\n print(\"No path found.\")\r\n\r\n\r\n\r\ndef bestBag(board):\r\n ''' Return the 3 legal boards '''\r\n minS = score(board)\r\n Bag = []\r\n S = 50\r\n kCounter = 0 \r\n currnetCheck = [[0,0]] \r\n while kCounter != 3:\r\n temp = makeMove(copy.deepcopy(board), currnetCheck, 1 )\r\n if not temp:\r\n S = 50\r\n kCounter += 1\r\n else: \r\n S = score(temp)\r\n if S < minS:\r\n Bag.append(copy.deepcopy(temp))\r\n kCounter += 1\r\n return Bag \r\n\r\ndef localBeam(b1, b2, isDetail):\r\n ''' Local beam search algorithm (beam = 3) '''\r\n boradBag = []\r\n temp = []\r\n final= {'1': [], '2': [], '3': []}\r\n finalKey = '1'\r\n counter = 0\r\n board = initBoard(b1, b2)\r\n minS = score(board)\r\n S = 50\r\n boradBag = bestBag(copy.deepcopy(board))\r\n for key, value in final.items():\r\n value.append(copy.deepcopy(board)) \r\n while minS != 0 and counter != 100: \r\n for key, value in final.items():\r\n boradBag = bestBag(copy.deepcopy(value[-1]))\r\n for b in boradBag:\r\n S = score(b)\r\n if S <= minS:\r\n minS = S\r\n temp.append(b)\r\n if minS == 0:\r\n finalKey = key\r\n break\r\n if temp: \r\n final[key].append(temp[np.random.randint(0,len(temp))])\r\n temp.clear()\r\n if isDetail:\r\n printBag(boradBag, counter, key)\r\n boradBag.clear()\r\n counter += 1 \r\n if minS == 0:\r\n printMyWay(final[finalKey],initBoard(b1, b2),initBoard(b2, b2))\r\n else:\r\n printMyWay(final[finalKey],initBoard(b1, b2),initBoard(b2, b2))\r\n print(\"No path Found.\") \r\n\r\ndef reproduce(dad, mom):\r\n ''' Create new board from two legal boards \r\n by chosen random index from each board '''\r\n child = [[0 for x in range(6)] for y in range(6)]\r\n d1 = []\r\n m1 = []\r\n for r in range(len(dad)):\r\n for c in range(len(dad[r])):\r\n if dad[r][c] == 1:\r\n d1.append([r,c])\r\n for r in range(len(mom)):\r\n for c in range(len(mom[r])):\r\n if mom[r][c] == 1:\r\n m1.append([r,c])\r\n for r in range(len(dad)):\r\n for c in range(len(dad[r])):\r\n if dad[r][c] == mom[r][c] == 2 or dad[r][c] == mom[r][c] == 3:\r\n child[r][c] = dad[r][c]\r\n if len(d1) == len(m1):\r\n for i in range(len(d1)):\r\n x=random.random()\r\n if x <= 0.5:\r\n child[d1[i][0]][d1[i][1]] = 1\r\n else: \r\n child[m1[i][0]][m1[i][1]] = 1\r\n elif len(d1) > len(m1):\r\n for i in range(len(m1)):\r\n x=random.random()\r\n if x <= 0.5:\r\n child[d1[i][0]][d1[i][1]] = 1\r\n else: \r\n child[m1[i][0]][m1[i][1]] = 1\r\n for i in range(len(m1),len(d1)): \r\n child[d1[i][0]][d1[i][1]] = 1\r\n else:\r\n for i in range(len(d1)):\r\n x=random.random()\r\n if x <= 0.5:\r\n child[d1[i][0]][d1[i][1]] = 1\r\n else: \r\n child[m1[i][0]][m1[i][1]] = 1\r\n for i in range(len(d1),len(m1)): \r\n child[m1[i][0]][m1[i][1]] = 1\r\n \r\n return child\r\n\r\n\r\ndef GeneticAlgorithm(b1, b2, isDetail):\r\n ''' Genetic search limited for 100 generations '''\r\n board = initBoard(b1, b2)\r\n minS = score(board)\r\n S = 50\r\n dad = [] \r\n mom = []\r\n child=[]\r\n population = []\r\n final = []\r\n currnetCheck = [[0,0]]\r\n final.append(copy.deepcopy(board))\r\n population.append(copy.deepcopy(board))\r\n for i in range(100):\r\n while not dad or not mom:\r\n print('dont have dad and mom yet!!!')\r\n dad = makeMove(copy.deepcopy(board), [[0,0]], 1 )\r\n mom = makeMove(copy.deepcopy(board), [[0,0]], 1 )\r\n child = reproduce(dad, mom)\r\n if score(child) == 50:\r\n print(\"broken child \", child)\r\n elif score(child) == 0:\r\n final.append(copy.deepcopy(child))\r\n population.append(copy.deepcopy(child)) \r\n break\r\n else:\r\n population.append(copy.deepcopy(child)) \r\n x=random.random()\r\n if x > 0.5:\r\n board = copy.deepcopy(child)\r\n final.append(copy.deepcopy(child))\r\n dad.clear()\r\n mom.clear()\r\n if isDetail:\r\n printMyWay(population,initBoard(b1, b2),initBoard(b2, b2))\r\n else:\r\n printMyWay(final,initBoard(b1, b2),initBoard(b2, b2))\r\n if score(child) != 0:\r\n print(\"No Path Found\")\r\n\r\ndef findFrontier(b ,goal):\r\n ''' Return an array of all the next states sorted by score '''\r\n boards = []\r\n for r in range(len(b)):\r\n for c in range (len(b[r])):\r\n if b[r][c] == 1:\r\n board1 = copy.deepcopy(b)\r\n board2 = copy.deepcopy(b)\r\n if isLegal(r+1,c+1,board1):\r\n board1[r][c] = 0\r\n if r!=5:\r\n board1[r+1][c+1] = 1\r\n if r == 5:\r\n pass \r\n if isLegal(r+1,c-1,board2):\r\n board2[r][c] = 0\r\n if r!=5:\r\n board2[r+1][c-1] = 1\r\n if r ==5:\r\n pass \r\n boards.append(initBoard(copy.deepcopy(board1),goal))\r\n boards.append(initBoard(copy.deepcopy(board2),goal)) \r\n boards.sort(key = score)\r\n return boards\r\n \r\ndef tempBoard(b):\r\n ''' initialized temp board '''\r\n temp = [[0 for x in range(6)] for y in range(6)] \r\n for r in range(len(b)):\r\n for c in range (len(b[r])):\r\n if b[r][c] == 1 or b[r][c] == 2:\r\n temp[r][c] = 1\r\n return temp \r\n\r\ndef AStar(b1, b2, isDetail):\r\n ''' A Star search algorithm '''\r\n board = initBoard(b1, b2)\r\n minS = score(board)\r\n S = 50\r\n frontier = findFrontier(b1, b2)\r\n exploared=[]\r\n exploaredDetail=[]\r\n exploared.append(copy.deepcopy(board))\r\n exploaredDetail.append([copy.deepcopy(board),minS])\r\n finish = False\r\n while not finish:\r\n if not frontier:\r\n finish = True\r\n break\r\n if minS == 0:\r\n finish = True\r\n break\r\n S = score(frontier[0])\r\n if S < minS:\r\n minS = S\r\n exploared.append(copy.deepcopy(frontier[0]))\r\n exploaredDetail.append([copy.deepcopy(frontier[0]),minS]) \r\n frontier = findFrontier(tempBoard(exploared[-1]), b2)\r\n print(frontier)\r\n if isDetail:\r\n printMyWayDetail(exploaredDetail, initBoard(b1, b2), initBoard(b2, b2))\r\n else: \r\n printMyWay(exploared, initBoard(b1, b2), initBoard(b2, b2))\r\n\r\n\r\ndef findPlayPath(algNum, b1, b2, isDetail):\r\n if algNum == \"1\":\r\n hillClimbing(b1, b2)\r\n elif algNum == \"2\": \r\n SA(b1, b2, isDetail) \r\n elif algNum == \"3\":\r\n localBeam(b1, b2, isDetail)\r\n elif algNum == \"4\":\r\n GeneticAlgorithm(b1, b2, isDetail) \r\n elif algNum == \"5\":\r\n AStar(b1, b2, isDetail)\r\n else:\r\n print(\"Illegal value, please insert value between 1-5!\")\r\n \r\n \r\n\r\n\r\nif __name__ == \"__main__\":\r\n \r\n algNum = input(\"Please choose Search method(1-5): \\n1. Hill climbing\\n2. Simulated annealing\\n3. Local beam\\n4. Genetic\\n5. A Star \")\r\n ans = input(\"Did you insert the boards in the top of the script (y/n)? \")\r\n if ans != 'y':\r\n print (\"Please insert the starting board as array, space between each number (1 for * , 0 for empty cell) \\nand press enter for the next row\")\r\n a = [[0]*6 for _ in range(6)]\r\n for i in range(6):\r\n a[i] = [int(j) for j in input(\"Row \"+ str(i+1) + \": \").strip().split(\" \")]\r\n printBoard(makeBoard(a))\r\n ans = input(\"Do you confirm the board (y/n)? \")\r\n if ans == 'y':\r\n startBoard = copy.deepcopy(a)\r\n else:\r\n sys.exit(0) \r\n print (\"Please insert the goal board as array, space between each number (1 for * , 0 for empty cell) \\nand press enter for the next row\") \r\n a = [[0]*6 for _ in range(6)]\r\n for i in range(6):\r\n a[i] = [int(j) for j in input(\"Row \"+ str(i+1) + \": \").strip().split(\" \")]\r\n printBoard(makeBoard(a))\r\n ans = input(\"Do you confirm the board (y/n)? \")\r\n if ans == 'y':\r\n goalBoard = copy.deepcopy(a) \r\n else:\r\n sys.exit(0) \r\n isDetail = input(\"Do you want Detail output (y/n)?\\n \")\r\n if isDetail == 'y':\r\n isDetail = True\r\n else:\r\n isDetail = False \r\n findPlayPath(algNum, startBoard, goalBoard, isDetail)\r\n\r\n\r\n \r\n\r\n\r\n\r\n\r\n\r\n"} {"blob_id": "f73633bbcb4b43f69ea9634bf550c41bba263497", "repo_name": "mvsaha/blahb", "path": "/blahb/encoding.py", "length_bytes": 12410, "score": 3.734375, "int_score": 4, "content": "import numpy as np\nimport numba\n\n\"\"\"\nThe idea of this compression is to pack multiple dimensions that each require\nless than 32 bits of information to represent into the _loc array of an\nIndexSet.\n\nThe compression should be structured such that a lexicographical comparion\nbetween two compressed rows should return the same value as a lexicographical\ncomparison between the uncompressed versions of the rows. This allows us to\nperform set operations on compressed IndexSets while avoiding potentially\ncostly unpacking.\n\nIn this module, the specification for how many bits each dimension gets\nis given by an encoding, a 1d array with a single signed integer for each\ndimension (column) of IndexSet.loc. If the value along a given dimension, `e`,\nis positive, this asserts that all values in that corresponding dimension are\npositive, and all are in the half-open range:\n [0, 2 ** e).\nIf `e` is negative, this asserts that all of the values lie in the range:\n [ -(2 ** abs(e)), 2 ** abs(e) )\n(and therefore requires abs(e) + 1 bits of representational power).\n\nOnce encoded, a bit-packed array is stored in the IndexSet as the int32 `loc`\narray as in a uncompressed IndexSet. However, the bit order must be\ninterpreted as an array of uint32 (accessed through array.view(np.uint32)) for\nthe purposes of lexicographical comparison.\n\nThe utilities below actually support encoding/decoding numbers >32 bits (i.e.\nstoring values >32 bits acrossed multiple columns of a packed 32 bit columns)\nbut the IndexSet is currently restricted to int32 indices, so this doesn't\ncome into play.\n\"\"\"\n\n\n@numba.njit\ndef bits_required(lo, hi):\n \"\"\"Find the number of bits needed to represent all values in a range.\n\n Arguments\n ---------\n lo, hi : int\n The lower and upper (inclusive) range of values that we want to\n represent.\n\n Returns\n -------\n n_bits : signed int\n The number of bits needed to represent all of the values in the range\n if both `lo` and `hi` are >= 0.\n If `lo` is negative, the negation of the maximum number of bits that are\n needed to represent the positive range is returned.\n [ 0, max(abs(lo), abs(hi)) )\n \"\"\"\n if abs(lo) <= abs(hi):\n n_bits = int(np.ceil(np.log2(abs(hi) + 1)))\n else:\n n_bits = int(np.ceil(np.log2(abs(lo))))\n \n if lo < 0:\n n_bits += 1\n \n return n_bits\n\n@numba.njit\ndef bit_code(lo, hi):\n \"\"\"Return the encoding value that is needed to represent a range of values.\n \n These should be used as the integer values for the encoding array passed\n into IndexSet.encode().\n \"\"\"\n b = bits_required(lo, hi)\n if lo < 0 or hi < 0: # Need a negative representation\n return -(b - 1)\n return b\n\n@numba.njit\ndef min_encoded_value(n_bits):\n \"\"\"The minimum value encoded by a signed bit-width.\"\"\"\n return 0 if n_bits >= 0 else -(2 ** (abs(n_bits)))\n\n\n@numba.njit\ndef bits_needed(encoding):\n \"\"\"The number of 32 bit columns needed for an encoding.\"\"\"\n n_bits = 0\n for e in encoding:\n n_bits += e if e >= 0 else abs(e) + 1\n return n_bits\n\n\n@numba.njit\ndef packed_columns_needed(encoding):\n n_bits_total = bits_needed(encoding)\n n_ints_needed = n_bits_total // 32\n if n_bits_total % 32:\n n_ints_needed += 1\n return n_ints_needed\n\n\n@numba.njit\ndef drop_lsb_bits(val, n_bits):\n \"\"\"Drop the lowest bits in a number.\"\"\"\n return (val >> n_bits) << n_bits\n\n\n@numba.njit\ndef keep_lsb_bits(val, bits_to_keep):\n \"\"\"Unset all bits but the lowest.\"\"\"\n return val & ~drop_lsb_bits(val, bits_to_keep)\n\n\n@numba.njit\ndef write_encoded(vals, encoding, packed, start):\n \"\"\"Pack values of a certain number of bits into an encoded array.\n\n Arguments\n ---------\n vals : 1d array\n This will be mutated\n encoding : int\n The\n packed : 2d int\n The compressed array\n start : int\n The number of bits already written to packed, with MSBs of\n each column of packed filling up first.\n \"\"\"\n \n # Number of bits in each column of compressed\n column_bit_capacity = 32\n \n n = vals.size\n min_val = min_encoded_value(encoding)\n \n # Need an extra bit to encode negative\n val_bit_width = encoding if encoding >= 0 else abs(encoding) + 1\n \n bits_to_write = val_bit_width #\n total_bits_written = 0\n \n while bits_to_write:\n \n column = start // column_bit_capacity # The column index to write to\n column_bit_start = start - (column * column_bit_capacity) #\n \n bits_left_in_column = column_bit_capacity - column_bit_start\n bits_taken = min(bits_left_in_column, bits_to_write)\n \n # The number of bits that we will be left in the\n n_lsb_bits_dropped = bits_to_write - bits_taken\n \n # The LSB of the bit range to be written\n shift = (column_bit_capacity - column_bit_start\n - bits_taken - n_lsb_bits_dropped)\n \n if shift == 0:\n for i in range(n):\n # Take only the first `bits_taken` higher bits\n val_to_write = drop_lsb_bits(\n vals[i] - min_val, n_lsb_bits_dropped)\n val_to_write = keep_lsb_bits(val_to_write, val_bit_width)\n packed[i, column] |= np.uint32(val_to_write)\n elif shift < 0:\n shift = abs(shift)\n for i in range(n):\n # Take only the first `bits_taken` higher bits\n val_to_write = drop_lsb_bits(\n vals[i] - min_val, n_lsb_bits_dropped)\n val_to_write = keep_lsb_bits(val_to_write, val_bit_width)\n packed[i, column] |= np.uint32(val_to_write >> shift)\n else:\n for i in range(n):\n # Take only the first `bits_taken` higher bits\n val_to_write = drop_lsb_bits(\n vals[i] - min_val, n_lsb_bits_dropped)\n val_to_write = keep_lsb_bits(val_to_write, val_bit_width)\n packed[i, column] |= np.uint32(val_to_write << shift)\n \n total_bits_written += bits_taken\n start += bits_taken\n bits_to_write -= bits_taken\n \n assert total_bits_written == val_bit_width\n assert bits_to_write == 0\n return start\n\n\n@numba.njit\ndef read_encoded(packed, encoding, vals, start):\n \"\"\"Unpack values from an encoded bit-packed array.\"\"\"\n column_bit_capacity = 32\n n = packed.shape[0]\n min_val = min_encoded_value(encoding)\n val_bit_width = encoding if encoding >= 0 else abs(encoding) + 1\n bits_to_read = val_bit_width #\n total_bits_read = 0\n vals_unsigned = vals.view(np.uint32)\n vals_signed = vals.view(np.int32)\n while bits_to_read:\n column = start // column_bit_capacity\n column_bit_start = start - (column * column_bit_capacity) #\n \n bits_left_in_column = column_bit_capacity - column_bit_start\n n_bits_read = min(bits_left_in_column, bits_to_read)\n \n # The number of bits that we will not be read\n n_lsb_bits_dropped = bits_to_read - n_bits_read\n \n # The LSB location of the bit range to be read\n shift = (column_bit_capacity - column_bit_start\n - n_bits_read - n_lsb_bits_dropped)\n \n if shift == 0:\n for i in range(n):\n val = keep_lsb_bits(packed[i, column], val_bit_width)\n vals_unsigned[i] |= val\n elif shift < 0:\n shift = abs(shift)\n for i in range(n):\n val = keep_lsb_bits(packed[i, column] << shift, val_bit_width)\n vals_unsigned[i] |= val\n else:\n for i in range(n):\n val = keep_lsb_bits(packed[i, column] >> shift, val_bit_width)\n vals_unsigned[i] |= val\n \n start += n_bits_read\n bits_to_read -= n_bits_read\n \n for i in range(n):\n vals_signed[i] = np.int32(vals_unsigned[i] + min_val)\n return start\n\n\n@numba.njit\ndef encode(loc, encoding):\n \"\"\"Encode locations into bit-packed array.\n\n Arguments\n ---------\n loc : 2d int32 array\n encoding : 1d array\n Should have a shape matching loc.shape[1], the dimensionality.\n Negative values in this array indicate that negative values\n should be considered as well.\n\n Returns\n -------\n packed : int32 array\n Contains the locations in `loc`, compressed so that\n lexicographical comparisons between rows are still valid.\n \"\"\"\n if not (encoding.ndim == 1 and encoding.size == loc.shape[1]):\n raise ValueError(\"`encoding` must be 1d and have size equal to \"\n \"dimensions of `loc`.\")\n n, ndim = loc.shape[0], packed_columns_needed(encoding)\n packed = np.zeros((n, ndim), dtype=np.uint32)\n start = 0\n for dim in range(loc.shape[1]):\n start = write_encoded(loc[:, dim], encoding[dim], packed, start)\n return packed\n\n\n@numba.njit\ndef read_encoded(packed, encoding, vals, start):\n \"\"\"Unpack values from an encoded bit-packed array.\n \n Arguments\n ---------\n packed : 2d array\n A n-by-ndim array containing bit-packed 32 bit unsigned integers\n encoding : 1d array\n vals : 1d array\n The array to write the outputs to\n start : int\n The start bit from which to read (from the first LSB in the array)\n \"\"\"\n column_bit_capacity = 32\n n = packed.shape[0]\n min_val = min_encoded_value(encoding)\n val_bit_width = encoding if encoding >= 0 else abs(encoding) + 1\n bits_to_read = val_bit_width #\n total_bits_read = 0\n vals_unsigned = vals.view(np.uint32)\n vals_signed = vals.view(np.int32)\n \n while bits_to_read:\n column = start // column_bit_capacity\n column_bit_start = start - (column * column_bit_capacity) #\n \n bits_left_in_column = column_bit_capacity - column_bit_start\n n_bits_read = min(bits_left_in_column, bits_to_read)\n \n # The number of bits that we will not be read\n n_lsb_bits_dropped = bits_to_read - n_bits_read\n \n # The LSB location of the bit range to be read\n shift = (column_bit_capacity - column_bit_start\n - n_bits_read - n_lsb_bits_dropped)\n \n if shift == 0:\n for i in range(n):\n val = keep_lsb_bits(packed[i, column], val_bit_width)\n vals_unsigned[i] |= val\n elif shift < 0:\n shift = abs(shift)\n for i in range(n):\n val = keep_lsb_bits(packed[i, column] << shift, val_bit_width)\n vals_unsigned[i] |= val\n else:\n for i in range(n):\n val = keep_lsb_bits(packed[i, column] >> shift, val_bit_width)\n vals_unsigned[i] |= val\n \n start += n_bits_read\n bits_to_read -= n_bits_read\n total_bits_read += n_bits_read\n \n assert total_bits_read == val_bit_width\n assert bits_to_read == 0\n \n for i in range(n):\n vals_signed[i] = np.int32(vals_unsigned[i] + min_val)\n return start\n\n\n@numba.njit\ndef decode(packed, encoding):\n loc = np.zeros((packed.shape[0], encoding.size), dtype=np.int32)\n start = 0\n for dim in range(encoding.size):\n start = read_encoded(packed, encoding[dim], loc[:, dim], start)\n return loc\n\n\n@numba.njit\ndef compatible_encoding(a, b):\n \"\"\"Test whether two IndexSets have compatible encoding.\n \n Arguments\n ---------\n a, b: IndexSet objects\n \n Returns\n -------\n True if the encoding arrays for `a` and `b` are identical. Returns False\n if either `a` or `b` are not encoded.\n \"\"\"\n if (a.encoding is None or b.encoding is None or\n a.encoding.size != b.encoding.size):\n return False\n \n a_enc = a.encoding.view(np.int8)\n b_enc = b.encoding.view(np.int8)\n for i in range(a_enc.size):\n if a_enc[i] != b_enc[i]:\n return False\n return True\n\n\n@numba.njit\ndef same_encoding(a, b):\n if a.encoding is None and b.encoding is None:\n return True\n elif a.encoding is None or b.encoding is None:\n return False\n else:\n if not a.encoding.size == b.encoding.size:\n return False\n \n for i in range(a.encoding.size):\n if a.encoding[i] != b.encoding[i]:\n return False\n return True"} {"blob_id": "b7573ea7b46439650857a1553e9efb33e575fc69", "repo_name": "BrandonLMorris/ml-examples", "path": "/linear_regression/linear_regression.py", "length_bytes": 5643, "score": 4.0, "int_score": 4, "content": "#!/usr/local/env python3\n\"\"\"\nSimple linear regression with gradient descent. No optimization attempts have\nbeen made, this is purely for example and educational purposes.\n\nData is randomly generated and saved to a file in the current directory for\nreproduceability. To regenerate the data, simply delete the\n'linear_regression_data.txt' file.\n\"\"\"\n\nfrom random import randint\nfrom numpy import linspace, random, array\nfrom matplotlib import pyplot\nfrom sklearn.linear_model import LinearRegression\n\n# Defined parameters for linear function (y = ax + b)\nA = 4\nB = 15\nSIGMA = 5\nLEARNING_RATE = .0003\nDATA_FILE = 'linear_regression_data.txt'\n\n\ndef generate_noisy_data(slope, intercept, start=0, stop=100):\n \"\"\"Create some linear data with some noise added to it\"\"\"\n num_points = abs(start) + abs(stop)\n line = linspace(start, stop, num_points)\n noise = random.normal(0, SIGMA, num_points)\n noisy = [(slope * d + intercept) + n for (d, n) in zip(line, noise)]\n return noisy\n\n\ndef save_data(x, y):\n \"\"\"Save the x and y coordinates to a file\"\"\"\n with open(DATA_FILE, 'w+') as f:\n for (xx, yy) in zip(x, y):\n f.write('{} {}\\n'.format(xx, yy))\n\n\ndef get_data():\n \"\"\"Retrieve the data from the cached file\n\n If the data can't be found in a saved file, generate some new data\n and save that to a file\n \"\"\"\n x, y = list(), list()\n try:\n with open(DATA_FILE, 'r') as f:\n lines = f.readlines()\n for line in lines:\n xx, yy = line.split()\n x.append(float(xx))\n y.append(float(yy))\n return x, y\n except FileNotFoundError:\n # No data file, generate the data\n y = generate_noisy_data(A, B)\n x = list(range(len(y)))\n save_data(x, y)\n return get_data()\n\n\ndef hypothesis(theta0, theta1, x):\n \"\"\"Return our hypothesis, or guess, given the parameters and input value\"\"\"\n return theta0 + (theta1 * x)\n\n\ndef cost(X, Y, theta0, theta1):\n \"\"\"Find the total cost of our model from the training examples\n\n :param X: a list of input values\n :param Y: a list of ouput values\n :param theta0: the value of the first parameter of the model\n :param theta1: the value of the second parameter of the model\n \"\"\"\n errors = [(hypothesis(theta0, theta1, x) - y) for (x, y) in zip(X, Y)]\n return (1 / (2 * len(Y))) * sum([e * e for e in errors])\n\n\ndef descend(alpha, theta0, theta1, X, Y):\n \"\"\"One iteration of gradient descent\n\n Adjusts the model to reflect a single step of the linear descent algorithm\n\n :param alpha: the learning rate\n :param thetas: a list of parameters for the model\n :param Y: a list of output values\n :param X: a list of input values\n \"\"\"\n results = list()\n n = len(Y)\n partial0 = (1 / n) * sum([(hypothesis(theta0, theta1, x) - y)\n for (x, y) in zip(X, Y)])\n partial1 = (1 / n) * sum([(hypothesis(theta0, theta1, x) - y) * x\n for (x, y) in zip(X, Y)])\n new_theta0 = theta0 - alpha * partial0\n new_theta1 = theta1 - alpha * partial1\n return (new_theta0, new_theta1)\n\n\ndef r_squared(Y_predict, Y_true):\n \"\"\"Calculate the R-squared value of the model\n\n :param theta0: the first parameter of the model\n :param theta1: the second parameter of the model\n :param X: a list of input values\n :param Y: a list of output values\n \"\"\"\n u = sum([(yt - yp) ** 2 for (yt, yp) in zip(Y_true, Y_predict)])\n mean = sum(Y_true) / len(Y_true)\n v = sum([(y - mean) ** 2 for y in Y_true])\n return (1 - (u / v))\n\n\ndef extract_test_set(X, Y):\n \"\"\"Segregate the data set into test and training sets\"\"\"\n num_test = round(len(X) * .3)\n X_test, Y_test = list(), list()\n for i in range(num_test):\n index = randint(0, len(X) - 1)\n X_test.append(X.pop(index))\n Y_test.append(Y.pop(index))\n return (X, X_test, Y, Y_test)\n\n\ndef main():\n # Plot the original data set\n X, Y = get_data()\n pyplot.title(\"Original Data Set\")\n pyplot.plot(Y, 'k.')\n pyplot.show()\n\n # Create our initial values\n X_train, X_test, Y_train, Y_test = extract_test_set(X, Y)\n theta0, theta1 = 0, 0\n\n # Train out model\n prev_cost = 2 << 32 # Arbitrarily large number\n iterations = 0\n while True:\n theta0, theta1 = descend(LEARNING_RATE, theta0, theta1, X_train,\n Y_train)\n current_cost = cost(X_train, Y_train, theta0, theta1)\n\n # Stop if we've converged\n if abs(current_cost - prev_cost) < 0.0001:\n print('{} iterations'.format(iterations))\n break\n else:\n iterations += 1\n prev_cost = current_cost\n\n # Plot our results\n result = [hypothesis(theta0, theta1, yy) for yy in range(0, 100)]\n pyplot.title(\"By-Hand Results\")\n pyplot.plot(X, Y, 'k.')\n pyplot.plot(result)\n pyplot.show()\n\n Y_predict = [hypothesis(theta0, theta1, x) for x in X_test]\n print('R^2 from by-hand: {}'.format(r_squared(Y_predict, Y_test)))\n\n # Same algorithm, but utilize sklearn\n lr = LinearRegression()\n X_vector, Y_vector = (array(X_train).reshape(-1, 1),\n array(Y_train).reshape(-1, 1))\n lr.fit(X_vector, Y_vector)\n sk_predictions = [lr.predict(x) for x in X]\n print('R^2 from sklearn: {}'.format(lr.score(X_vector, Y_vector)))\n\n # Plot the results\n sk_y_predict = [lr.predict(x)[0, 0] for x in X]\n pyplot.title('sklearn Results')\n pyplot.plot(X, Y, 'k.')\n pyplot.plot(X, sk_y_predict)\n pyplot.show()\n\n\nif __name__ == '__main__':\n main()\n\n"} {"blob_id": "bb2b3696c94c4dc772fd43e3bd99168ce0f05762", "repo_name": "oriel975/orielwork", "path": "/equtaions.py", "length_bytes": 1791, "score": 3.578125, "int_score": 4, "content": "# -*- coding: utf-8 -*-\ndef XtimesY(x,y):\n if x <= 0:\n return 0.0\n return exponent(y*Ln(x))\n\n\ndef myfactorial(x):\n fac = 1\n i = 1\n while i <= x:\n fac = fac * i\n i = i + 1 \n return fac\n \n\ndef mypow(x,y):\n ans = 1\n for n in range(y):\n ans=ans*x\n # print (\"mypow\",ans) \n return ans\n\n#def exponent(x):\n# exp = x\n# result = 1 + x\n# i = 2\n# while i < 100:\n# x *= exp\n# result += (x/myfactorial(i))\n# i += 1\n# return result\n\ndef exponent(x):\n ans = 1 + x\n for n in range (2,100):\n x_pow = mypow(x,n)\n ans += (x_pow/myfactorial(n))\n return ans\n\n\n#def Ln(x):\n# if x <= 0:\n# return 0.0\n# Epsilon = 0.001\n# y = x - 1.0\n# result = y\n# while True:\n# new_y = y + 2 * ((x - exponent1(y)) / (x + exponent1(y)))\n# result = new_y\n# dif = new_y - y\n# if dif < 0:\n# dif = dif * (-1)\n# if dif <= Epsilon:\n# return result\n# y = new_y \n \ndef calcAbs(x,y):\n remainder = x - y\n if remainder < 0:\n return remainder * (-1)\n return remainder\n \ndef Ln(x):\n if x <= 0:\n return 0.0\n yn = x - 1.0\n while True:\n yn1 = yn + 2 * ((x - exponent(yn)) / (x + exponent(yn)))\n if (calcAbs(yn1,yn)) <= 0.001:\n return yn1\n yn = yn1\n \ndef sqrt(x,y):\n if y <= 0:\n return 0.0\n return float('%0.6f' % XtimesY(y,1/x))\n \n\ndef calculate(x):\n if x <= 0:\n return 0.0\n return float('%0.6f' % (exponent(x) * XtimesY(7,x) * XtimesY(x,-1) * sqrt(x,x)))\n \n#print (mypow(2,2)) \n#print(myfactorial(4)) \n#print (XtimesY(-2.2,2))\n#print(exponent(2))\n#print(exponent(2.0))\nprint (calculate(2))\n#print (sqrt(2.5,4))\n"} {"blob_id": "bf24e8592619e15bc63f62581bf987a200f555af", "repo_name": "DmitryVlaznev/leetcode", "path": "/234-palindrome-linked-list.py", "length_bytes": 1516, "score": 3.859375, "int_score": 4, "content": "# 234. Palindrome Linked List\n\n# Easy\n\n# Given the head of a singly linked list, return true if it is a\n# palindrome.\n\n# Example 1:\n# Input: head = [1,2,2,1]\n# Output: true\n\n# Example 2:\n# Input: head = [1,2]\n# Output: false\n\n\n# Constraints:\n# The number of nodes in the list is in the range [1, 10^5].\n# 0 <= Node.val <= 9\n\n# Follow up: Could you do it in O(n) time and O(1) space?\n\nfrom utils import ListNode, checkValue, listFromArray, listToArray\n\n\nclass Solution:\n def isPalindrome(self, head: ListNode) -> bool:\n l, p = 0, head\n while p:\n l += 1\n p = p.next\n if l < 2:\n return True\n mid = l // 2 + l % 2\n i, l_tail = 1, head\n while i < mid:\n i, l_tail = i + 1, l_tail.next\n\n r_head, p = None, l_tail.next\n while p:\n n = p.next\n p.next = r_head\n r_head = p\n p = n\n\n l_tail.next = r_head\n p, q = head, r_head\n while q:\n if p.val != q.val:\n return False\n p, q = p.next, q.next\n return True\n\n\nt = Solution()\n\ncheckValue(True, t.isPalindrome(listFromArray([2, 2])))\ncheckValue(True, t.isPalindrome(listFromArray([1, 2, 3, 2, 1])))\ncheckValue(True, t.isPalindrome(listFromArray([1, 2, 3, 4, 4, 3, 2, 1])))\ncheckValue(False, t.isPalindrome(listFromArray([2, 1])))\ncheckValue(False, t.isPalindrome(listFromArray([1, 2, 3, 1, 2])))\ncheckValue(False, t.isPalindrome(listFromArray([1, 2, 3, 4, 4, 3, 4, 1])))\n"} {"blob_id": "1e7a5c403d1243d40cb74129eb35956828a49ac8", "repo_name": "marissa-graham/undergraduate_work", "path": "/Non-ACME classes/cs557proj4.py", "length_bytes": 4633, "score": 3.671875, "int_score": 4, "content": "from __future__ import division\r\nimport sys\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\n\r\ndef deCasteljua(P,n,u):\r\n \"\"\"Better because doesn't require calculating Bernstein schtuff.\"\"\"\r\n Q = np.copy(P)\r\n #print \"Q.shape, n: \", Q.shape, n\r\n\r\n # Need each column of Q to be a point\r\n # P is an array of points; each column is a point\r\n for k in xrange(1,n+1):\r\n for i in xrange(n-k+1):\r\n Q[:,i] = (1.0-u)*Q[:,i] + u*Q[:,i+1]\r\n return Q[:,0].T\r\n\r\ndef deCasteljua2(P,n,m,u0,v0):\r\n \"\"\"n rows by m columns. MUST BE N ROWS BY M COLUMNS.\"\"\"\r\n #print \"P.shape: \", P.shape\r\n #print \"n, m = \", n, m\r\n if n <= m:\r\n # 3 because 3d points\r\n Q = np.zeros((3,n+1))\r\n for j in xrange(n+1):\r\n # Go through the rows\r\n Q[:,j] = deCasteljua(P[j,:,:].T,m,u0)\r\n return deCasteljua(Q,n,v0)\r\n else:\r\n #print \"Case where m > n:\"\r\n Q = np.zeros((3,m+1))\r\n for i in xrange(m+1):\r\n # Go through the columns\r\n Q[:,i] = deCasteljua(P[:,i,:].T,n,v0)\r\n return deCasteljua(Q,m,u0)\r\n\r\ndef bezier_surface(A):\r\n \"\"\"\r\n Plot the nonrational bezier surface defined by the (n+1)x(m+1)\r\n net of points defined by the (n+1)x(m+1)x3 matrix A.\r\n \"\"\"\r\n n, m, z = A.shape\r\n n, m = n-1, m-1\r\n res = 10\r\n B = np.zeros((res,res,3))\r\n\r\n u = np.linspace(0,1,res)\r\n v = np.linspace(0,1,res)\r\n for i in xrange(res):\r\n for j in xrange(res):\r\n B[i,j,:] = deCasteljua2(A,n,m,u[i],v[j]) \r\n\r\n return B\r\n\r\ndef get_normals(pts, deg):\r\n # Get the partial derivatives control points in the x direction\r\n # n*(P_i+1 - P_i)\r\n D_x = deg[1]*(pts[:,1:,:] - pts[:,:-1,:])\r\n print D_x.shape\r\n\r\n # Get the partial derivatives control points in the y direction\r\n D_y = deg[0]*(pts[1:,:,:] - pts[:-1,:,:])\r\n print D_y.shape\r\n\r\n # Get the partial derivative values at each sample point in the patch\r\n B_x = bezier_surface(D_x)\r\n B_y = bezier_surface(D_y)\r\n\r\n # Cross the partial derivatives to get the normal\r\n return np.cross(B_x,B_y)\r\n\r\nclass Patch(object):\r\n def __init__(self, degree, pts):\r\n # Get the i,jth point with pts[i,j,:]\r\n # Get the x coordinates with pts[:,:,0], etc.\r\n # pts[:,i,:] gives you the ith column of points in the patch\r\n # pts[j,:,:] gives you the jth row of points in the patch\r\n self.degree = degree\r\n self.points = pts\r\n\r\ndef get_patches(filename):\r\n patches = {}\r\n with open(filename) as f:\r\n # Get number of patches\r\n N = int(f.readline().strip().lower())\r\n\r\n for i in xrange(N):\r\n # Get the degree of the patch\r\n deg = map(int, f.readline().strip().lower().split())\r\n\r\n # Read in the points for the patch\r\n pts = []\r\n for j in xrange((deg[0]+1)*(deg[1]+1)):\r\n pts.append(np.array(map(float, f.readline().strip().lower().split())))\r\n\r\n # Each point is a row\r\n pts = np.array(pts).reshape((deg[0]+1,deg[1]+1,3))\r\n patches[i] = Patch(deg, pts)\r\n\r\n return N, patches\r\n\r\ndef main():\r\n k = 1\r\n # Ensure command line input is correct\r\n if len(sys.argv) < 3:\r\n print \"Syntax:\\n python cs557proj4.py testfile outputfile\"\r\n return\r\n\r\n # Read in and store patches\r\n N, patches = get_patches(sys.argv[1])\r\n \r\n # Create the output file.\r\n output = [\"g\"]\r\n face_output = []\r\n\r\n # Go through the patches\r\n for n in xrange(N):\r\n print patches[n].points.shape\r\n B = bezier_surface(patches[n].points)\r\n Vn = get_normals(patches[n].points,patches[n].degree)\r\n\r\n for i in xrange(9):\r\n for j in xrange(9):\r\n # Add the face \r\n output.append(\"v {} {} {}\".format(*B[i,j,:]))\r\n output.append(\"v {} {} {}\".format(*B[i+1,j,:]))\r\n output.append(\"v {} {} {}\".format(*B[i+1,j+1,:]))\r\n output.append(\"v {} {} {}\".format(*B[i,j+1,:]))\r\n output.append(\"vn {} {} {}\".format(*Vn[i,j,:]))\r\n output.append(\"vn {} {} {}\".format(*Vn[i+1,j,:]))\r\n output.append(\"vn {} {} {}\".format(*Vn[i+1,j+1,:]))\r\n output.append(\"vn {} {} {}\".format(*Vn[i,j+1,:]))\r\n face_output.append(\"f {}//{} {}//{} {}//{} {}//{}\".format(k,k,k+1,k+1,k+2,k+2,k+3,k+3))\r\n k += 4\r\n\r\n # Write to output file \r\n with open(sys.argv[2], 'w') as f:\r\n f.write(\"\\n\".join(output)+\"\\n\")\r\n f.write(\"\\n\".join(face_output)+\"\\n\")\r\n\r\nmain()"} {"blob_id": "b2df25d12178483143cbb6fcceaba3e2220b2b4b", "repo_name": "eludom/snippits", "path": "/python/exercises/python/QuickSort.py", "length_bytes": 2607, "score": 4.125, "int_score": 4, "content": "# -*- coding: utf-8 -*-\n\"\"\"\nThis class implements qucksort on arrays.\n\nSee https://en.wikipedia.org/wiki/Quicksort\n\n# algorithm quicksort(A, lo, hi) is#\n# if lo < hi then\n# p := partition(A, lo, hi)\n# quicksort(A, lo, p \u2013 1)\n# quicksort(A, p + 1, hi)\n# \n# algorithm partition(A, lo, hi) is\n# pivot := A[hi]\n# i := lo - 1 \n# for j := lo to hi - 1 do\n# if A[j] \u2264 pivot then\n# i := i + 1\n# swap A[i] with A[j]\n# swap A[i+1] with A[hi]\n# return i + 1\n# \n\"\"\"\n\nclass QuickSort(object):\n \"\"\"Quicksort implementaton\"\"\"\n\n def __init__(self, unsorted_array):\n \"\"\"Initialize an array for quicksort\"\"\"\n self.array_to_sort = unsorted_array\n self.is_sorted = False\n print \"starting array is\", self.print_array()\n return None\n\n def print_array(self):\n \"\"\"Print the [un]sorted array\"\"\"\n print self.array_to_sort\n\n def swap(self, swap_x, swap_y):\n \"\"\"swap two elements of an array\"\"\"\n tmp = self.array_to_sort[swap_x]\n self.array_to_sort[swap_x] = self.array_to_sort[swap_y]\n self.array_to_sort[swap_y] = tmp\n\n def partition(self, lo_index, hi_index):\n \"\"\"Parttiton the array\"\"\" \n print \"partition(%d,%d)\" % (lo_index, hi_index)\n print \" array: \", self.array_to_sort\n\n # pivot on this value\n pivot = self.array_to_sort[hi_index]\n print \" pivot on hi_index \", hi_index, \" pivot is \", pivot\n print\n\n # next place to put values less than pivot\n insert_here = lo_index - 1 \n\n for from_here in range(lo_index, hi_index):\n if self.array_to_sort[from_here] <= pivot:\n # move where to insert right one\n insert_here = insert_here + 1\n\n # put value less than pivot left of pivot value\n self.swap(insert_here, from_here)\n\n # finally, swap the pivot value itself to the end of the lis\n self.swap(insert_here+1, hi_index)\n\n # and report where we partitioned\n return insert_here + 1\n\n def quicksort(self, lo_index, hi_index):\n \"\"\"Quicksort a slice of the array\"\"\"\n print \"quicksort(%d,%d)\" % (lo_index, hi_index)\n print \" array: \", self.array_to_sort\n print\n if lo_index < hi_index:\n partition_index = self.partition(lo_index, hi_index)\n self.quicksort(lo_index, partition_index - 1)\n self.quicksort(partition_index + 1, hi_index)\n self.is_sorted = True\n"} {"blob_id": "6205d4a230221917c9bd7f1485d004987b397245", "repo_name": "HamPUG/meetings", "path": "/2022/2022-11-14/ian/prime_number_locator.py", "length_bytes": 37717, "score": 3.53125, "int_score": 4, "content": "#!/usr/bin/env python3\n#\n# Program: prime_number_locator.py\n#\n# Objective: Digital Technologies - NCEA Level 3 - example program\n# Locates prime numbers.\n# Uses the tlinter GUI\n# Progress bar uses determinate mode while locating prime\n# numbers\n#\n# Written for: Hamilton Python User Group - Presentation 11 April 2016\n# https://github.com/hampug\n# http://www.meetup.com/nzpug-hamilton/\n#\n# Author: Ian Stewart\n#\n# Date: 2016-Apr-11\n# Updated: 2022-Nov-14 - Add two method using sympy\n#\n# Copyright: This work is licensed under a Creative Commons\n# Attribution-ShareAlike 4.0 International License.\n# http://creativecommons.org/licenses/by-sa/4.0/\n#\n# Notes:\n# 1. Indentation method: 4 x space characters per indentation\n#\n# Python modules to be imported. Plus checking\nimport sys\nimport os\nimport time\nimport math\nimport sympy\n# Check OS platform:\n# Checked on Windows 7 / 10 with python 3.4.4 - OK. 2016-07-29\n#print(sys.platform) # win32\n#\n#if (sys.platform) == \"linux\" or (sys.platform) == \"linux2\":\n# # Program was developed on Linux so it should work OK.\n# pass\n#else:\n# print(\"WARNING: This program was developed and tested on Linux.\\n\"\n# \"It may need modifications for the Operating System you are using.\")\n\n# Check Python is version 3\nif int(sys.version[0]) < 3:\n print(\"Python Version Error: Run program using python3 to support \"\n \"tkinter.\\nExiting...\")\n sys.exit()\n# Import tkinter, ttk, and other tkinter modules\ntry:\n import tkinter as tk\nexcept ImportError as e:\n print(\"Import Error: {}\".format(e))\n print(\"tkinter module for python3 is not available.\")\n print(\"To install tkinter: $ sudo apt-get install python3-tk\")\n sys.exit(1)\ntry:\n from tkinter import ttk\nexcept ImportError as e:\n print(\"Import Error: {}\".format(e))\n print(\"Import Error: tkinter.ttk module is not available.\")\n print(\"To install tkinter: $ sudo apt-get install python3-tk\")\n sys.exit(1)\n\ntry:\n import tkinter.scrolledtext as tkst\nexcept:\n print(\"tkinter does not include scrolled text\")\n sys.exit(1)\n\ntry:\n import tkinter.messagebox as tkmsgbox\nexcept:\n print(\"tkinter does not include messagebox module\")\n sys.exit(1)\n\ntry:\n import tkinter.filedialog as tkfiledialog\nexcept:\n print(\"tkinter does not include filedialog\")\n sys.exit(1)\n\n# Define Variables:\n\n# Define Constants:\nPROGRAM = \"prime_number_locator.py\"\nVERSION = \"1.0\"\nTITLE_1 = \"Prime Number Locator\"\nTITLE_2 = \"Launching tkinter/ttk application. {} {}\".format(PROGRAM, VERSION)\nFONT = ('FreeSans', 12, \"normal\")\nRANGE_TUPLE = (1, 10, 100, 500, 1000, 5000, 10000)\nMETHOD_TUPLE = (\"Divide every number\", \"Skip Even numbers\",\n \"Modulo 6 with 1 & 5\", \"Minimal Recursion\", \"sympy.primerange\",\n \"sympy.primerange list\")\nLABEL_2_TEXT = \"Start From:\"\nLABEL_3_TEXT = \"Range:\"\nLABEL_4_TEXT = \"Method:\"\nLABEL_5A_TEXT = \"Prime Located:\"\nLABEL_5B_TEXT = \"Total Primes:\"\nLABEL_7A_TEXT = \"Elapsed:\"\nLABEL_7B_TEXT = \"Duration:\"\nLABEL_9_TEXT = \"Prime Numbers in the range:\"\nBUTTON_1_TEXT = \"Locate\"\nBUTTON_2_TEXT = \"Clear\"\n# Constants for Help / Infomation class\nHELP_FILE_LIST = (\"prime_number_locator_help.txt\",\n \"prime_number_locator_flow.txt\",\n \"prime_number_locator_reference.txt\",\n \"prime_number_locator_specification.txt\")\nHELP_BUTTON_TEXT_TUPLE = (\"Help\", \"Flow\", \"References\", \"Specification\")\nHELP_BUTTON_TEXT_1 = \"\"\nHELP_BUTTON_TEXT_2 = \"Close\"\n\nMSGBOX_TITLE = \"Prime Number locator - About...\"\nMSGBOX_TEXT = (\"\"\"Prime Number Locator.\nAn NCEA Example program.\nHamilton Python User Group.\nhttps://github.com/hampug\nAuthor: Ian Stewart\nDate: 2016-04-11\n\nThis work is licensed under a Creative Commons\nAttribution-ShareAlike 4.0 International License.\nhttp://creativecommons.org/licenses/by-sa/4.0/\n\"\"\")\n\n\nclass HelpFrame(tk.Toplevel):\n\n \"\"\"Open a child Toplevel window. Read in the help files and display\"\"\"\n\n def __init__(self):\n \"\"\"Constructor for the Toplevel window\"\"\"\n tk.Toplevel.__init__(self)\n # self.geometry(\"400x300\")\n self.title(\"Prime Number Locator - Information\")\n self.create_widgets()\n\n def create_widgets(self):\n \"\"\"create widgets for the help window\"\"\"\n # Information selection button\n self.help_button_text_index = 0\n self.help_button_1 = ttk.Button(self, text=HELP_BUTTON_TEXT_1,\n command=self.select_help_button)\n self.help_button_1.grid(row=1, column=0, padx=5, pady=5, sticky=\"w\")\n # Close button\n self.help_button_2 = ttk.Button(self, text=HELP_BUTTON_TEXT_2,\n command=self.close_help_button)\n self.help_button_2.grid(row=1, column=1, padx=5, pady=5, sticky=\"e\")\n # Scrolled text\n self.help_scrolledtext_1 = tkst.ScrolledText(self,\n wrap=tk.WORD,\n bg='beige',\n font=(FONT))\n self.help_scrolledtext_1.grid(row=0, column=0, columnspan=2)\n\n # Display the help file if it is available.\n self.select_help_button()\n\n def select_help_button(self):\n \"\"\"Toggle that selects help, references, and specification files\"\"\"\n # Clear the Scrolled Text\n self.help_scrolledtext_1.delete(1.0, tk.END)\n # Read the text file and place in the scrolledtext\n try:\n with open(HELP_FILE_LIST[self.help_button_text_index], \"r\") as f:\n for line in iter(f):\n # Skip displaying the commented out lines\n if line[0] == \"#\":\n continue\n else:\n # print(line)\n self.help_scrolledtext_1.insert(tk.INSERT, line)\n except IOError as e:\n self.help_scrolledtext_1.insert(tk.INSERT,\n \"Prime Number Locator\\n{}\"\n .format(e))\n # Update button_1 text to display title of next information\n self.help_button_text_index += 1\n if self.help_button_text_index == len(HELP_BUTTON_TEXT_TUPLE):\n self.help_button_text_index = 0\n next_text = HELP_BUTTON_TEXT_TUPLE[self.help_button_text_index]\n self.help_button_1.config(text=next_text)\n\n def close_help_button(self):\n \"\"\"Close the help information window\"\"\"\n self.destroy()\n\n# Main GUI application\n\n\nclass GUI_Prime_Number_Locator(ttk.Frame):\n\n \"\"\"Locate the prime numbers and display\"\"\"\n\n def __init__(self, parent, start, range_):\n \"\"\"Initilization\"\"\"\n ttk.Frame.__init__(self, parent)\n # print(dir(self))\n # print(dir(parent))\n self.parent = parent\n self.master.title(TITLE_1)\n self.create_widgets(start, range_)\n self.action_on_launch(start, range_)\n\n # ===== Start for Feature Section =====\n def create_widgets(self, start, range_):\n\n # ===== Initialization =====\n # *** Set Int variable for Entry 1\n self.entry_1_integer = tk.IntVar()\n self.entry_1_integer.set(start)\n\n # Set Int variable for Combobox 1\n self.combobox_1_integer = tk.IntVar()\n # Drop down list for combobox 1\n\n self.combobox_1_list = RANGE_TUPLE\n # Range can be based on length of string.\n # Rough passing from sys.argv range to select of range of the combobox\n range_length = len(str(range_)) - 1\n if range_length > 5:\n range_length = 5\n self.combobox_1_integer.set(self.combobox_1_list[range_length])\n\n # Set Str variable for Combobox 2\n self.combobox_2_string = tk.StringVar()\n # Setup Drop down list for combobox 2\n self.combobox_2_list = METHOD_TUPLE\n\n # ([Divide every number\", Skip Even number, etc...])\n self.combobox_2_string.set(self.combobox_2_list[0])\n\n self.progress_bar_int = tk.IntVar()\n self.progress_bar_int.set(0)\n\n # Initialize Start and stop times\n self.time_start = time.time()\n self.time_stop = time.time()\n\n # Create the default options for saving the prime numbers to a file\n # https://tkinter.unpythonic.net/wiki/tkFileDialog # Old V2.7 example\n # -confirmoverwrite, -defaultextension, -filetypes, -initialdir,\n # -initialfile, -parent, -title, or -typevariable\n self.file_opt = options = {}\n options['confirmoverwrite'] = True\n options['defaultextension'] = '.txt'\n options['filetypes'] = [('text files', '.txt'), ('all files', '.*')]\n options['initialdir'] = os.getcwd()\n options['initialfile'] = \"prime_numbers\"\n options['parent'] = self.parent\n options['title'] = \"Save Prime Numbers\"\n # options['typevariable'] = ? string???\n\n # ===== Create styles for use with ttk widgets =====\n self.style = ttk.Style()\n # Change a root style to modify font of all widgets.\n self.style.configure('.', font=FONT)\n\n # ===== Create Widgets =====\n # label_1 - Not used / Reserved\n # self.label_1 = ttk.Label(self, text=\"\", wraplength=500)\n # Label for entry\n self.label_2 = ttk.Label(self, text=LABEL_2_TEXT)\n # Create entry for start integer value. Data is validated\n self.entry_1 = ttk.Entry(self,\n textvariable=self.entry_1_integer,\n validate='key',\n invalidcommand=(self.register(\n self.is_invalid_entry_1),\n '%W', '%P'),\n validatecommand=(self.register(\n self.is_valid_entry_1), '%P')\n )\n # Combobox1 label - Range of numbers for locating primes\n self.label_3 = ttk.Label(self, text=LABEL_3_TEXT)\n # Create Combobox_1\n # As combobox is \"readonly\" no varification of input is required.\n self.combobox_1 = ttk.Combobox(self,\n textvariable=self.combobox_1_integer,\n height=5,\n width=6,\n state=\"readonly\", # readwrite\n values=self.combobox_1_list)\n\n # Combobox2 label - Methods of locating primes\n self.label_4 = ttk.Label(self, text=LABEL_4_TEXT)\n # Create Combobox_2\n # Use register to define functions to validate and process invalid\n self.combobox_2 = ttk.Combobox(\n self,\n textvariable=self.combobox_2_string,\n state=\"readonly\", # readwrite\n values=self.combobox_2_list)\n\n # Labels for each Prime number located\n self.label_5 = ttk.Label(self, text=LABEL_5A_TEXT)\n self.label_6 = ttk.Label(self, text=\"\")\n # Labels for Duration to locate prime numbers\n self.label_7 = ttk.Label(self, text=LABEL_7A_TEXT)\n self.label_8 = ttk.Label(self, text=\"\")\n # Labels for displaying the range\n self.label_9 = ttk.Label(self, text=LABEL_9_TEXT)\n self.label_10 = ttk.Label(self, text=\"\")\n # Scrollect Text # http://www.tutorialspoint.com/python/tk_text.htm\n self.scrolledtext_1 = tkst.ScrolledText(self,\n wrap=tk.WORD,\n height=5,\n bg='lightgreen',\n fg=\"black\",\n font=(FONT))\n #bg='beige',\n # Button Locate\n self.button_1 = ttk.Button(self, text=BUTTON_1_TEXT,\n command=self.button_1_callback)\n # Button Clear\n self.button_2 = ttk.Button(self, text=BUTTON_2_TEXT,\n command=self.button_2_callback)\n # Create progress bar\n self.progress_bar_1 = ttk.Progressbar(self,\n mode='determinate',\n variable=self.progress_bar_int,\n maximum=100)\n # Create a menubar for Saving data, Exit and Help infromation.\n menubar = tk.Menu(self.parent)\n self.parent.config(menu=menubar)\n self.filemenu = tk.Menu(menubar, tearoff=False, font=FONT)\n self.filemenu.add_command(label=\"Save\", command=self.file_save)\n self.filemenu.add_command(\n label=\"Save As...\", command=self.file_save_as)\n self.filemenu.add_separator()\n self.filemenu.add_command(label=\"Exit\", command=self.file_exit)\n menubar.add_cascade(label=\"File\", menu=self.filemenu, font=FONT)\n self.helpmenu = tk.Menu(menubar, tearoff=False, font=FONT)\n self.helpmenu.add_command(label=\"Help\", command=self.help_launch)\n self.helpmenu.add_command(label=\"About...\", command=self.help_about)\n menubar.add_cascade(label=\"Help\", menu=self.helpmenu, font=FONT)\n\n # This will disable the item at index 0 on the File menu. i.e. \"Save\"\n self.filemenu.entryconfig(0, state=tk.DISABLED)\n # self.filemenu.entryconfig(0, state=tk.NORMAL)\n\n # ===== Add widgets using grid method to the frame =====\n # self.label_1.grid(row=1, column=0, columnspan=5) # Unused\n self.label_2.grid(row=2, column=0, padx=5, pady=5, sticky=\"e\")\n self.entry_1.grid(row=2, column=1, padx=5, pady=5, sticky=\"w\")\n self.label_3.grid(row=2, column=2, padx=5, pady=5, sticky=\"e\")\n self.combobox_1.grid(row=2, column=3, padx=5, pady=5, sticky=\"w\")\n self.label_4.grid(row=2, column=4, padx=5, pady=5, sticky=\"e\")\n self.combobox_2.grid(row=2, column=5, padx=5, pady=5, sticky=\"w\")\n\n self.label_5.grid(row=3, column=0, padx=5, pady=5, sticky=\"e\")\n self.label_6.grid(row=3, column=1, padx=5, pady=5, sticky=\"w\")\n\n self.label_7.grid(row=3, column=2, padx=5, pady=5, sticky=\"e\")\n self.label_8.grid(row=3, column=3, padx=5, pady=5, sticky=\"w\")\n\n self.label_9.grid(row=0, column=1, columnspan=2, sticky=\"e\")\n self.label_10.grid(row=0, column=3, columnspan=2, sticky=\"w\")\n\n self.button_1.grid(row=3, column=4, padx=5, pady=5)\n self.button_2.grid(row=3, column=5, padx=5, pady=5)\n self.progress_bar_1.grid(row=6, column=0, columnspan=6,\n padx=5, pady=5, sticky=\"we\")\n # Don't display the progress bar at this stage\n self.progress_bar_1.grid_forget()\n\n self.scrolledtext_1.grid(row=1, column=0, padx=5, pady=5, columnspan=6)\n\n def action_on_launch(self, start, range_):\n \"\"\"Actions on initial launching of the application\"\"\"\n # Not used / Reserved.\n pass\n\n # ===== Menu bar call backs =====\n def help_launch(self):\n \"\"\"Menubar. Help. The HelpFrame class to display the help\"\"\"\n subFrame = HelpFrame()\n\n def help_about(self):\n \"\"\"Menubar. Help. Use a messsage box to display the About info\"\"\"\n tkmsgbox.showinfo(MSGBOX_TITLE, MSGBOX_TEXT)\n\n def file_save(self):\n \"\"\"Using the defaults blindly perform a file save\"\"\"\n # \"end-1c\" The -1c strips the newline at the end of the text\n text = self.scrolledtext_1.get(\"1.0\", tk.END + \"-1c\")\n # print(text)\n # Build the path/filename/extension\n # print(dir(os))\n # print(os.sep)\n file_path_name_ext = (\"{}{}{}{}\"\n .format(self.file_opt['initialdir'],\n os.sep,\n self.file_opt['initialfile'],\n self.file_opt['defaultextension']))\n\n # print(file_path_name_ext)\n try:\n with open(file_path_name_ext, \"w\") as f:\n f.write(text)\n except:\n print(\"Failed to save\")\n return\n\n # Disable Save menu item after perfroming the save\n self.filemenu.entryconfig(0, state=tk.DISABLED)\n\n # print(dir(tkfiledialog))\n # data_file = tkfiledialog.askopenfile()\n # data_file_path_name = data_file.name\n # print(data_file_path_name)\n # print(dir(file_path_name))\n # asksaveasfile\n\n def file_save_as(self):\n \"\"\"Open dialog to save file as. Update changes from default values\"\"\"\n # \"end-1c\" The -1c strips the newline at the end of the text\n text = self.scrolledtext_1.get(\"1.0\", tk.END + \"-1c\")\n # asksaveasfile returns and opened file. asksaveasfilename just\n # filename\n data_file = tkfiledialog.asksaveasfile(mode='w', **self.file_opt)\n # if directory path, or filename or extenxion change then remember\n # Seperate data_file.name into path, name, and extension\n # print(data_file.name)\n try:\n file_path_name_ext = data_file.name\n except AttributeError as e:\n # 'NoneType' object has no attribute 'name'\n # print(\"Cancelled: {}\".format(e))\n return\n\n # Returned the files /path/name.ext which may now be different from\n # the self.file_opt values for initialdir, initialfile,\n # defaultextension\n # print(file_path_name_ext)\n path, tail = os.path.split(file_path_name_ext)\n # print(path, tail)\n filename, ext = os.path.splitext(tail)\n # print(path, filename, ext)\n # Update the default values for dir, file and extension\n self.file_opt.update(initialdir=path)\n self.file_opt.update(initialfile=filename)\n self.file_opt.update(defaultextension=ext)\n\n # self.file_opt(defaultextension = ext)\n # print(dir(self.file_opt))\n # print(self.file_opt.keys())\n # print(self.file_opt.values())\n # print(self.file_opt['defaultextension'])\n\n # TODO: If defaultextension changes then update the filetypes\n # options['filetypes'] = [('text files', '.txt'), ('all files', '.*')]\n # print(dir(data_file))\n\n data_file.write(text)\n data_file.close()\n # Enable the Save menu\n self.filemenu.entryconfig(0, state=tk.DISABLED)\n\n def file_exit(self):\n \"\"\"Menubar. File exit to end the program\"\"\"\n sys.exit()\n\n # ===== Widget call backs =====\n def is_valid_entry_1(self, txt):\n \"\"\"Check that text is only numeric in entry_1\"\"\"\n if txt.isdigit():\n return True\n else:\n return False\n\n def is_invalid_entry_1(self, widget_name, txt):\n \"\"\"Called whenever is_valid_entry_1() returns false\"\"\"\n # non-lowercase letters have been prevented from being added to entry_1\n # Make the bell warning sound\n # >>> [m for m in dir(str) if m.startswith('is')]\n # ['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle',\n # 'isupper']\n widget = self.nametowidget(widget_name)\n widget.bell()\n widget.focus_set()\n\n def button_1_callback(self):\n \"\"\"Start the prime number search with progress bar\"\"\"\n # Get the currently selected method to determine which method to call\n method_index = self.combobox_2.current()\n\n # Two methods to obtain values of the entry and comboboxes. E.g.:\n # print(self.entry_1.get()) # Get directly\n # print(self.entry_1_integer.get()) # Get from variable\n # print(self.combobox_1.get())\n # print(self.combobox_1_integer.get())\n\n # Set starting point of progress bar. From 0 to maximum E.g. 100\n self.progress_bar_int.set(0)\n # Display the progress bar\n self.progress_bar_1.grid(row=6, column=0, columnspan=7,\n padx=5, pady=5, sticky=\"we\")\n # Set the label to display each prime number found\n self.label_5.config(text=LABEL_5A_TEXT)\n self.label_6.config(text=\"\")\n\n self.label_7.config(text=LABEL_7A_TEXT)\n\n # Clear the duration\n self.label_8.config(text=\"\")\n # Get the start time\n self.time_start = time.time()\n\n # Get the last integer of the range\n end_integer = (self.entry_1_integer.get() +\n self.combobox_1_integer.get())\n # Display the range\n self.label_10.config(text=\"{} to {}\"\n .format(self.entry_1_integer.get(),\n end_integer - 1))\n\n # ==== Select the method and call function to locate prime numbers ====\n if method_index == 0:\n # Call the prime number method and pass start and end\n primes = self.prime_number_method_0(self.entry_1_integer.get(),\n end_integer)\n if method_index == 1:\n # Call the prime number method and pass start and end\n primes = self.prime_number_method_1(self.entry_1_integer.get(),\n end_integer)\n\n if method_index == 2:\n # Call the prime number method and pass start and end\n primes = self.prime_number_method_2(self.entry_1_integer.get(),\n end_integer)\n if method_index == 3:\n # Call the prime number method and pass start and end\n primes = self.prime_number_method_3(self.entry_1_integer.get(),\n end_integer)\n\n if method_index == 4:\n # Call the prime number method and pass start and end\n primes = self.prime_number_method_4(self.entry_1_integer.get(),\n end_integer)\n\n if method_index == 5:\n # Call the prime number method and pass start and end\n primes = self.prime_number_method_5(self.entry_1_integer.get(),\n end_integer)\n\n # ===== On completing locating primes =====\n # Register the time completed\n self.time_stop = time.time()\n # Display the duration.\n self.label_7.config(text=LABEL_7B_TEXT)\n self.label_8.config(text=\"{0:.3f} secs\"\n .format(self.time_stop - self.time_start))\n\n # Change the label to give total of prime numbers found\n self.label_5.config(text=LABEL_5B_TEXT)\n self.label_6.config(text=\"{}\".format(len(primes)))\n\n # Hide the progress bar\n self.progress_bar_1.grid_forget()\n # As the data has changed enable the ability to do a save\n self.filemenu.entryconfig(0, state=tk.NORMAL)\n\n def button_2_callback(self):\n \"\"\"Clear the Scrolled Text\"\"\"\n self.scrolledtext_1.delete(1.0, tk.END)\n\n def prime_number_method_0(self, start_integer, end_integer):\n \"\"\"\n Locate prime numbers using method 0.\n Designed to be CPU intensive. Iterates through every number.\n \"\"\"\n # Locate prime numbers and place them in a list\n prime_number_list = []\n for i in range(start_integer, end_integer):\n # ==== GUI updating =====\n # Increment the progress on the Progress bar. Default is 1\n self.progress_bar_1.step(100 / (end_integer - start_integer))\n # Duration. Progress in seconds\n self.label_8.config(text=\"{0:.0f} secs\"\n .format(time.time() - self.time_start))\n # Refresh the GUI\n self.update_idletasks()\n # ==== End of GUI Updating =====\n\n # ==== Method of locating prime numbers =====\n # METHOD: Divide every number. Excessively recursive.\n count = 0\n for j in range(1, i):\n # print(\"i {} mod j {} = {}\".format(i, j, i % j))\n if i % j == 0:\n count += 1\n if count == 1:\n # A count of only 1 indicates a prime number\n # Place the located prime into the list\n prime_number_list.append(i)\n # ===== GUI Updating as each prime number is located =====\n # Display the located prime number\n self.label_6.config(text=str(i))\n # Insert latest found prime number in the Scrolled Text box\n self.scrolledtext_1.insert(tk.END, \"{}, \"\n .format(prime_number_list[-1]))\n # ===== End of GUI updating =====\n\n # print(prime_number_list)\n # print(len(prime_number_list))\n return prime_number_list\n\n def prime_number_method_1(self, start_integer, end_integer):\n \"\"\"\n Locate prime numbers using method 1.\n Designed to be CPU intensive. Skips the even numbers.\n \"\"\"\n # Locate prime numbers and place them in a list\n prime_number_list = []\n\n # If required, cheat and manually add the 2.\n if start_integer <= 2:\n prime_number_list.append(2)\n # Insert the prime number 2 in the Scrolled Text box\n self.scrolledtext_1.insert(tk.END, \"{}, \"\n .format(prime_number_list[-1]))\n\n for i in range(start_integer, end_integer):\n # ==== GUI updating =====\n # Increment the progress on the Progress bar. Default is 1\n self.progress_bar_1.step(100 / (end_integer - start_integer))\n # Duration. Progress in seconds\n self.label_8.config(text=\"{0:.0f} secs\"\n .format(time.time() - self.time_start))\n # Refresh the GUI\n self.update_idletasks()\n # ==== End of GUI Updating =====\n\n # ==== Method of locating prime numbers =====\n # METHOD: Skip the even numbers. Still excessively recursive.\n # Skip all even numbers\n if i % 2 == 0:\n continue\n\n count = 0\n for j in range(1, i):\n if i % j == 0:\n count += 1\n\n if count == 1:\n prime_number_list.append(i)\n\n # ===== GUI Updating as each prime number is located =====\n # Display the located prime number\n self.label_6.config(text=str(i))\n # Insert latest found prime number in the Scrolled Text box\n self.scrolledtext_1.insert(tk.END, \"{}, \"\n .format(prime_number_list[-1]))\n # ===== End of GUI updating =====\n return prime_number_list\n\n def prime_number_method_2(self, start_integer, end_integer):\n \"\"\"\n Locate prime numbers using method 2. Module6 remainders 1 and 5\n \"\"\"\n # Locate prime numbers and place them in a list\n prime_number_list = []\n\n # Cheat, If required, and manually add the 2 & 3.\n if start_integer < 3:\n prime_number_list.append(2)\n # Insert the prime number 2 in the Scrolled Text box\n self.scrolledtext_1.insert(tk.END, \"{}, \"\n .format(prime_number_list[-1]))\n prime_number_list.append(3)\n # Insert the prime number 2 in the Scrolled Text box\n self.scrolledtext_1.insert(tk.END, \"{}, \"\n .format(prime_number_list[-1]))\n if start_integer == 3:\n prime_number_list.append(3)\n # Insert the prime number 3 in the Scrolled Text box\n self.scrolledtext_1.insert(tk.END, \"{}, \"\n .format(prime_number_list[-1]))\n\n for i in range(start_integer, end_integer):\n # ==== GUI updating =====\n # Increment the progress on the Progress bar. Default is 1\n self.progress_bar_1.step(100 / (end_integer - start_integer))\n # Duration. Progress in seconds\n self.label_8.config(text=\"{0:.0f} secs\"\n .format(time.time() - self.time_start))\n # Refresh the GUI\n self.update_idletasks()\n # ==== End of GUI Updating =====\n\n # ==== Method of locating prime numbers =====\n # METHOD: Skip all modulo 6 that do not have a remainder of 1 or 5\n if i % 6 in [0, 2, 3, 4]:\n continue\n count = 0\n\n for j in range(1, i):\n if i % j == 0:\n count += 1\n\n if count == 1:\n prime_number_list.append(i)\n\n # ===== GUI Updating as each prime number is located =====\n # Display the located prime number\n self.label_6.config(text=str(i))\n # Insert latest found prime number in the Scrolled Text box\n self.scrolledtext_1.insert(tk.END, \"{}, \"\n .format(prime_number_list[-1]))\n # ===== End of GUI updating =====\n return prime_number_list\n\n def prime_number_method_3(self, start_integer, end_integer):\n \"\"\"\n Locate prime numbers using method 3. Minimal Recursion.\n \"\"\"\n # Locate prime numbers and place them in a list\n prime_number_list = []\n if start_integer < 2:\n start_integer = 2\n for i in range(start_integer, end_integer):\n # ==== GUI updating =====\n # Increment the progress on the Progress bar. Default is 1\n self.progress_bar_1.step(100 / (end_integer - start_integer))\n # Duration. Progress in seconds\n self.label_8.config(text=\"{0:.0f} secs\"\n .format(time.time() - self.time_start))\n # Refresh the GUI\n self.update_idletasks()\n # ==== End of GUI Updating =====\n\n # ==== Method of locating prime numbers =====\n # METHOD: Minimal Recursion\n for j in range(2, int(math.sqrt(i) + 1)):\n if i % j == 0:\n break\n\n else:\n prime_number_list.append(i)\n\n # ===== GUI Updating as each prime number is located =====\n # Display the located prime number\n self.label_6.config(text=str(i))\n # Insert latest found prime number in the Scrolled Text box\n self.scrolledtext_1.insert(tk.END, \"{}, \"\n .format(prime_number_list[-1]))\n # ===== End of GUI updating =====\n return prime_number_list\n\n\n def prime_number_method_4(self, start_integer, end_integer):\n \"\"\"\n Locate prime numbers using method 4. \n Note that sympy.primerange returns a list, but this function sets a\n one integer range. so not as fast as asking for a list.\n \n https://www.sympy.org\n list(sympy.primerange(start_integer, end_integer)\n import sympy # Computer algebra system (CAS) in Python\n SymPy is a Python library for symbolic mathematics.\n 'isprime' 'prevprime', nextprime 'prime', 'primefactors', 'primenu', \n 'primeomega', 'primepi', 'primerange',\n \n airyaiprime, airybiprime, is_mersenne_prime, mathieucprime, mathieusprime\n mersenne_prime_exponent randprime, ratsimpmodprime\n \"\"\"\n # Locate prime numbers and place them in a list\n prime_number_list = []\n if start_integer < 2:\n start_integer = 2\n for i in range(start_integer, end_integer):\n # ==== GUI updating =====\n # Increment the progress on the Progress bar. Default is 1\n self.progress_bar_1.step(100 / (end_integer - start_integer))\n # Duration. Progress in seconds\n self.label_8.config(text=\"{0:.0f} secs\"\n .format(time.time() - self.time_start))\n # Refresh the GUI\n self.update_idletasks()\n # ==== End of GUI Updating =====\n\n # ==== Method of locating prime numbers =====\n # METHOD: Using sympy.primerange\n #for j in range(2, int(math.sqrt(i) + 1)):\n # if i % j == 0:\n # break\n\n temp_list = list(sympy.primerange(i, i+1))\n if len(temp_list) == 0:\n continue\n \n else:\n prime_number_list.append(temp_list[0])\n\n # ===== GUI Updating as each prime number is located =====\n # Display the located prime number\n self.label_6.config(text=str(i))\n # Insert latest found prime number in the Scrolled Text box\n self.scrolledtext_1.insert(tk.END, \"{}, \"\n .format(prime_number_list[-1]))\n # ===== End of GUI updating =====\n return prime_number_list\n\n\n def prime_number_method_5(self, start_integer, end_integer):\n \"\"\"\n Locate prime numbers using method 4. \n Note that sympy.primerange returns a list, but this function sets a\n one integer range. so not as fast as asking for a list.\n \n https://www.sympy.org\n list(sympy.primerange(start_integer, end_integer)\n import sympy # Computer algebra system (CAS) in Python\n SymPy is a Python library for symbolic mathematics.\n 'isprime' 'prevprime', nextprime 'prime', 'primefactors', 'primenu', \n 'primeomega', 'primepi', 'primerange',\n \n airyaiprime, airybiprime, is_mersenne_prime, mathieucprime, mathieusprime\n mersenne_prime_exponent randprime, ratsimpmodprime\n \"\"\"\n #print( start_integer, end_integer)\n # Locate prime numbers and place them in a list\n #prime_number_list = []\n if start_integer < 2:\n start_integer = 2\n \n prime_number_list = list(sympy.primerange(start_integer, end_integer)) \n \n #print(type(prime_number_list)) # list\n #print(len(prime_number_list)) # 6\n #self.label_6.config(text=str(i))\n # Insert latest found prime number in the Scrolled Text box\n \n for prime_number in prime_number_list:\n self.scrolledtext_1.insert(tk.END, \"{}, \"\n .format(prime_number))\n\n \n return prime_number_list \n \n \"\"\" \n for i in range(start_integer, end_integer):\n # ==== GUI updating =====\n # Increment the progress on the Progress bar. Default is 1\n self.progress_bar_1.step(100 / (end_integer - start_integer))\n # Duration. Progress in seconds\n self.label_8.config(text=\"{0:.0f} secs\"\n .format(time.time() - self.time_start))\n # Refresh the GUI\n self.update_idletasks()\n # ==== End of GUI Updating =====\n\n # ==== Method of locating prime numbers =====\n # METHOD: Using sympy.primerange\n #for j in range(2, int(math.sqrt(i) + 1)):\n # if i % j == 0:\n # break\n\n\n if len(temp_list) == 0:\n continue\n \n else:\n prime_number_list.append(temp_list[0])\n\n # ===== GUI Updating as each prime number is located =====\n # Display the located prime number\n self.label_6.config(text=str(i))\n # Insert latest found prime number in the Scrolled Text box\n self.scrolledtext_1.insert(tk.END, \"{}, \"\n .format(prime_number_list[-1]))\n # ===== End of GUI updating =====\n return prime_number_list\n \"\"\"\n\n\nif __name__ == \"__main__\":\n \"\"\"Check for command line arguments.\"\"\"\n print(TITLE_2)\n\n # Check for start integer\n if len(sys.argv) > 1:\n if sys.argv[1].isdigit():\n start = int(sys.argv[1])\n else:\n print(\"Prime number locator options: [start integer] and [range]\")\n sys.exit(1)\n else:\n start = 100000 # Default value of 100000 to take time\n\n # Check for range\n if len(sys.argv) > 2:\n if sys.argv[2].isdigit():\n range_ = int(sys.argv[2])\n else:\n range_ = 100\n else:\n range_ = 100\n\n # Launch tkinter GUI.\n root = tk.Tk()\n\n # Force the geometry of the GUI width x height + position x + position y\n # root.geometry('1000x180+100+100')\n # Open the GUI Application class. Use grid to place in different rows\n # Add the sticky=\"we\" - Expands the grey background area\n main_gui = (GUI_Prime_Number_Locator(root, start, range_)\n .grid(row=0, column=0, sticky=\"we\"))\n\n root.mainloop()\n\n'''\nNotes:\nProgress Bar:\nYou must be using: self.pgBar.step(x) where 'x' is the amount to be increased\nin progressbar. For this to get updated in your UI you have to put\nself.update_idletasks() after every self.pgBar.step(x) statement.\n\n 1 2 3 4 5 6 7 7\n1234567890123456789012345678901234567890123456789012345678901234567890123456789\n'''\n"} {"blob_id": "cdf6172cdbd928db735048ba282a64addcf214a6", "repo_name": "akimi-yano/algorithm-practice", "path": "/lc/1963.MinimumNumberOfSwapsToMake.py", "length_bytes": 2188, "score": 3.796875, "int_score": 4, "content": "# 1963. Minimum Number of Swaps to Make the String Balanced\n# Medium\n\n# 53\n\n# 6\n\n# Add to List\n\n# Share\n# You are given a 0-indexed string s of even length n. The string consists of exactly n / 2 opening brackets '[' and n / 2 closing brackets ']'.\n\n# A string is called balanced if and only if:\n\n# It is the empty string, or\n# It can be written as AB, where both A and B are balanced strings, or\n# It can be written as [C], where C is a balanced string.\n# You may swap the brackets at any two indices any number of times.\n\n# Return the minimum number of swaps to make s balanced.\n\n \n\n# Example 1:\n\n# Input: s = \"][][\"\n# Output: 1\n# Explanation: You can make the string balanced by swapping index 0 with index 3.\n# The resulting string is \"[[]]\".\n# Example 2:\n\n# Input: s = \"]]][[[\"\n# Output: 2\n# Explanation: You can do the following to make the string balanced:\n# - Swap index 0 with index 4. s = \"[]][[]\".\n# - Swap index 1 with index 5. s = \"[[][]]\".\n# The resulting string is \"[[][]]\".\n# Example 3:\n\n# Input: s = \"[]\"\n# Output: 0\n# Explanation: The string is already balanced.\n \n\n# Constraints:\n\n# n == s.length\n# 2 <= n <= 106\n# n is even.\n# s[i] is either '[' or ']'.\n# The number of opening brackets '[' equals n / 2, and the number of closing brackets ']' equals n / 2.\n\n# This solution works:\n\nclass Solution:\n def minSwaps(self, s: str) -> int:\n '''\n []][]]][[[[] : [1, 0, -1, 0, -1, -2, -3, -2, -1, 0, 1, 0]\n \n v--swap--v\n []][]]][[[[] : [1, 0, -1, 0, -1, -2, -3, -2, -1, 0, 1, 0]\n \n \n [[][]]][[[]] : [1, 2, 1, 2, 1, 0, -1, 0, 1, 2, 1, 0]\n \n v v\n [[][]]][[[]] : [1, 2, 1, 2, 1, 0, -1, 0, 1, 2, 1, 0]\n\n \n \n \n ][][\n \n []][\n [[]]\n \n \n ]]][[[\n []]][[\n [[[]]]\n [[][]]\n '''\n cur = 0\n least = 0\n for c in s:\n if c == '[':\n cur += 1\n else:\n cur -= 1\n least = min(least, cur)\n # gotta do ceiling instead of flooring - think of both odd and even case by writng down the examples\n return (-least+1)//2"} {"blob_id": "b2065a382c36d84100497a77de8e1421394fdfae", "repo_name": "brain-bzh/elu616-introtoai", "path": "/session6/lab/rl.py", "length_bytes": 5948, "score": 3.546875, "int_score": 4, "content": "import numpy as np\nimport pickle\n\n## Part 1 - Linear Model Training using SGD\n# This part can be skipped unless you want to understand the details of how the linear model is being trained using Stochastic Gradient Descent. \n# A starting point can be found here : https://medium.com/deeplearningschool/2-1-linear-regression-f782ada81a53\n# However there are many online ressources on the topic. \n\nclass NLinearModels(object):\n def __init__(self,x_example,number_of_regressors=4,learning_rate = 0.1):\n shape_input = x_example.reshape(-1).shape[0]\n limit = np.sqrt(6 / (shape_input + number_of_regressors)) \n self.W = np.random.uniform(-limit,limit, size=(shape_input,number_of_regressors)) #HE INITIALIZATION\n #self.W = np.ones((shape_input,number_of_regressors))/10 #HE INITIALIZATION\n self.bias = np.zeros(number_of_regressors)\n self.learning_rate = learning_rate\n \n def forward(self,x):\n return x.dot(self.W) + self.bias\n\n def predict(self,x):\n x = np.array(x)\n x = x.reshape(x.shape[0],-1)\n return self.forward(x)\n\n def cost(self,y_hat,y):\n return ((y_hat-y)**2).mean(axis=0)\n \n def backward(self,x,y_hat,y):\n m = y_hat.shape[0]\n dl = 2*(y_hat-y)/m\n self.bias_gradient = np.sum(dl,axis=0) \n self.W_gradient = x.T.dot(dl)/m \n\n def train_on_batch(self,_input,target):\n _input = np.array(_input)\n y = np.array(target)\n x = _input.reshape(_input.shape[0],-1)\n y_hat = self.forward(x)\n cost = self.cost(y_hat,y).sum()\n self.backward(x,y_hat,y)\n self.update_weights()\n return cost\n\n def update_weights(self):\n\n self.W -= self.learning_rate * self.W_gradient \n self.bias -= self.learning_rate * self.bias_gradient\n\n def load(self):\n W = np.load(open('save_rl/W.npy',\"rb\"))\n bias = np.load(open('save_rl/bias.npy',\"rb\"))\n self.W = W\n self.bias = bias\n\n def save(self):\n np.save(open(\"save_rl/W.npy\",\"wb\"),self.W)\n np.save(open(\"save_rl/bias.npy\",\"wb\"),self.bias)\n\n## Part 2 - Experience Replay\n## This part has to be read and understood in order to code the main.py file. \n\nclass ExperienceReplay(object):\n \"\"\"\n During gameplay all the experiences < s, a, r, s\u2019 > are stored in a replay memory. \n In training, batches of randomly drawn experiences are used to generate the input and target for training.\n \"\"\"\n def __init__(self, max_memory=100, discount=.9):\n \"\"\"\n Setup\n max_memory: the maximum number of experiences we want to store\n memory: a list of experiences\n discount: the discount factor for future experience\n \n In the memory the information whether the game ended at the experience is stored seperately in a nested array\n [...\n [experience, game_over]\n [experience, game_over]\n ...]\n \"\"\"\n self.max_memory = max_memory\n self.memory = list()\n self.discount = discount\n\n def remember(self, experience, game_over):\n #Save an experience to memory\n self.memory.append([experience, game_over])\n #We don't want to store infinite memories, so if we have too many, we just delete the oldest one\n if len(self.memory) > self.max_memory:\n del self.memory[0]\n\n def get_batch(self, model, batch_size=10):\n \n #How many experiences do we have?\n len_memory = len(self.memory)\n \n #Calculate the number of actions that can possibly be taken in the game\n num_actions = 4\n \n #Dimensions of the game field\n env_dim = list(self.memory[0][0][0].shape)\n env_dim[0] = min(len_memory, batch_size)\n \n \n #We want to return an input and target vector with inputs from an observed state...\n inputs = np.zeros(env_dim)\n #...and the target r + gamma * max Q(s\u2019,a\u2019)\n #Note that our target is a matrix, with possible fields not only for the action taken but also\n #for the other possible actions. The actions not take the same value as the prediction to not affect them\n Q = np.zeros((inputs.shape[0], num_actions))\n \n #We draw experiences to learn from randomly\n for i, idx in enumerate(np.random.randint(0, len_memory,\n size=inputs.shape[0])):\n \"\"\"\n Here we load one transition from memory\n state_t: initial state s\n action_t: action taken a\n reward_t: reward earned r\n state_tp1: the state that followed s\u2019\n \"\"\"\n# idx = -1\n state, action_t, reward_t, state_tp1 = self.memory[idx][0]\n #We also need to know whether the game ended at this state\n game_over = self.memory[idx][1]\n\n #add the state s to the input\n inputs[i:i+1] = state\n # First we fill the target values with the predictions of the model.\n # They will not be affected by training (since the training loss for them is 0)\n Q[i] = model.predict([state])[0]\n\n \"\"\"\n If the game ended, the expected reward Q(s,a) should be the final reward r.\n Otherwise the target value is r + gamma * max Q(s\u2019,a\u2019)\n \"\"\"\n #if the game ended, the reward is the final reward\n if game_over: # if game_over is True\n Q[i, action_t] = reward_t\n else:\n # r + gamma * max Q(s\u2019,a\u2019)\n next_round = model.predict([state_tp1])[0]\n Q[i, action_t] = reward_t + self.discount*np.max(next_round)\n return inputs, Q\n\n def load(self):\n self.memory = pickle.load(open(\"save_rl/memory.pkl\",\"rb\"))\n def save(self):\n pickle.dump(self.memory,open(\"save_rl/memory.pkl\",\"wb\"))\n"} {"blob_id": "f28774937fa79b7531329155bb7ffe7f37064122", "repo_name": "selvendiranj-zz/pyth-coin", "path": "/python/test_pow.py", "length_bytes": 1896, "score": 3.5625, "int_score": 4, "content": "import hashlib\nimport json\n\n\ndef hash(block):\n \"\"\"\n Creates a SHA-256 hash of a Block\n\n :param block: Block\n \"\"\"\n\n # We must make sure that the Dictionary is Ordered, or we'll have inconsistent hashes\n block_string = json.dumps(block, sort_keys=True).encode()\n return hashlib.sha256(block_string).hexdigest()\n\n\ndef get_proof_of_work(last_block):\n \"\"\"\n Simple Proof of Work Algorithm:\n\n - Find a number p' such that hash(pp') contains leading 4 zeroes\n - Where p is the previous proof, and p' is the new proof\n\n :param last_block: last Block\n :return: \n \"\"\"\n\n last_proof = last_block['proof']\n last_hash = hash(last_block)\n\n proof = 0\n while is_proof_valid(last_proof, proof, last_hash) is False:\n proof += 1\n\n return proof\n\n\ndef is_proof_valid(last_proof, proof, last_hash):\n \"\"\"\n Validates the Proof\n\n :param last_proof: Previous Proof\n :param proof: Current Proof\n :param last_hash: The hash of the Previous Block\n :return: True if correct, False if not.\n\n \"\"\"\n\n guess = f'{last_proof}{proof}{last_hash}'.encode()\n guess_hash = hashlib.sha256(guess).hexdigest()\n\n \"\"\"print('\\n')\n print('last_proof:', last_proof)\n print('proof:', proof)\n print('last_hash:', last_hash)\n print('guess:', f'{last_proof}{proof}{last_hash}')\n print('encoded_guess:', guess)\n print('hashed_guess:', guess_hash)\"\"\"\n\n return guess_hash[:4] == \"0000\"\n\n\nlastBlock = {\n \"index\": 1,\n \"timestamp\": 1506057125.900785,\n \"transactions\": [{\n \"sender\": \"8527147fe1f5426f9dd545de4b27ee00\",\n \"recipient\": \"a77f5cdfa2934df3954a5c7c7da5df1f\",\n \"amount\": 5\n }],\n \"proof\": 324984774000,\n \"previous_hash\": \"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824\"\n}\n\nproof = get_proof_of_work(lastBlock)\nprint('proof:', proof)\n"} {"blob_id": "59b9c9b36be8d0bb2acde394d83ffae0c0e4143c", "repo_name": "Vijay1234-coder/data_structure_plmsolving", "path": "/Dynamic Programming/LCS(longestCommonSubsequence)/sequncePatternMatching.py", "length_bytes": 729, "score": 3.65625, "int_score": 4, "content": "'''quse'''\n'''Sequence Pattern Matching \na: \"AXY\"\nb: \"ABGXJDGY\"\n\nQ: if a is subsequnce of b return True else return False\n'''\n''' Aproach would be first find LCS of a and b then if lcs == len(a) then True '''\n\n\ndef lcs(x,y,n,m):\n t = [[-1 for j in range(n + 1)] for i in range(m + 1)]\n # Base Case\n\n for i in range(0,m+1):\n for j in range(0,n+1):\n if i==0 or j==0:\n t[i][j]=0\n elif (x[j - 1] == y[i - 1]):\n t[i][j] = 1 + t[i-1][j-1]\n else:\n t[i][j]= max(t[i-1][j],t[i][j-1])\n\n if t[m][n] == min(len(x),len(y)):\n return True\n else:\n return False\n\n\n\n\n\n\n\n\nx= \"AXY\"\ny= \"ABGXJDGY\"\nn=len(x)\nm=len(y)\n\nprint(lcs(x,y,n,m))\n"} {"blob_id": "e8a71bbfd5a755f85d3935d33b7f53a150249025", "repo_name": "kazzastic/CV", "path": "/maze/mazelib/solve/BacktrackingSolver.py", "length_bytes": 1700, "score": 3.625, "int_score": 4, "content": "\nfrom random import choice\nimport cython\nif not cython.compiled:\n from mazelib.solve.MazeSolveAlgo import MazeSolveAlgo\n\n\nclass BacktrackingSolver(MazeSolveAlgo):\n \"\"\"\n The Algorithm\n\n 1. Pick a random direction and follow it\n 2. Backtrack if and only if you hit a dead end.\n \"\"\"\n def __init__(self, prune=True):\n self.prune = prune\n\n def _solve(self):\n solution = []\n\n # a first move has to be made\n current = self.start\n if self._on_edge(self.start):\n current = self._push_edge(self.start)\n solution.append(current)\n\n # pick a random neighbor and travel to it, until you're at the end\n while not self._within_one(solution[-1], self.end):\n ns = self._find_unblocked_neighbors(solution[-1])\n\n # do no go where you've just been\n if len(ns) > 1 and len(solution) > 2:\n if solution[-3] in ns:\n ns.remove(solution[-3])\n\n nxt = choice(ns)\n solution.append(self._midpoint(solution[-1], nxt))\n solution.append(nxt)\n\n if self.prune:\n solution = self._prune_solution(solution)\n\n solution = self._fix_entrances(solution)\n\n return [solution]\n\n def _fix_entrances(self, solution):\n \"\"\"Ensure the start and end are appropriately placed in the solution.\"\"\"\n # prune if start is found in solution\n if self.start in solution:\n i = solution.index(self.start)\n solution = solution[i+1:]\n\n # fix solution so it doesn't overlap endpoints\n if not self._on_edge(self.end):\n [solution] = [solution[:-1]]\n\n return solution\n"} {"blob_id": "744b71fd326ae4e952d72460a67c645c70741dc7", "repo_name": "prashanth018/Boolean-WildCard", "path": "/SearchEngine.py", "length_bytes": 9994, "score": 3.78125, "int_score": 4, "content": "Docs = ['austen-emma.txt','austen-persuasion.txt','austen-sense.txt','blake-poems.txt','bryant-stories.txt','burgess-busterbrown.txt','carroll-alice.txt','chesterton-ball.txt','chesterton-brown.txt','chesterton-thursday.txt','edgeworth-parents.txt','milton-paradise.txt','shakespeare-caesar.txt','shakespeare-hamlet.txt','shakespeare-macbeth.txt','whitman-leaves.txt']\r\n\r\nimport nltk\r\nimport nltk.tokenize\r\nfrom nltk.stem.porter import *\r\nfrom nltk.tokenize import word_tokenize\r\nimport Tkinter as tk\r\nfrom Tkinter import StringVar\r\nfrom Tkinter import IntVar\r\nimport re\r\n\r\ndef tok(stri): #function to know if a given substring is a token or AND/NOT/OR\r\n if stri==\"AND\" or stri==\"NOT\" or stri==\"OR\":\r\n return False\r\n return True\r\n\r\ndef noting(l): #function to complement of a given list documents\r\n ans=[] #l is a list\r\n for i in range(len(Docs)):\r\n if i not in l:\r\n ans.append(i)\r\n return ans #ans is a complemented list of l\r\n\r\ndef anding(l,r): #anding finds the intersection of 2 lists\r\n ans=[]\r\n for i in range(len(l)):\r\n if l[i] in r:\r\n ans.append(l[i])\r\n return ans #ans contains common elemets of list l and r\r\n\r\ndef oring(l,r): #oring finds the union of 2 lists\r\n ans=[]\r\n ans=l+r\r\n ans = list(set(ans))\r\n return ans #ans returns the union list of l and r\r\n\r\n\r\ndictionary ={} #dictionary here, is used as a map from tokenized, lematized, string to list of document in which it occurs \r\ni=0\r\nj=0\r\ngut = nltk.corpus.gutenberg\r\nst = PorterStemmer() #stemming used here is porter's stemmer\r\n\r\nfor i in range(len(Docs)): \r\n cor = gut.words(Docs[i])\r\n corp = []\r\n for j in range(len(cor)):\r\n l = word_tokenize(cor[j]) #tokenizing the words\r\n for k in range(len(l)):\r\n corp.append(l[k])\r\n l=[]\r\n for j in range(len(corp)): \r\n wd = st.stem(corp[j]) #stemming the words\r\n \r\n if wd.lower() in dictionary and not (i in dictionary[wd.lower()]): #if the word is in dictionary and if the document id doesn't already exist in the list then append the doc id to the list\r\n dictionary[wd.lower()].append(i) #case-lowering the word and appending it to dictionary \r\n elif wd.lower() not in dictionary: #if word is not in the dictionary\r\n dictionary[wd.lower()]=[] #initialize the list\r\n dictionary[wd.lower()].append(i) #and append the document\r\n\r\n\r\nhashdictionary={} #This is a map to find the unique keywords used to answer wildcard queries\r\nfor i in range(len(Docs)): #It is a map from tokenized but not lematized string to list of documents\r\n cor = gut.words(Docs[i])\r\n for j in range(len(cor)):\r\n if (cor[j].lower()) in hashdictionary and not (i in hashdictionary[cor[j].lower()]): #if the word is in dictionary and if the document id doesn't already exist in the list then append the doc id to the list\r\n hashdictionary[cor[j].lower()].append(i) #case-lowering the word and appending it to dictionary \r\n elif (cor[j].lower()) not in hashdictionary: #if word is not in the dictionary\r\n hashdictionary[cor[j].lower()]=[] #initialize the list\r\n hashdictionary[cor[j].lower()].append(i) #and append the document\r\n\r\n\r\n\r\nprint \"Start your search\\n\" #Construction of GUI\r\n\r\n\r\nclass SampleApp(tk.Tk):\r\n def __init__(self):\r\n \r\n tk.Tk.__init__(self)\r\n \r\n labelText = StringVar()\r\n labelText.set(\"Enter your Query\")\r\n \r\n self.title(\"Search Engine\")\r\n \r\n self.labelDir = tk.Label(self, textvariable=labelText, height=4) #Label\r\n self.labelDir.grid(row=0)\r\n self.labelDir.pack()\r\n \r\n directory=StringVar(None)\r\n self.entry = tk.Entry(self,textvariable=directory,width=50) #Entry\r\n self.entry.grid(row=0,column=1)\r\n self.entry.pack()\r\n \r\n self.button = tk.Button(self, text=\"Search\", command=self.on_button) #Button\r\n self.button.grid(row=1,column=0)\r\n self.button.pack()\r\n \r\n self.tex = tk.Text(self) #TexBox\r\n self.tex.grid(row=2)\r\n self.tex.pack()\r\n \r\n self.p = IntVar() #Initializing Variable self.p for grouping RadioButtons \r\n \r\n self.rb1 = tk.Radiobutton(self, text=\"Boolean Query\", variable = self.p , value=1 ) #RadioButton1\r\n self.rb2 = tk.Radiobutton(self, text=\"Wild Card Query\", variable = self.p , value=2 ) #RadioButton2\r\n self.rb1.grid(row=1,column=1)\r\n self.rb2.grid(row=1,column=2)\r\n self.rb1.pack()\r\n self.rb2.pack()\r\n \r\n def on_button(self): #eventHandler, triggered when Run is clicked \r\n self.tex.delete(\"1.0\",tk.END) #clearing the text written by previous query\r\n q = self.entry.get() #retrieving the text entered in the entry box\r\n \r\n try:\r\n if self.p.get()==1: #if value returned is 1\r\n k = word_tokenize(q)\r\n i=0\r\n for i in range(len(k)): #Code to Answer Boolean query\r\n if not(k[i]==\"AND\" or k[i]==\"OR\" or k[i]==\"NOT\"):\r\n k[i] = k[i].lower()\r\n k[i] = st.stem(k[i])\r\n s = []\r\n i=0\r\n while i < (len(k)):\r\n if k[i]=='NOT' and i+1intervals[length-1].end:\n intervals.append(Interval(newInterval.start,newInterval.end))\n return intervals\n loca=0\n #Find the location of start point\n while locaintervals[loca].start:\n loca+=1\n else:\n break\n\n #Find the location of end point\n if loca==0 or newInterval.start>intervals[loca-1].end:\n if newInterval.endnewInterval.end:\n res.append(interval)\n else:\n newInterval.start = min(interval.start, newInterval.start)\n newInterval.end = max(interval.end, newInterval.end)\n res.insert(insert_pos, newInterval)\n return res"} {"blob_id": "7a7f7a7da20f360d26e9859af09d434ba183e180", "repo_name": "noelevans/sandpit", "path": "/simulated_annealing.py", "length_bytes": 3622, "score": 3.84375, "int_score": 4, "content": "\"\"\"\nImplementing Einstein's Fish riddle explained here:\n http://blog.pluszero.ca/blog/2016/07/17/\n using-simulated-annealing-to-solve-logic-puzzles/\n\"\"\"\n\nfrom __future__ import division\nimport numpy as np\n\n\n# house 1 2 3 4 5\nanimals = ['bird', 'dog', 'cat', 'horse', 'fish']\ncigarettes = ['pall mall', 'dunhill', 'blends', 'prince', 'blue master']\nnationalities = ['british', 'danish', 'swedish', 'norwegian', 'german']\nhouse_colours = ['yellow', 'red', 'white', 'green', 'blue']\ndrinks = ['water', 'tea', 'milk', 'coffee', 'root beer']\n\nCFG = np.array([animals, cigarettes, nationalities, house_colours, drinks])\nMAX_COST = 15\n\ndef adjacents(arr):\n return (np.arange(len(filter(None, arr))) ==\n arr.nonzero()[0] - min(arr.nonzero()[0])\n ).all()\n\n\ndef cost(cfg):\n \"\"\" Score for a configuration of the houses' wrt constraints of the riddle.\n\n Lower result indicates a better configuration; closer to the\n desired constraints.\n\n The Brit lives in the house with red walls.\n The Swede has a dog.\n The Dane drinks tea.\n The house with green walls is directly to the left of the house with white\n walls.\n The owner of the house with green walls drinks coffee.\n The person who smokes Pall Mall cigars owns a bird.\n The owner of the house with yellow walls smokes Dunhill.\n The man living in the center house drinks milk.\n The Norwegian lives in the first house.\n The man who smokes blends lives next to the cat owner.\n The horse's owner lives next to the man who smokes Dunhill.\n The man who smokes Blue Master drinks root beer.\n The German smokes Prince.\n The Norwegian lives next to the house with blue walls.\n The man who smokes Blends lives next to the man who drinks water.\n \"\"\"\n score = [\n 2 in ((cfg == 'british') | (cfg == 'red')).sum(axis=0),\n 2 in ((cfg == 'swedish') | (cfg == 'dog')).sum(axis=0),\n 2 in ((cfg == 'danish') | (cfg == 'tea')).sum(axis=0),\n 1 == list(cfg[3,:]).index('green') - list(cfg[3,:]).index('white'),\n 2 in ((cfg == 'green') | (cfg == 'coffee')).sum(axis=0),\n 2 in ((cfg == 'bird') | (cfg == 'pall mall')).sum(axis=0),\n 2 in ((cfg == 'yellow') | (cfg == 'dunhill')).sum(axis=0),\n 'milk' in cfg[:, 2],\n 'norwegian' in cfg[:, 0],\n adjacents(((cfg == 'blends') | (cfg == 'cat')).sum(0)),\n adjacents(((cfg == 'horse') | (cfg == 'dunhill')).sum(0)),\n 2 in ((cfg == 'blue master') | (cfg == 'root beer')).sum(axis=0),\n 2 in ((cfg == 'german') | (cfg == 'prince')).sum(axis=0),\n adjacents(((cfg == 'norwegian') | (cfg == 'blue')).sum(0)),\n adjacents(((cfg == 'blends') | (cfg == 'water')).sum(0)),\n ]\n return MAX_COST - sum(score)\n\n\ndef shuffle(arr):\n choice = np.random.randint(len(arr))\n np.random.shuffle(arr[choice])\n return arr\n\n\ndef accept_new_state(current, proposed, temp):\n change = cost(proposed) - cost(current)\n return change <= 0 or np.random.rand() < np.exp(-change / temp)\n\n\ndef main():\n np.random.seed(0)\n cfg = CFG\n N = 1000000\n for i in range(N):\n if i % 500 == 0:\n print(cost(cfg))\n cfg_prime = shuffle(np.copy(cfg))\n temp = max([float(N - i) / N, 0.1])\n if accept_new_state(cfg, cfg_prime, temp):\n cfg = cfg_prime\n # print(cost(cfg))\n if cost(cfg) == 0:\n 'Finished on iteration %i' % i+1\n return\n\n\nif __name__ == '__main__':\n main()\n\n"} {"blob_id": "334ac7e247ed7f77c7c23715017fb4a608bacc9d", "repo_name": "zenithude/Python-Leetcode", "path": "/iscousins.py", "length_bytes": 2344, "score": 4.03125, "int_score": 4, "content": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\n@author: zenithude\r\n\r\nCousins in Binary Tree\r\n\r\nIn a binary tree, the root node is at depth 0, and children of each depth k\r\nnode are at depth k+1.\r\n\r\nTwo nodes of a binary tree are cousins if they have the same depth, but have\r\ndifferent parents.\r\n\r\nWe are given the root of a binary tree with unique values, and the values x\r\nand y of two different nodes in the tree.\r\n\r\nReturn true if and only if the nodes corresponding to the values x and y are\r\ncousins.\r\n\r\n\r\n\r\nExample 1:\r\n\r\nInput: root = [1,2,3,4], x = 4, y = 3\r\nOutput: false\r\n\r\nExample 2:\r\n\r\nInput: root = [1,2,3,null,4,null,5], x = 5, y = 4\r\nOutput: true\r\n\r\nExample 3:\r\n\r\nInput: root = [1,2,3,null,4], x = 2, y = 3\r\nOutput: false\r\n\r\n\r\n\r\nNote:\r\n\r\n The number of nodes in the tree will be between 2 and 100.\r\n Each node has a unique integer value from 1 to 100.\r\n\"\"\"\r\n\r\n\r\n# Definition for a binary tree node.\r\nclass TreeNode:\r\n def __init__(self, x):\r\n self.val = x\r\n self.left = None\r\n self.right = None\r\n\r\n\r\nclass Solution:\r\n def isCousins(self, root, x, y):\r\n \"\"\"\r\n :param root: Treenode\r\n :param x: int\r\n :param y: int\r\n :return: bool\r\n \"\"\"\r\n # 1. The two nodes should be on the same level in the binary tree.\r\n # The two nodes should not be siblings(means that they should not\r\n # have the same parent node.\r\n x_info = []\r\n y_info = []\r\n depth = 0\r\n parent = None\r\n if root is None:\r\n return False\r\n\r\n self.dfs(root, x, y, depth, parent, x_info, y_info)\r\n return x_info[0][0] == y_info[0][0] and x_info[0][1] != y_info[0][1]\r\n\r\n def dfs(self, root, x, y , depth, parent, x_info, y_info):\r\n if root is None:\r\n return None\r\n\r\n if root.val == x:\r\n x_info.append((depth, parent))\r\n\r\n if root.val == y:\r\n y_info.append((depth, parent))\r\n\r\n self.dfs(root.left, x, y, depth + 1, root, x_info, y_info)\r\n self.dfs(root.right, x, y, depth + 1, root, x_info, y_info)\r\n\r\n\r\nroot = TreeNode(1)\r\nroot.left = TreeNode(2)\r\nroot.right = TreeNode(3)\r\nroot.left.left = TreeNode(None)\r\nroot.left.right = TreeNode(4)\r\nroot.right.left = TreeNode(None)\r\nroot.right.right = TreeNode(5)\r\nx = 5\r\ny = 4\r\ns = Solution()\r\nprint(s.isCousins(root, x, y))\r\n"} {"blob_id": "003bc82579dfd89b4d1d001ee16d40d6a726da67", "repo_name": "a100kpm/daily_training", "path": "/problem 0207.py", "length_bytes": 1301, "score": 4.15625, "int_score": 4, "content": "'''\nGood morning! Here's your coding interview problem for today.\n\nThis problem was asked by Dropbox.\n\nGiven an undirected graph G, check whether it is bipartite. \nRecall that a graph is bipartite if its vertices can be divided into two independent sets,\n U and V, such that no edge connects vertices of the same set.\n'''\n\nimport numpy as np\n\ngraph = np.array([[0,1,1,1,0,0,0],\n [1,0,0,0,0,0,0],\n [1,0,1,1,0,0,0],\n [1,0,1,1,0,0,0],\n [0,0,0,0,0,1,1],\n [0,0,0,0,1,0,1],\n [0,0,0,0,1,1,0]\n ])\n\n\n\ndef bipartite(graph):\n lenn=np.shape(graph)[0]\n list_=set()\n \n compteur=0\n while len(list_) 0:\n q = a // b\n r = a - q * b\n u = u2 - q * u1\n v = v2 - q * v1\n a = b\n b = r\n u2 = u1\n u1 = u\n v2 = v1\n v1 = v\n d = a\n u = u2\n v = v2\n return d, u, v\n\n\n'''\n modular inverse of a number a modulo m\n'''\n\n\ndef modular_inverse(a, m):\n gcd, x, y = gcd_extended(a, m)\n return x % m\n\n\n'''\n we generate a random prime number of 4 digits;\n to verify if it is prime, we use the Miller-Rabin test\n'''\n\n\ndef random_prime():\n rnd = randint(1000, 9999)\n while True:\n if rnd % 2 == 1 and miller_rabin(rnd) and (rnd - 3) % 4 == 0:\n return rnd\n else:\n rnd = randint(1000, 9999)\n\n\n'''\n here we obtain a map with the conrespondences between letters and numbers\n'''\n\n\ndef alphabet():\n i = 0\n alpha = {'_': i}\n i += 1\n for letter in list(string.ascii_uppercase):\n alpha[letter] = i\n i += 1\n return alpha\n\n\n'''\n here we obtain a map with the conrespondences between numbers and letters\n'''\n\n\ndef reverse_alphabet():\n i = 0\n reverse_alpha = {i: '_'}\n i += 1\n for letter in list(string.ascii_uppercase):\n reverse_alpha[i] = letter\n i += 1\n return reverse_alpha\n\n\n'''\n function to generate a valid key\n for the encryption system\n'''\n\n\ndef key_generation(k, l):\n while True:\n p = random_prime()\n q = random_prime()\n while q == p:\n q = random_prime()\n public_key = p * q\n private_key = [p, q]\n if valid_key(public_key, k, l):\n return public_key, private_key\n\n\n'''\n function to split a text into blocks of k letters\n'''\n\n\ndef split_text_into_words(text, k):\n text_blocks = []\n while text:\n lng = len(text)\n if k <= lng:\n block = text[0:k]\n text = text[k:lng]\n text_blocks.append(block)\n else:\n while len(text) < k:\n text += '_'\n return text_blocks\n\n\n'''\n function to get the corresponding text \n from its numerical equivalent\n'''\n\n\ndef number_to_word(encrypt, l, reverse_alpha):\n ciphertext = \"\"\n for power in range(l - 1, -1, -1):\n numerical_equiv = encrypt // (27 ** power)\n ciphertext += reverse_alpha[numerical_equiv]\n encrypt -= numerical_equiv * (27 ** power)\n return ciphertext\n\n\n'''\n function to obtain the numerical equivalence \n of a word (block of text)\n'''\n\n\ndef word_to_number(block, alpha):\n m = 0\n for i in range(len(block)):\n m += alpha[block[i]] * 27 ** (len(block) - i - 1)\n return m\n\n\n'''\n text validation \n the text must contain only symbols from\n within the given alphabet\n'''\n\n\ndef valid_text(text):\n alpha = alphabet()\n for i in range(0, len(text)):\n if text[i] not in alpha:\n raise TextValidationError()\n\n\n'''\n function for key validation\n'''\n\n\ndef valid_key(key, k, l):\n if isinstance(key, list):\n if not 27 ** k < key[0] * key[1] < 27 ** l:\n return False\n else:\n if not 27 ** k < key < 27 ** l:\n return False\n return True\n\n\n'''\n encryption function\n f(m)=m^2 mod n\n'''\n\n\ndef encryption_function(m, public_key):\n return (m ** 2) % public_key\n\n\ndef rabin_encryption(text, k, l, public_key):\n text = text.upper()\n text = text.replace(\" \", \"_\")\n valid_text(text)\n ciphertext = \"\"\n alpha = alphabet()\n reverse_alpha = reverse_alphabet()\n\n # Split plaintext\n plaintext_words = split_text_into_words(text, k)\n\n # numerical equivalents\n for block in plaintext_words:\n m = word_to_number(block, alpha)\n binary = bin(m)\n binary += binary[len(binary) - redundancy_size:len(binary)]\n encrypt = encryption_function(int(binary, 2), public_key)\n ciphertext += number_to_word(encrypt, l, reverse_alpha)\n return ciphertext\n\n\ndef decryption_function(m, private_key, public_key, k, reverse_alpha):\n a1 = modular_square_root(m, private_key[0])\n a2 = modular_square_root(m, private_key[1])\n N1 = private_key[1]\n N2 = private_key[0]\n K1 = modular_inverse(N1, N2)\n K2 = modular_inverse(N2, N1)\n\n # list containing the four possible solutions\n x = [(a1 * N1 * K1 + a2 * N2 * K2) % public_key,\n (-a1 * N1 * K1 + a2 * N2 * K2) % public_key,\n (a1 * N1 * K1 - a2 * N2 * K2) % public_key,\n (-a1 * N1 * K1 - a2 * N2 * K2) % public_key]\n res = []\n text_result = \"\"\n\n accepted_solutions = real_solutions(x)\n for sol in accepted_solutions:\n sol = int(bin(sol)[:len(bin(sol)) - redundancy_size], 2)\n if sol < 27 ** k:\n dec = number_to_word(sol, k, reverse_alpha)\n res.append(dec)\n\n return res, text_result\n\n\ndef rabin_decryption(text, private_key, public_key, k, l):\n ambiguous = False\n decrypted_text = \"\"\n\n # text validation\n valid_text(text)\n\n alpha = alphabet()\n reverse_alpha = reverse_alphabet()\n\n # split ciphertext into blocks of l letters\n ciphertext_blocks = split_text_into_words(text, l)\n\n decryption_results = []\n for block in ciphertext_blocks:\n m = word_to_number(block, alpha)\n res, txt = decryption_function(m, private_key, public_key, k, reverse_alpha)\n decryption_results.append(res)\n if len(res) != 1:\n ambiguous = True\n decrypted_text = \"\"\n if not ambiguous:\n for block in decryption_results:\n decrypted_text += block[0]\n decrypted_text = decrypted_text.replace('_', ' ')\n\n return decryption_results, ciphertext_blocks, decrypted_text\n\n'''\n function to determine the solutions that have the \n corresponding redundancy\n'''\ndef real_solutions(x):\n acc_sol = []\n for sol in x:\n binary_sol = bin(sol)\n length = len(binary_sol)\n if binary_sol[length - redundancy_size * 2:length - redundancy_size] \\\n == binary_sol[length - redundancy_size:length]:\n if sol not in acc_sol:\n acc_sol.append(sol)\n return acc_sol\n"} {"blob_id": "20a64ebd303f373f06e16d3cee4803e834c88b56", "repo_name": "zengln/leetcode_pj", "path": "/\u6808/\u57fa\u672c\u8ba1\u7b97\u5668II.py", "length_bytes": 5178, "score": 3.578125, "int_score": 4, "content": "# \u5b9e\u73b0\u4e00\u4e2a\u57fa\u672c\u7684\u8ba1\u7b97\u5668\u6765\u8ba1\u7b97\u4e00\u4e2a\u7b80\u5355\u7684\u5b57\u7b26\u4e32\u8868\u8fbe\u5f0f\u7684\u503c\u3002\n#\n# \u5b57\u7b26\u4e32\u8868\u8fbe\u5f0f\u4ec5\u5305\u542b\u975e\u8d1f\u6574\u6570\uff0c+\uff0c - \uff0c*\uff0c/ \u56db\u79cd\u8fd0\u7b97\u7b26\u548c\u7a7a\u683c \u3002 \u6574\u6570\u9664\u6cd5\u4ec5\u4fdd\u7559\u6574\u6570\u90e8\u5206\u3002\n#\n# \u793a\u4f8b 1:\n#\n# \u8f93\u5165: \"3+2*2\"\n# \u8f93\u51fa: 7\n#\n#\n# \u793a\u4f8b 2:\n#\n# \u8f93\u5165: \" 3/2 \"\n# \u8f93\u51fa: 1\n#\n# \u793a\u4f8b 3:\n#\n# \u8f93\u5165: \" 3+5 / 2 \"\n# \u8f93\u51fa: 5\n#\n#\n# \u8bf4\u660e\uff1a\n#\n#\n# \u4f60\u53ef\u4ee5\u5047\u8bbe\u6240\u7ed9\u5b9a\u7684\u8868\u8fbe\u5f0f\u90fd\u662f\u6709\u6548\u7684\u3002\n# \u8bf7\u4e0d\u8981\u4f7f\u7528\u5185\u7f6e\u7684\u5e93\u51fd\u6570 eval\u3002\n#\n\n'''\n\u89e3\u9898\u601d\u8def\uff1a\n\n\u9898\u76ee\u4e2d\u7ed9\u51fa\uff0c\u4ec5\u5305\u542b\u975e\u8d1f\u6574\u6570\uff0c+\uff0c - \uff0c*\uff0c/ \u56db\u79cd\u8fd0\u7b97\u7b26\u548c\u7a7a\u683c \u3002 \u6574\u6570\u9664\u6cd5\u4ec5\u4fdd\u7559\u6574\u6570\u90e8\u5206\n\n1. \u8fd0\u7b97\u6ee1\u8db3\u5148\u4e58\u9664\u540e\u52a0\u51cf\u7684\u539f\u5219\n2. \u9047\u5230\u6570\u5b57\u4fdd\u5b58\u4e0b\u6765,\u5982\u679c\u662f\u52a0\u51cf\u6cd5\u4e0d\u8fdb\u884c\u8ba1\u7b97\uff0c\u76f4\u63a5\u5165\u6808\n3. \u9047\u5230\u4e58\u9664\u5c06\u7ed3\u679c\u8ba1\u7b97\u51fa\u6765\u540e\u4fdd\u7559\u4e0b\u8ba1\u7b97\u51fa\u7684\u6570\u636e\u5165\u6808\n4. \u5c06\u6808\u4e2d\u6240\u6709\u6570\u636e\u76f8\u52a0(\u51cf\u6cd5\u4e5f\u662f\u4e00\u79cd\u52a0\u6cd5\uff0c\u52a0\u4e0a\u8d1f\u6570)\n\na.\u904d\u5386\u6574\u4e2a\u5b57\u7b26\u4e32\nb.\u5982\u679c\u662f\u6570\u5b57,\u4fdd\u5b58\u5728\u4e34\u65f6\u53d8\u91cf\u91cc\nc.\u5982\u679c\u662f\u7b26\u53f7,\u5c06\u4e34\u65f6\u53d8\u91cf\u5165\u6808\nd.\u7b26\u53f7\u4e3a\u4e58\u9664, \u5f53\u4e0b\u6b21\u518d\u9047\u5230\u7b26\u53f7\u65f6,\u5c06\u6808\u9876\u5143\u7d20\u4e0e\u4fdd\u5b58\u4e0b\u6765\u7684\u53d8\u91cf\u8fdb\u884c\u8fd0\u7b97\ne.\u7b26\u53f7\u4e3a\u52a0\u51cf, \u5f53\u4e0b\u6b21\u518d\u9047\u5230\u7b26\u53f7\u65f6,\u5c06\u53d8\u91cf\u5165\u6808\nd.\u904d\u5386\u5230\u6700\u540e\u4e00\u4e2a\u5143\u7d20\u65f6,\u518d\u505a\u4e00\u6b21(d\u3001e\u5224\u65ad)\n'''\n\n'''\nclass Solution:\n def calculate(self, s: str) -> int:\n stack_num = []\n num = 0\n operator = \"+\"\n s = s.strip()\n for index in range(0, len(s)):\n s_char = s[index]\n if s_char.isdigit():\n num = num * 10 + int(s_char)\n if index == len(s) - 1:\n if operator == \"*\":\n stack_num.append(stack_num.pop() * num)\n elif operator == \"/\":\n temp_num = stack_num.pop()\n if temp_num < 0:\n result = (0 - temp_num) // num\n result = -result\n else:\n result = temp_num // num\n stack_num.append(result)\n elif operator == \"-\":\n stack_num.append(-num)\n else:\n stack_num.append(num)\n elif s_char in ['+', '-', '*', '/']:\n if not stack_num:\n stack_num.append(num)\n else:\n if operator == \"*\":\n stack_num.append(stack_num.pop() * num)\n elif operator == \"/\":\n temp_num = stack_num.pop()\n if temp_num < 0:\n result = (0 - temp_num) // num\n result = -result\n else:\n result = temp_num // num\n stack_num.append(result)\n elif operator == \"-\":\n stack_num.append(-num)\n else:\n stack_num.append(num)\n operator = s_char\n num = 0\n\n result = 0\n for num in stack_num:\n result += num\n return result\n'''\n\n'''\n# \u7b2c\u4e00\u7248\u4f18\u5316\nclass Solution:\n def calculate(self, s: str) -> int:\n stack_num = []\n num = 0\n operator = \"+\"\n s = s.strip()\n for index in range(0, len(s)):\n s_char = s[index]\n\n if s_char.isdigit():\n num = num * 10 + int(s_char)\n\n if index == len(s) - 1 or s_char in ['+', '-', '*', '/']:\n if operator == \"*\":\n stack_num.append(stack_num.pop() * num)\n elif operator == \"/\":\n temp_num = stack_num.pop()\n if temp_num < 0:\n result = (0 - temp_num) // num\n result = -result\n else:\n result = temp_num // num\n stack_num.append(result)\n elif operator == \"-\":\n stack_num.append(-num)\n else:\n stack_num.append(num)\n operator = s_char\n num = 0\n\n result = 0\n for num in stack_num:\n result += num\n return result\n'''\n# \u5927\u4f6c\u4e0e\u6211\u89e3\u6cd5\u7684\u533a\u522b\n# 1.\n# \u5728\u8fdb\u884c\u9664\u6cd5\u65f6, \u6211\u4f7f\u7528//\uff0c\u8fd9\u65f6\u5982\u679c\u662f\u8d1f\u6570\u5219\u4f1a\u5f80\u540e\u53d6\u503c\uff0c\u6240\u4ee5\u6211\u591a\u505a\u4e86\u4e00\u4e9b\u5224\u65ad\n# \u5927\u4f6c\u7684\u9664\u6cd5\u903b\u8f91\u662f\uff0c\u4f7f\u7528/\uff0c\u5bf9\u7ed3\u679c\u8fdb\u884c\u53d6\u8bc1,\u6240\u4ee5\u65e0\u9700\u8fdb\u884c\u6b63\u8d1f\u6570\u7684\u7279\u6b8a\u533a\u5206\n# 2.\n# \u8fd4\u56de\u65f6\u4f7f\u7528sum\u548c\u624b\u52a8\u8ba1\u7b97\u7684\u533a\u522b\n'''\nclass Solution:\n def calculate(self, s: str) -> int:\n stack = []\n num = 0; sign = '+'\n for i in range(len(s)):\n if s[i].isdigit():\n num = num*10 + int(s[i])\n if s[i] in '+-*/' or i == len(s)-1:\n if sign == '+':\n stack.append(num)\n elif sign == '-':\n stack.append(-num)\n elif sign == '*':\n stack.append(stack.pop() * num)\n else:\n stack.append(int(stack.pop() / num))\n num = 0; sign = s[i]\n return sum(stack)\n\n'''\n\n"} {"blob_id": "e9bf9202428c1b7114b3a6e43c9a9bf5507441ed", "repo_name": "Wolokin/Text-Algorithms", "path": "/Lab4/modules/lcs.py", "length_bytes": 1682, "score": 3.671875, "int_score": 4, "content": "from enum import Enum\n\n\nclass Step(Enum):\n MATCH = 0\n LEFT = 1\n UP = 2\n\n\ndef lcs(s1, s2):\n n = len(s1)\n m = len(s2)\n length = [[0 for i in range(m + 1)] for j in range(n + 1)]\n path = [[0 for i in range(m + 1)] for j in range(n + 1)]\n for i in range(n + 1):\n length[i][0] = 0\n path[i][0] = Step.UP\n for i in range(m + 1):\n length[0][i] = 0\n path[0][i] = Step.LEFT\n for i in range(1, n + 1):\n for j in range(1, m + 1):\n if s1[i - 1] == s2[j - 1]:\n length[i][j] = length[i - 1][j - 1] + 1\n path[i][j] = Step.MATCH\n else:\n length[i][j] = length[i - 1][j]\n path[i][j] = Step.UP\n if length[i][j] < length[i][j - 1]:\n length[i][j] = length[i][j - 1]\n path[i][j] = Step.LEFT\n return length[n][m], visualize(s1, s2, path)\n\n\ndef visualize(s1, s2, path):\n i = len(s1)\n j = len(s2)\n subseq = []\n while i != 0 or j != 0:\n c = path[i][j]\n if c == Step.UP:\n i -= 1\n elif c == Step.LEFT:\n j -= 1\n else:\n i -= 1\n j -= 1\n subseq.append(s1[i])\n subseq.reverse()\n return subseq\n\n\nif __name__ == '__main__':\n t1, t2 = \"los\", \"kloc\"\n count, ss = lcs(t1, t2)\n print(count, ''.join(ss))\n t1, t2 = \"\u0141\u00f3d\u017a\", \"Lodz\"\n count, ss = lcs(t1, t2)\n print(count, ''.join(ss))\n t1, t2 = \"kwintesencja\", \"quintessence\"\n count, ss = lcs(t1, t2)\n print(count, ''.join(ss))\n t1, t2 = \"ATGAATCTTACCGCCTCG\", \"ATGAGGCTCTGGCCCCTG\"\n count, ss = lcs(t1, t2)\n print(count, ''.join(ss))\n"} {"blob_id": "736a16c6c9f13efd689a4449c5bdaef22d1d96fc", "repo_name": "garciaha/DE_daily_challenges", "path": "/2020-08-03/unravel.py", "length_bytes": 641, "score": 4.4375, "int_score": 4, "content": "\"\"\"Unravel all the Possibilities\n\nWrite a function that takes in a string and returns all possible combinations. Return the final result in alphabetical order.\n\nExamples\nunravel(\"a[b|c]\") -> [\"ab\", \"ac\"]\n\nNotes\nThink of each element in every block (e.g. [a|b|c]) as a fork in the road.\n\"\"\"\n\n\ndef unravel(string):\n pass\n\n\nif __name__ == \"__main__\":\n assert unravel(\"a[b|c]de[f|g]\") == [\"abdef\", \"acdef\", \"abdeg\", \"acdeg\"]\n assert unravel(\"a[b]c[d]\") == [\"abcd\"]\n assert unravel(\"a[b|c|d|e]f\") == [\"abf\", \"acf\", \"adf\", \"aef\"]\n assert unravel(\"apple [pear|grape]\") == [\"apple pear\", \"apple grape\"]\n print(\"All cases passed!\")\n"} {"blob_id": "16b266cd90d62520583d377a85c3828c4858dda7", "repo_name": "0xall/FindingMin", "path": "/visualization.py", "length_bytes": 1104, "score": 3.8125, "int_score": 4, "content": "from decimal import Decimal\nfrom typing import Tuple\n\nfrom polynomial import Polynomial\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n\ndef visualize_polynomial(p: Polynomial, interval: Tuple[str, str]):\n x = np.linspace(float(interval[0]), float(interval[1]), 100)\n y = np.zeros(len(x))\n\n for level, coefficient in enumerate(p.coefficients):\n y += float(coefficient) * (x ** level)\n\n plt.axhline(y=0, color='lightgray')\n plt.axvline(x=0, color='lightgray')\n plt.plot(x, y)\n plt.xlim(float(interval[0]), float(interval[1]))\n\n\ndef visualize_newton_iteration(p: Polynomial, x: Decimal, step: int = 0):\n diff = p.differential()\n gradient = diff(x)\n gradient_polynomial = Polynomial(gradient, - gradient * x + p(x))\n\n plt.subplot(2, 1, 1)\n plt.title(f'STEP {step} (x = {x}, y = {p(x)})')\n visualize_polynomial(p, (x - 1, x + 1))\n visualize_polynomial(gradient_polynomial, (x - 1, x + 1))\n plt.plot(float(x), float(p(x)), 'bo')\n\n plt.subplot(2, 1, 2)\n visualize_polynomial(diff, (x - 1, x + 1))\n plt.plot(float(x), float(diff(x)), 'bo')\n"} {"blob_id": "516e25e9f680aaad96261fa816d6c96d018ce76a", "repo_name": "ironboxer/leetcode", "path": "/python/23.py", "length_bytes": 4272, "score": 4.09375, "int_score": 4, "content": "\"\"\"\nhttps://leetcode.com/problems/merge-k-sorted-lists\n\nYou are given an array of k linked-lists lists, each linked-list is sorted in ascending order.\n\nMerge all the linked-lists into one sorted linked-list and return it.\n\n\n\nExample 1:\n\nInput: lists = [[1,4,5],[1,3,4],[2,6]]\nOutput: [1,1,2,3,4,4,5,6]\nExplanation: The linked-lists are:\n[\n 1->4->5,\n 1->3->4,\n 2->6\n]\nmerging them into one sorted list:\n1->1->2->3->4->4->5->6\nExample 2:\n\nInput: lists = []\nOutput: []\nExample 3:\n\nInput: lists = [[]]\nOutput: []\n\n\nConstraints:\n\nk == lists.length\n0 <= k <= 10^4\n0 <= lists[i].length <= 500\n-10^4 <= lists[i][j] <= 10^4\nlists[i] is sorted in ascending order.\nThe sum of lists[i].length won't exceed 10^4.\n\n\"\"\"\n\n# Definition for singly-linked list.\n\nfrom typing import List\n\n\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n\nclass Solution:\n def mergeKLists(self, lists: List[ListNode]) -> ListNode:\n lists = [node for node in lists if node]\n dummy = ListNode(0)\n cur = dummy\n while lists:\n min_val, min_pos = 2 ** 31, -1\n for i, node in enumerate(lists):\n if node.val < min_val:\n min_val = node.val\n min_pos = i\n cur.next = lists[min_pos]\n cur = cur.next\n lists[min_pos] = lists[min_pos].next\n if lists[min_pos] is None:\n lists.pop(min_pos)\n return dummy.next\n\n\nclass Solution:\n def mergeKLists(self, lists: List[ListNode]) -> ListNode:\n from queue import PriorityQueue\n dummy = ListNode(0, None)\n cur = dummy\n q = PriorityQueue()\n for i, node in enumerate(lists):\n if node:\n q.put((node.val, i, node))\n while q.qsize() > 0:\n node = q.get()\n idx = node[1]\n cur.next = node[-1]\n cur = cur.next\n # \u5f88\u597d\u7684\u63a7\u5236\u4e86\u961f\u5217\u7684\u5927\u5c0f\n if cur.next:\n q.put((cur.next.val, idx, cur.next))\n return dummy.next\n\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def mergeKLists(self, lists: List[ListNode]) -> ListNode:\n dummy = ListNode(0)\n cur = dummy\n lists = list(filter(None, lists))\n while lists:\n j = 0\n for i in range(1, len(lists)):\n if lists[i].val <= lists[j].val:\n j = i\n cur.next = lists[j]\n cur = cur.next\n lists[j] = lists[j].next\n if not lists[j]:\n lists.pop(j)\n\n return dummy.next\n\n\n\nfrom queue import PriorityQueue\n\nclass Solution:\n def mergeKLists(self, lists: List[ListNode]) -> ListNode:\n dummy = ListNode(0)\n cur = dummy\n q = PriorityQueue()\n for node in lists:\n if node:\n # TODO: \u8fd9\u91cc\u4e3a\u4ec0\u4e48\u4f1a\u62a5\u9519?\n q.put((node.val, node))\n while not q.empty():\n _, node = q.get()\n cur.next = node\n cur = cur.next\n if node.next:\n q.put((node.next.val, node.next))\n return dummy.next\n\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\n\nfrom queue import PriorityQueue\n\nclass Solution:\n def mergeKLists(self, lists: List[ListNode]) -> ListNode:\n dummy = ListNode(0)\n cur = dummy\n q = PriorityQueue()\n for i, node in enumerate(lists):\n if node:\n q.put((node.val, i))\n while not q.empty():\n _, i = q.get()\n cur.next = lists[i]\n cur = cur.next\n if lists[i].next:\n lists[i] = lists[i].next\n q.put((lists[i].val, i))\n return dummy.next\n\n\n\nif __name__ == '__main__':\n l1 = ListNode(1, ListNode(4, ListNode(5)))\n l2 = ListNode(1, ListNode(3, ListNode(4)))\n l3 = ListNode(2, ListNode(6))\n lists = [l1, l2, l3]\n\n cur = Solution().mergeKLists(lists)\n while cur:\n print(cur.val)\n cur = cur.next\n\n\n"} {"blob_id": "813d679785214c619e9e39942fd323cff7681671", "repo_name": "heikoschmidt1187/DailyCodingChallenges", "path": "/day11.py", "length_bytes": 2071, "score": 3.828125, "int_score": 4, "content": "#!/bin/python3\n\"\"\"\nImplement an autocomplete system. That is, given a query string s and a set\nof all possibly query strings, return all strings in the set that have s as\na prefix.\n\nFor example, given the query string de and the set of strings [dog, deer,\ndeal], return [deer, deal].\n\nHint: Try preprocessing the dictionary into a more efficient data setructure\nto speed up queries.\n\"\"\"\ndef add_word_to_trie(w, trie):\n # base case\n if not w:\n return\n \n if w[0] not in trie:\n trie[w[0]] = dict()\n \n # continue with next characters until base case\n trie[w[0]] = add_word_to_trie(w[1:], trie[w[0]])\n\n return trie\n\ndef setup_trie(d):\n trie = dict()\n \n for word in d:\n trie = add_word_to_trie(word, trie)\n \n return trie\n\ndef get_completions(trie):\n completions = []\n\n # loop through tree and collect characters at level\n for ch in trie:\n \n # if subtrie, go down\n if trie[ch]:\n sub_completions = get_completions(trie[ch])\n\n for sc in sub_completions:\n completions.append(ch + sc)\n else:\n completions.append(ch)\n\n return completions\n\ndef get_autocomplete(s, dictionary):\n # as datastructure I use a trie, prefix search and compression tree formed\n # as dictionary of dicitonaries in python\n trie = setup_trie(dictionary)\n \n # perform a fast search if words are in the dictionary that start with\n # the prefix string\n subtrie = trie\n for ch in s:\n if ch not in subtrie:\n return []\n \n subtrie = subtrie[ch]\n \n # if we land here, there are words present we need to capture and\n # return \n completions = get_completions(subtrie)\n \n # as we operate on the relevant subtree, we need to expand the completions\n # with the prefix to get the actual words\n completions = [s + w for w in completions]\n\n return completions\n\nif __name__ == '__main__':\n print(get_autocomplete('de', ['dog', 'deer', 'deal']))\n print(get_autocomplete('de', []))"} {"blob_id": "184d9ebdcd5132606f1e2ad75a76824990e8a75d", "repo_name": "lilsweetcaligula/sandbox-online-judges", "path": "/lintcode/easy/count_and_say/py/count_and_say.py", "length_bytes": 691, "score": 3.625, "int_score": 4, "content": "# coding:utf-8\n'''\n@Copyright:LintCode\n@Author: lilsweetcaligula\n@Problem: http://www.lintcode.com/problem/count-and-say\n@Language: Python\n@Datetime: 17-02-15 14:07\n'''\n\nclass Solution:\n # @param {int} n the nth\n # @return {string} the nth sequence\n def countAndSay(self, n):\n def helper(n, s='1'):\n import itertools\n \n if n <= 1:\n return s\n \n t = ''\n \n for c, g in itertools.groupby(s):\n t += str(len(tuple(g))) + c\n \n return helper(n - 1, t)\n \n if n == 0:\n return ''\n \n return helper(n)"} {"blob_id": "065432e1ef4ba3e168b5c30c3781b9327f875e53", "repo_name": "superY-25/algorithm-learning", "path": "/src/algorithm/202003/swapPairs.py", "length_bytes": 1147, "score": 4.09375, "int_score": 4, "content": "\"\"\"\n\u7ed9\u5b9a\u4e00\u4e2a\u94fe\u8868\uff0c\u4e24\u4e24\u4ea4\u6362\u5176\u4e2d\u76f8\u90bb\u7684\u8282\u70b9\uff0c\u5e76\u8fd4\u56de\u4ea4\u6362\u540e\u7684\u94fe\u8868\u3002\n\n\u4f60\u4e0d\u80fd\u53ea\u662f\u5355\u7eaf\u7684\u6539\u53d8\u8282\u70b9\u5185\u90e8\u7684\u503c\uff0c\u800c\u662f\u9700\u8981\u5b9e\u9645\u7684\u8fdb\u884c\u8282\u70b9\u4ea4\u6362\u3002\n\n\u00a0\n\n\u793a\u4f8b:\n\n\u7ed9\u5b9a 1->2->3->4, \u4f60\u5e94\u8be5\u8fd4\u56de 2->1->4->3.\n\n\u6765\u6e90\uff1a\u529b\u6263\uff08LeetCode\uff09\n\u94fe\u63a5\uff1ahttps://leetcode-cn.com/problems/swap-nodes-in-pairs\n\u8457\u4f5c\u6743\u5f52\u9886\u6263\u7f51\u7edc\u6240\u6709\u3002\u5546\u4e1a\u8f6c\u8f7d\u8bf7\u8054\u7cfb\u5b98\u65b9\u6388\u6743\uff0c\u975e\u5546\u4e1a\u8f6c\u8f7d\u8bf7\u6ce8\u660e\u51fa\u5904\u3002\n\"\"\"\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution:\n def swapPairs(self, head: ListNode) -> ListNode:\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n\n # If the list has no node or has only one node left.\n if not head or not head.next:\n return head\n\n # Nodes to be swapped\n first_node = head\n second_node = head.next\n\n # Swapping\n first_node.next = self.swapPairs(second_node.next)\n second_node.next = first_node\n\n # Now the head is the second node\n return second_node\n"} {"blob_id": "c5fb2b3c33c05d3d098923f788b3b057571ae73c", "repo_name": "sprax/1337", "path": "/python3/l0148_sort_list.py", "length_bytes": 1336, "score": 3.828125, "int_score": 4, "content": "from common import ListNode\nfrom typing import Tuple\n\nclass Solution:\n def sortList(self, head: ListNode) -> ListNode:\n\n def merge_sort(head: ListNode, length: int) -> Tuple[ListNode, ListNode]:\n # Sort list for given length, return sorted list and list after length.\n if not head:\n return (None, None)\n\n if length == 1:\n next_head = head.next\n head.next = None\n return (head, next_head)\n \n new_head_1, next_to_sort_1 = merge_sort(head, length // 2)\n new_head_2, next_to_sort_2 = merge_sort(next_to_sort_1, length // 2 + length % 2)\n\n # Merge new_head_1 and new_head_2.\n p = dummy = ListNode(0)\n p1, p2 = new_head_1, new_head_2\n while p1 or p2:\n v1 = p1.val if p1 else float('inf')\n v2 = p2.val if p2 else float('inf')\n if v1 <= v2:\n p.next = p1\n p1 = p1.next\n else:\n p.next = p2\n p2 = p2.next\n p = p.next\n return (dummy.next, next_to_sort_2)\n \n p = head\n length = 0\n while p:\n length += 1\n p = p.next\n return merge_sort(head, length)[0]"} {"blob_id": "34301e251fe8c318ff2ef2242b0f22573ebb6b01", "repo_name": "yourSprite/LeetCodeExcercise", "path": "/37.py", "length_bytes": 1688, "score": 3.8125, "int_score": 4, "content": "class Solution:\n def solveSudoku(self, board):\n \"\"\"\n :type board: List[List[str]]\n :rtype: void Do not return anything, modify board in-place instead.\n \"\"\"\n if board is None or len(board) == 0: return\n self.solve(board)\n\n def solve(self, board):\n \"\"\"\n \u586b\u5145\u6570\u5b57\n \"\"\"\n for i in range(9): # \u904d\u5386\u884c\n for j in range(9): # \u904d\u5386\u5217\n if board[i][j] == '.': # \u5f53\u524d\u683c\u5b50\u9700\u8981\u586b\u5145\n for c in range(1, 10): # \u4ece1\u5f00\u59cb\u586b\u5145\uff0c\u540e\u7eed\u5224\u65ad\u662f\u5426\u6709\u6548\n c = str(c) # \u5c06\u6570\u5b57\u8f6c\u6362\u5b57\u7b26\u4e32\n if self.isValid(board, i, j, c): # \u5224\u65ad\u662f\u5426\u6709\u6548\uff0c\u6709\u6548\u586b\u5145\u6570\u5b57\n board[i][j] = c\n if self.solve(board): # \u586b\u5145\u6570\u5b57\u540e\u8fdb\u884c\u9012\u5f52\u7ee7\u7eed\u586b\u5145\u6570\u72ec\n return True\n else:\n board[i][j] = '.' # \u540e\u7eed\u65e0\u6cd5\u586b\u5145\u8fdb\u884c\u56de\u6eaf\n return False\n return True\n\n def isValid(self, board, row, col, c):\n \"\"\"\n \u5224\u65ad\u586b\u5165\u6570\u5b57\u662f\u5426\u6709\u6548\n \"\"\"\n for i in range(9):\n if board[i][col] != '.' and board[i][col] == c: # \u5f53\u524d\u5217\u662f\u5426\u6709\u91cd\u590d\u6570\u5b57\n return False\n if board[row][i] != '.' and board[row][i] == c: # \u5f53\u524d\u884c\u662f\u5426\u6709\u91cd\u590d\u6570\u5b57\n return False\n if board[3*(row//3)+i//3][3*(col//3)+i%3] != '.' and board[3*(row//3)+i//3][3*(col//3)+i%3] == c:\n # \u5f53\u524d3x3\u5b50\u6570\u72ec\u662f\u5426\u6709\u91cd\u590d\u6570\u5b57\n return False\n return True\n"} {"blob_id": "e5a7db285842cd57846dea7d12a22b3c533b712e", "repo_name": "OluwoleCo/LeetCodeExercises", "path": "/university_career_fair/university_career_fair.py", "length_bytes": 789, "score": 3.625, "int_score": 4, "content": "# https://leetcode.com/discuss/interview-question/algorithms/374846/twitter-oa-2019-university-career-fair\n# https://www.codespeedy.com/interval-scheduling-in-python/\n\n# print(universityCareerFair([1, 3, 3, 5, 7], [2, 2, 1, 2, 1])) # 4\n# print(universityCareerFair([1, 2], [7, 3])) # 1\n\ndef universityCareerFair(arrival, duration):\n finish = list(map(sum, zip(duration,arrival)))\n index = list(range(len(arrival)))\n print (\"index\", index)\n \n max_set = set()\n prev_event_time = 0\n for i in index:\n if arrival[i] >= prev_event_time:\n max_set.add(i)\n prev_event_time = finish[i]\n \n return max(max_set)\n\nresult = universityCareerFair([1, 3, 3, 5, 7], [2, 2, 1, 2, 1])\nprint('Maximum number of tasks can be executed are', result)\n"} {"blob_id": "e156826f40473fc149bcc909a91528f46faa5044", "repo_name": "btjanaka/algorithm-problems", "path": "/hackerrank/little-chammys-huge-donation.py", "length_bytes": 1066, "score": 3.71875, "int_score": 4, "content": "# Author: btjanaka (Bryon Tjanaka)\n# Problem: (HackerRank) little-chammys-huge-donation\n# Title: Little Ashish's Huge Donation\n# Link: https://www.hackerrank.com/challenges/little-chammys-huge-donation/problem\n# Idea: Since there is a closed formula we can use to calculate the sum of\n# squares from 1 to n, we can binary search for the number of children that can\n# be fed.\n# Difficulty: medium\n# Tags: math, binary-search\n\n\ndef sqsum(n):\n \"\"\"\"\n Calculates 6 * (sum of numbers from 1 to n) (we want to avoid division\n for large numbers because Python is not good with it). See\n https://trans4mind.com/personal_development/mathematics/series/sumNaturalSquares.htm\n \"\"\"\n return n * (n + 1) * (2 * n + 1)\n\n\nfor _ in range(int(input())):\n x = 6 * int(input()) # To avoid division in sqsum\n lo, hi = 0, 10**9\n while hi - lo > 1:\n mid = (hi + lo) // 2\n s = sqsum(mid)\n if s < x:\n lo = mid\n elif s > x:\n hi = mid\n else:\n lo = mid\n hi = mid\n break\n print(lo)\n"} {"blob_id": "06b8339073dff3c0e3207154c9a1277f63202956", "repo_name": "davidygp/Project_Euler", "path": "/python/prob4.py", "length_bytes": 893, "score": 4.34375, "int_score": 4, "content": "\"\"\"\nProblem 4:\n\nA palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 \u00d7 99.\n\nFind the largest palindrome made from the product of two 3-digit numbers.\n\"\"\"\n\ndef find_max_palin_product() -> int:\n \"\"\"\n Find the largest palindrome made from the product of two 3-digit numbers\n \"\"\"\n max_palin_product = 0\n for _, val1 in enumerate(range(100, 1000), 1):\n for _, val2 in enumerate(range(100, 1000), 1):\n if val1 > val2:\n product = str(val1 * val2)\n reverse_product = \"\".join(list(product)[::-1])\n if product == reverse_product and int(product) > max_palin_product:\n max_palin_product = int(product)\n return max_palin_product\n\n\n\n\nif __name__ == \"__main__\":\n print(\"Ans is %s\" % ( find_max_palin_product() ) )\n # 9066909\n"} {"blob_id": "968b6a37ecacc1e00cd20affa2fbeda24edd6049", "repo_name": "sncodeGit/ML-and-DA", "path": "/Math_and_Python_for_DA/week3/Task1_3.py", "length_bytes": 785, "score": 3.515625, "int_score": 4, "content": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 14 22:26:23 2019\n\n@author: inter000\n\"\"\"\n\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt \nfrom scipy import optimize\n\ndef f(x):\n return math.sin(x / 5.) * math.exp(x / 10.) + 5 * math.exp(-x / 2.)\n\ndef h(x):\n return int(f(x))\n\nX = np.arange(1, 31, 0.01)\nplt.plot(X, list(map(h, X)))\nplt.show()\n\nprint(\"\\n\\nBFGS with X0 = 30:\\n\\n\", optimize.minimize(h, 30., method='BFGS'))\nprint(\"\\n\\nBFGS with X0 = 25.1:\\n\\n\", optimize.minimize(h, 25.1, method='BFGS'))\n# \u0413\u0440\u0430\u0434\u0438\u0435\u043d\u0442 (\u043f\u0440\u043e\u0438\u0437\u0432\u043e\u0434\u043d\u0430\u044f, \u0442.\u043a. \u0441\u043b\u0443\u0447\u0430\u0439 \u043e\u0434\u043d\u043e\u043c\u0435\u0440\u043d\u044b\u0439) \u043d\u0443\u043b\u0435\u0432\u043e\u0439 =>\n# BFGS \u0434\u0430\u0436\u0435 \u043d\u0435 \u0441\u043e\u0432\u0435\u0440\u0448\u0438\u0442 \u043d\u0438 \u043e\u0434\u043d\u043e\u0439 \u0438\u0442\u0435\u0440\u0430\u0446\u0438\u0438\nprint(\"\\n\\nDifferential Evolution:\\n\\n\", optimize.differential_evolution(h, ([1, 30],)))"} {"blob_id": "dc04dba396316ac1216b1e1e14cf677a68e10925", "repo_name": "TJRobson/MITx6.00.2x", "path": "/quiz/quiz_code.py", "length_bytes": 3863, "score": 3.75, "int_score": 4, "content": "\ndef song_playlist(songs, max_size):\n \"\"\"\n songs: list of tuples, ('song_name', song_len, song_size)\n max_size: float, maximum size of total songs that you can fit\n\n Start with the song first in the 'songs' list, then pick the next \n song to be the one with the lowest file size not already picked, repeat\n\n Returns: a list of a subset of songs fitting in 'max_size' in the order \n in which they were chosen.\n \"\"\"\n play_list, space_left = list(), 0 \n songs_cpy = songs[:1] + sorted(songs[1:], key=lambda x: x[2])\n \n i = 0 \n while i != len(songs) and space_left < max_size:\n \n temp_size = space_left + songs_cpy[i][2] \n \n if temp_size <= max_size:\n play_list.append(songs_cpy[i][0])\n space_left = temp_size\n i += 1 \n else: \n break \n \n return play_list\n\n# Interesting solution to the same problem.\n\n#def song_playlist(songs, max_size):\n# \"\"\"[...]\"\"\"\n# playlist = []\n# try:\n# for (song, length, size) in songs[0:1] \\\n# + sorted(songs[1:], key=lambda x: x[2]):\n# if max_size > size:\n# max_size -= size\n# playlist.append(song)\n# else:\n# break\n# except IndexError:\n# pass\n# return playlist\n\nsongs = [('Roar',4.4, 4.0),('Sail',3.5, 7.7),('Timber', 5.1, 6.9),('Wannabe',2.7, 1.2)] \nmax_size = 12.2\n# Returns ['Roar','Wannabe','Timber']\n\n#print(song_playlist(songs, max_size))\n#print(song_playlist([('a', 4.4, 4.0), ('b', 3.5, 7.7), ('c', 5.1, 6.9), ('d', 2.7, 1.2)], 20))\n#print(song_playlist([('aa', 4, 4), ('bb', 5, 7), ('cc', 5, 6), ('dd', 2, 1)], 3))\n#print(song_playlist([('z', 0.1, 9.0), ('a', 4.4, 5.0), ('b', 2.7, 7.2), ('cc', 3.5, 7.7), ('ddd', 5.1, 6.9)], 14))\n\ndef greedySum(L, s):\n \"\"\" input: s, positive integer, what the sum should add up to\n L, list of unique positive integers sorted in descending order\n Use the greedy approach where you find the largest multiplier for \n the largest value in L then for the second largest, and so on to \n solve the equation s = L[0]*m_0 + L[1]*m_1 + ... + L[n-1]*m_(n-1)\n return: the sum of the multipliers or \"no solution\" if greedy approach does \n not yield a set of multipliers such that the equation sums to 's'\n \"\"\"\n multipliers, remainder = list(), s\n \n for num in L:\n multipliers.append(remainder // num)\n remainder = remainder % num\n \n return sum(multipliers) if remainder == 0 else 'no solution'\n\n# Recursive take, takes some reasoning.\n\n#def greedySum(L, s):\n# if not L:\n# return 'no solution'\n# elif not s % L[0]:\n# return s // L[0]\n# else:\n# try:\n# return s//L[0] + greedySum(L[1:], s = s % L[0])\n# except TypeError:\n# return 'no solution'\n \n#print(greedySum([101, 51, 11, 2, 1], 3000), '\\n') \n## Answer 36\n#print(greedySum([30, 20, 10], 60), '\\n')\n## Answer 2\n#print(greedySum([10, 9, 8, 1], 17), '\\n')\n## Answer 8\n#print(greedySum([10, 7, 6, 3], 19), '\\n')\n## 'no solution'\n\n\ndef max_contig_sum(L):\n \"\"\" L, a list of integers, at least one positive\n Returns the maximum sum of a contiguous subsequence in L \"\"\"\n\n N, greatest = len(L), 0\n \n for b in range(N):\n for e in range(N):\n sumd = sum(L[b:e])\n if sumd > greatest:\n greatest = sumd\n \n return greatest\n\n# zum = []\n# for i in range(len(L)):\n# s = 0\n# for j in range(i, len(L)):\n# s += L[j]\n# zum.append(s)\n#\n# return max(zum)\n \nprint(max_contig_sum([-2, 6, 8, 10])) \n# Answer 24 \nprint(max_contig_sum([10, 9, 8, -1]))\n# Answer 27\nprint(max_contig_sum([-3, -2, 1, -1, -5]))\n# Answer 1\n \n "} {"blob_id": "d14df0a00cf5c88d9d398263546c7eb3c536e5a4", "repo_name": "Quoly/Algorithms_from_Coursera", "path": "/Week 7/min_weight_sum_diff.py", "length_bytes": 1650, "score": 3.546875, "int_score": 4, "content": "def merge_inverse_sort(array):\n\tif len(array) == 1:\n\t\treturn array\n\tmiddle = len(array) // 2\n\treturn merge_inverse(merge_inverse_sort(array[:middle]), merge_inverse_sort(array[middle:]))\n\ndef merge_inverse(array1, array2):\n\tinfinity = 10000000\n\tarray1.append(infinity)\n\tarray2.append(infinity)\n\ti1 = 0\n\ti2 = 0\n\tmerged_array = []\n\tfor k in range(len(array1) + len(array2) - 2):\n\t\tif array1[i1] > array2[i2] and array1[i1] != infinity or array2[i2] == infinity:\n\t\t\tmerged_array.append(array1[i1])\n\t\t\ti1 += 1\n\t\telse:\n\t\t\tmerged_array.append(array2[i2])\n\t\t\ti2 += 1\n\treturn merged_array\n\ndef min_weight_sum(lst):\n\tweights = [int(lst[i][0]) for i in range(len(lst))]\n\tlengths = [int(lst[i][1]) for i in range(len(lst))]\n\tdiffs = {}\n\tfor i in range(len(lst)):\n\t\tdifference = int(lst[i][0]) / int(lst[i][1])\n\t\tdiffs[difference] = diffs.get(difference, []) + [i]\n\tfor key in diffs.keys():\n\t\tdiffs[key] = merge_inverse_sort(diffs[key])\n\tdiffs_list = list(diffs)\n\tsorted_diffs_list = merge_inverse_sort(diffs_list)\n\tlength = 0\n\tresult = 0\n\tfor item in sorted_diffs_list:\n\t\tcurr_weights = []\n\t\tcurr_lengths = []\n\t\tfor i in diffs[item]:\n\t\t\tcurr_weights.append(weights[i])\n\t\t\tcurr_lengths.append(lengths[i])\n\t\tcurr_weights_sorted = merge_inverse_sort(curr_weights)\n\t\tfor i in curr_weights_sorted:\n\t\t\tind = curr_weights.index(i)\n\t\t\tlength += curr_lengths[ind]\n\t\t\tresult += curr_weights[ind] * length\n\treturn result\n\n\nif __name__ == '__main__':\n\tf = open('jobs.txt')\n\tlst = [item.split() for item in f.readlines()]\n\ttest1 = [[1, 1], [1, 3], [2, 2]]\n\ttest2 = [[30, 90], [10, 30], [20, 40], [30, 50], [20, 60], [10, 50]]\n\tto_count = lst\n\tprint(min_weight_sum(to_count))"} {"blob_id": "80082cb77bdaa137b9bc6f35efac848671463b73", "repo_name": "rhondacrespo/EpiProject", "path": "/epimodel.py", "length_bytes": 3480, "score": 3.578125, "int_score": 4, "content": "#! /usr/bin/env python3\n\n#rhonda crespo, carlos phillips\n#april 25, 2020\n#this is a simple epidemiology model using the SIR model developed by\n#Kermack & McKendrick in 1927. S stands for Susceptible, I is for\n#Infected, and R stands for Removed (either recovered or\n#dead). Removed are assumed to not be susceptible to the disease\n#again. The goal of the model is provide information as to the rate of\n#infection in a population for medical experts and\n#policymakers. Further implementation would incorporate how to reduce\n#infection rate (immunization, social distancing, medicine, etc).\n#Honor Code: We pledge that this program represents our own program\n#code. We received help in designing and\n#debugging my program from my friend Mark. References:\n#Hubbs, Christian. \u201cSocial Distancing to Slow the Coronavirus.\u201d\n#Medium. Available at\n#https://towardsdatascience.com/social-distancing-to-slow-the-coronavirus-768292f04296\n#\"The SIR Model,\" Availabe at\n#https://scipython.com/book/chapter-8-scipy/additional-examples/the-sir-epidemic-model/\n#Yeghikyan, George. \u201cModelling the Coronavirus Epidemic with Python:\n#Are Cities Prepared for an Epidemic?\u201d Medium. Available at\n#https://towardsdatascience.com/modelling-the-coronavirus-epidemic-spreading-in-a-city-with-python-babd14d82fa2\n#Simple Line Plots. Available at\n#https://jakevdp.github.io/PythonDataScienceHandbook/04.01-simple-line-plots.html\n#\"Pass defualt variables to matplotlib.\" Available at\n#https://stackoverflow.com/questions/41755550/pass-default-variables-to-matplotlib\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef main():\n #sets up the inital parameters\n N = 1000 #initial population\n t_max = 100 #length of time\n dt = 0.1 #change in time\n t = np.linspace(0, t_max, int(t_max/dt) + 1) #sets up graph\n init_values = N-1, 1, 0 #sets up initial values for S, I, R\n beta = 2.0 #contact rate in the population\n gamma = 1.0 #inverse of the mean infectious period\n results = sir_model(N, t, dt, beta, gamma, init_values) #runs the model\n \n \n#these are the differential equations that calculate the SIR model\ndef sir_model(N, t, dt, beta, gamma, init_values):\n S_0, I_1, R_0 = init_values #initial values for SIR\n S, I, R = [S_0], [I_1], [R_0] #empty lists for SIR\n dt = t[1] - t[0] #change in time\n for i in t: #these are the actual calculations \n next_S = int(S[-1] - (beta*S[-1]*I[-1])/N*dt)\n next_I = int(I[-1] + (beta*S[-1]*I[-1]/N-gamma* I[-1]*dt))\n next_R = int(R[-1] + (gamma*I[-1]*dt))\n S.append(next_S) #these appends the calculations to the bottom of each list\n I.append(next_I)\n R.append(next_R)\n #print('this actually worked!') #I just needed to see that it worked!\n print(S)\n print(I)\n print(R)\n plot_fun(t, S[:-1], I[:-1], R[:-1])\n return np.stack([S, I, R]).T #returns the values\n\n\n#plot the data as three separate lines for S, I, and R\ndef plot_fun(t, S, I, R):\n fig = plt.figure() #these two lines sets up the plot and axes\n ax = plt.axes()\n ax.plot(t, S, color='blue', label='Susceptible') #plots each group as a separate line on the y-axis\n ax.plot(t, I, color='red', label='Infectious')\n ax.plot(t, R, color='green', label='Removed')\n ax.set_xlabel('Time(Days)') #these label the axes\n ax.set_ylabel('Number of Individuals')\n plt.show()\n #fig, ax = plt.subplots(1)\n fig.savefig('epidemic.png') #saves to an output file\n return (fig)\n\n\n#call the main function\nmain()\n\n"} {"blob_id": "8428716f8d9505ca72ed10bf6c7573d31c5603ba", "repo_name": "kpahwani/DS-Algorithm", "path": "/data_structures/arrays/subset_sum.py", "length_bytes": 641, "score": 3.53125, "int_score": 4, "content": "# Subset Sum Problem\n\n\ndef recursive_implementation(arr, n, sum):\n if sum == 0:\n return True\n if n == 0 and sum != 0:\n return False\n if sum < arr[n-1]:\n return recursive_implementation(arr, n-1, sum)\n return recursive_implementation(arr, n-1, sum) or recursive_implementation(arr, n-1, sum - arr[n-1])\n\n\ndef dp_implementation(arr, n, sum):\n dp = [[False]*(sum+1) for _ in range(n+1)]\n for i in range(n):\n dp[i][0] = True\n\n\n\n\narr = map(int, input(\"Enter array:\").split())\nsum = input(\"Enter sum: \")\nprint(recursive_implementation(arr, len(arr), sum))\nprint(dp_implementation(arr, len(arr), sum))\n"} {"blob_id": "0ec2e9f2fcb36f32ae4220b6f35fa96529a2af30", "repo_name": "Sandeep8447/interview_puzzles", "path": "/src/main/python/com/skalicky/python/interviewpuzzles/sum_2_binary_numbers_without_converting_to_integer.py", "length_bytes": 1784, "score": 4.21875, "int_score": 4, "content": "# Task:\n#\n# Given two binary numbers represented as strings, return the sum of the two binary numbers as a new binary represented\n# as a string. Do this without converting the whole binary string into an integer.\n#\n# Here's an example and some starter code.\n#\n# def sum_binary(bin1, bin2):\n# # Fill this in.\n#\n# print(sum_binary(\"11101\", \"1011\"))\n# # 101000\nfrom typing import Tuple\n\n\ndef sum_binary_digits(binary_digit1: str, binary_digit2: str, overflow: bool) -> Tuple[str, bool]:\n if binary_digit1 == '1':\n if binary_digit2 == '1':\n if overflow:\n return '1', True\n else:\n return '0', True\n else:\n if overflow:\n return '0', True\n else:\n return '1', False\n else:\n if binary_digit2 == '1':\n if overflow:\n return '0', True\n else:\n return '1', False\n else:\n if overflow:\n return '1', False\n else:\n return '0', False\n\n\ndef sum_2_binary_numbers_without_converting_to_integer(binary_number1: str, binary_number2: str) -> str:\n overflow: bool = False\n index_in_number1: int = len(binary_number1) - 1\n index_in_number2: int = len(binary_number2) - 1\n result: str = ''\n while index_in_number1 >= 0 or index_in_number2 >= 0 or overflow:\n binary_digit1: str = binary_number1[index_in_number1] if index_in_number1 >= 0 else 0\n binary_digit2: str = binary_number2[index_in_number2] if index_in_number2 >= 0 else 0\n result_digit, overflow = sum_binary_digits(binary_digit1, binary_digit2, overflow)\n result = result_digit + result\n index_in_number1 -= 1\n index_in_number2 -= 1\n return result\n"} {"blob_id": "7852688d5d4902cf11695c72bcfb527088ee0811", "repo_name": "ematheson/Projects", "path": "/Markov Chains/Markov_Chains.py", "length_bytes": 6042, "score": 3.6875, "int_score": 4, "content": "# markov_chains.py\n\nimport numpy as np\nimport scipy as sp\nfrom scipy import linalg as la\nfrom numpy import linalg as nla\n\n\ndef random_markov(n):\n \"\"\"Create and return a transition matrix for a random Markov chain with\n 'n' states, stored as an nxn NumPy array.\n \"\"\"\n A = np.random.random((n,n))\n\n #normalize the columns\n for i in xrange(n):\n\n A[:,i] = A[:,i] / np.sum(A[:,i])\n\n return A\n\n\ndef forecast(days):\n \"\"\"Forecast tomorrow's weather given that today is hot=0.\"\"\"\n #success is 1 = cold\n\n t_matrix = np.array(([0.7, 0.6], [0.3, 0.4]))\n\n forecast = []\n today = 0\n \n for i in xrange(0, days):\n today = np.random.binomial(1, t_matrix[1, today])\n # Sample from a binomial distribution (with n=1) to choose a new state.\n\n forecast.append(today)\n\n return forecast\n\n\ndef four_state_forecast(days):\n \"\"\"Run a simulation for the weather over the specified number of days,\n with mild as the starting state, using the four-state Markov chain.\n Return a list containing the day-by-day results, not including the\n starting day.\n\n Examples:\n >>> four_state_forecast(3)\n [0, 1, 3]\n >>> four_state_forecast(5)\n [2, 1, 2, 1, 1]\n\n 0= hot, 1= mild, 2= cold, 3= freezing\n \"\"\"\n today = 1 #first day is Mild\n forecast = []\n t_matrix = np.array([[0.5, 0.3, 0.1, .0], [0.3, 0.3, 0.3, 0.3], [0.2, 0.3, 0.4, 0.5], [0., 0.1, 0.2, 0.2]])\n\n for i in xrange(0, days):\n #np.random.multinomial(1, probabilities)\n array = np.random.multinomial(1, t_matrix[:,today]) #to get the column\n #returns an array [0 ... 1 ... 0 0]\n \n #today gets set to where the 1 is in the array \n today = np.argmax(array) \n \n forecast.append(today)\n\n return forecast\n\n\ndef steady_state(A, tol=1e-12, N=40):\n \"\"\"Compute the steady state of the transition matrix A.\n\n Inputs:\n A ((n,n) ndarray): A column-stochastic transition matrix.\n tol (float): The convergence tolerance.\n N (int): The maximum number of iterations to compute.\n\n Raises:\n ValueError: if the iteration does not converge within N steps.\n\n Returns:\n x ((n,) ndarray): The steady state distribution vector of A.\n \"\"\"\n n,n = A.shape\n\n x = abs(np.random.rand(n,1))\n\n #normalize\n x = x / float(np.sum(x)) \n i = 0\n t = 1\n\n while i <= N and t >= tol:\n \n i+=1\n newx = np.dot(A, x)\n #calculate x^(k+1) = A x^k\n\n t = la.norm(newx - x, ord=np.inf)\n x = newx\n if i > N:\n raise ValueError(\"the matrix A^k does not converge\")\n break\n\n return newx\n\n\n# Problems 5 and 6\nclass SentenceGenerator(object):\n \"\"\"Markov chain creator for simulating bad English.\n\n Attributes:\n (what attributes do you need to keep track of?)\n\n Example:\n >>> yoda = SentenceGenerator(\"Yoda.txt\")\n >>> print yoda.babble()\n The dark side of loss is a path as one with you.\n \"\"\"\n\n def __init__(self, filename):\n \"\"\"Read the specified file and build a transition matrix from its\n contents. You may assume that the file has one complete sentence\n written on each line.\n \"\"\"\n self.filename = filename\n #one sentence on each line\n with open(filename, 'r') as sentence_file:\n\n my_lines = []\n\n states = [\"$tart\"]\n\n for line in sentence_file:\n\n sentence = line.strip(\"\\n\")\n my_lines.append(sentence)\n\n for s in my_lines:\n\n words = s.split(\" \")\n\n for w in words:\n if w not in states:\n states.append(w)\n \n states.append(\"$top\")\n \n first_array = np.zeros((len(states), len(states)))\n\n for line in my_lines:\n words = [\"$tart\"] + line.split(\" \") + [\"$top\"]\n #example of words = [$tart, I, am , Sam, Sam, I, am., $top] (first line)\n\n #states = [$tart, I, am, Sam, am., $top]\n indices = [states.index(w) for w in words]\n\n #becomes [0, 1, 2, 3, 3, 1, 2, 4, 5]\n\n for i in xrange(len(words)-1):\n first_array[indices[i+1], indices[i]] +=1\n #P [1 , 0] 0 --> 1\n #P [2, 1] 1 -- connected --> to 2\n\n\n first_array[-1,-1] +=1 #so no division by 0 in last column\n\n new_array = first_array / np.sum(first_array, axis=0)\n\n #print new_array.sum(axis=0) adding up columns to see if = 1\n\n self.t_matrix = new_array\n self.states = states\n\n def babble(self):\n \"\"\"Begin at the start sate and use the strategy from\n four_state_forecast() to transition through the Markov chain.\n Keep track of the path through the chain and the corresponding words.\n When the stop state is reached, stop transitioning and terminate the\n sentence. Return the resulting sentence as a single string.\n \"\"\"\n\n current_state = 0 # self.states[0]\n path = []\n\n while current_state != self.states.index(\"$top\"):\n\n array = np.random.multinomial(1, self.t_matrix[:,current_state]) #to get the column\n #returns an array [0 ... 1 ... 0 0]\n \n #current_state gets set to where the 1 is in the array \n current_state = np.argmax(array)\n path.append(current_state)\n\n path.pop() #gets rid of \"$top\"\n #return path\n #make list called \"path\" into a string\n word_list = [self.states[p] for p in path]\n\n return \" \".join(word_list)\n\n\nif __name__ == '__main__':\n #print forecast(5)\n #B = random_markov(3)\n #print steady_state(B)\n #print nla.matrix_power(B, 8) #check B_k\n #print steady_state(np.array([[0.7, 0.6], [0.3, 0.4]]))\n #print four_state_forecast(5)\n b = SentenceGenerator(\"tswift1989.txt\")\n print b\n print b.babble()"} {"blob_id": "07f2d3c45853ea453a147d734c87ae5978a89c8a", "repo_name": "joelericswanson/reverse", "path": "/data/_10_create_a_pcfg_and_flip_each_rule.py", "length_bytes": 1846, "score": 3.53125, "int_score": 4, "content": "# 10/20: Create a Probabilistic Context-Free Grammar and flip each rule\n\n# Learn a PCFG to describe the input string. Then take the \n# rules and flip each rule's right-hand side. \n# Parse candidates for reverse versions, output the one with \n# the highest probability.\n\nimport nltk\nimport random\n\ndef build_tree(word, level):\n if len(word) == 1:\n if word.lower() in \"aeiou\u00e4\u00f6\u00fc\":\n return \"(V{} {})\".format(level, word)\n return \"(C{} {})\".format(level, word)\n return \"(N{} {} {})\".format(level, \n build_tree(word[0], level), \n build_tree(word[1:], level+1))\n\ndef pcfg_reverse(word):\n s = build_tree(word, 0)\n tree = nltk.Tree.fromstring(s)\n productions = tree.productions()\n for p in productions:\n \n ##################################################\n # !!! THIS IS WHERE THE MAGIC HAPPENS !!! #\n if len(p._rhs) > 1: #\n p._rhs = (p._rhs[1], p._rhs[0]) #\n ##############################################\n \n grammar = nltk.induce_pcfg(nltk.Nonterminal(\"N0\"), productions)\n# print(grammar) # UNCOMMENT FOR A FUN TIME!\n parser = nltk.pchart.InsideChartParser(grammar)\n \n # Shuffle to generate 1000 possible words; only the correct\n # solution will be parseable with our grammar!\n for i in range(1000):\n cand = random.sample(word, len(word))\n# print(cand) # UNCOMMENT FOR A FUN TIME!\n parser.parse(cand)\n for parse in parser.parse(cand):\n if parse._ProbabilisticMixIn__prob > 0:\n# print(\"number of tries: {}\".format(i)) # UNCOMMENT!\n return \"\".join(cand)\n return \"no reverse found, try again\"\n\nprint(pcfg_reverse(\"whyyy\"))"} {"blob_id": "eb83554b9c70faa225bd526410a53405f5cc0790", "repo_name": "caboe2012/network_graphs", "path": "/App2_Project_NetworkReslience.py", "length_bytes": 6848, "score": 4.0625, "int_score": 4, "content": "''' Algorithmic_Thinking 1 - Module 2 '''\nfrom collections import deque\nimport random\n#popleft to remove and return leftmost element(the head of the queue)\n#append to add new entry\n\nGRAPH5 = {1: set([2, 4, 6, 8]),\n 2: set([1, 3, 5, 7]),\n 3: set([4, 6, 8]),\n 4: set([3, 5, 7]),\n 5: set([6, 8]),\n 6: set([5, 7]),\n 7: set([8]),\n 8: set([7]),\n 9: set([10]),\n 10: set([9]),\n 11: set([])}\n\ndef bfs_visited(ugraph,start_node):\n\t''' Takes the undirected graph ugraph and \n\tthe node start_node and returns the set consisting \n\tof all nodes that are visited by a breadth-first search \n\tthat starts at start_node'''\n\t_queue = deque()\n\t_visited = set([start_node])\n\t_queue.append(start_node)\n\twhile len(_queue) > 0:\n\t\t_current_node = _queue.popleft()\n#\t\tprint \"Node\", _current_node, \"has the\", len(ugraph[_current_node]), \"following neighbors\"\n\t\tfor _neighbor in ugraph[_current_node]:\n\t\t\tif _neighbor not in _visited:\n\t\t\t\t_visited.add(_neighbor)\n\t\t\t\t_queue.append(_neighbor)\n\treturn _visited\n\ndef cc_visited(ugraph):\n\t'''Takes the undirected graph ugraph and returns \n\ta list of sets, where each set consists of all the \n\tnodes (and nothing else) in a connected component, \n\tand there is exactly one set in the list for each \n\tconnected component in ugraph and nothing else.'''\n\t_remaining_nodes = set(ugraph.keys())\n\t_connected_components = []\n\twhile len(_remaining_nodes) > 0:\n\t\t_random_node = random.sample(_remaining_nodes,1)\n#\t\tprint \"RANDOM START NODE\", _random_node\n\t\t_random_node_connections = bfs_visited(ugraph,_random_node[0])\n\t\t_connected_components.append(_random_node_connections)\n\t\t_remaining_nodes -= _random_node_connections\n#\t\tprint _remaining_nodes\n\treturn _connected_components\n\n#print cc_visited(GRAPH5)\n\ndef largest_cc_size(ugraph):\n\t''' Takes the undirected graph ugraph and returns \n\tthe size (an integer) of the largest connected component \n\tin ugraph.'''\n\t_graph_components = cc_visited(ugraph)\n\t_largest_component = 0\n\tfor _current_component in _graph_components:\n\t\tif len(_current_component) > _largest_component:\n\t\t\t_largest_component = len(_current_component)\n#\tprint \"Largest component is\", _largest_component\n\treturn _largest_component\n\ndef compute_resilience(ugraph, attack_order):\n\t'''Takes the undirected graph ugraph, a list of nodes attack_order \n\tand iterates through the nodes in attack_order. For each node in the list, \n\tthe function removes the given node and its edges from the graph and then \n\tcomputes the size of the largest connected component for the resulting graph.'''\n\t_original_largest_component = largest_cc_size(ugraph)\n\t_resiliency_list = [_original_largest_component]\n\t_attack_queue = deque(attack_order)\n\twhile len(_attack_queue) > 0:\n#\t\tprint \"Counter\", counter\n\t\t_node_to_remove = _attack_queue.popleft()\n#\t\tprint \"Node to remove\", _node_to_remove\n\t\t_edges_to_remove = ugraph.pop(_node_to_remove)\n#\t\tprint \"Edges to remove\", _edges_to_remove\n\t\tfor _edge in _edges_to_remove:\n\t\t\tif _node_to_remove in ugraph[_edge]:\n#\t\t\t\tprint \"Edges before\", ugraph[_edge]\n\t\t\t\tugraph[_edge] -= set([_node_to_remove])\n#\t\t\t\tprint \"Edges after\", ugraph[_edge]\n#\t\tprint \"Updated Graph:\", ugraph\n\t\t_new_largest_component = largest_cc_size(ugraph)\n\t\t_resiliency_list.append(_new_largest_component)\n\treturn _resiliency_list\n\n#print compute_resilience(GRAPH5, [1,3,10])\n\n##########################################################\n# Code for creating UNDIRECTED ER graphs (from Homework 1, Pseudo-Code on Q10)\nimport random\n\ndef undirected_ER(n,p):\n\ttemp = {}\n\tV = range(0,n)\n\tfor node_i in V:\n\t\ttemp[node_i] = set()\n\tfor node_i in V:\n\t\tfor node_j in V:\n\t\t\ta = random.random()\n\t\t\tif node_i == node_j:\n\t\t\t\tpass\n\t\t\telif a < p and node_j not in temp[node_i]:\n\t\t\t\ttemp[node_i].add(node_j)\n\t\t\t\ttemp[node_j].add(node_i)\n\treturn temp\n\n#test1 = undirected_ER(5,0.5)\n#for k,v in test1.items():\n#\tprint k, \":\", v\n\n##########################################################\n# Code for creating UPA Graphs\n\ndef make_complete_ugraph(num_nodes):\n\t''' returns a dictionary corresponding \n\tto a complete undirected graph with the specified '''\n\t_undirected_graph = {}\n\tfor _node_row in range(num_nodes):\n\t\t_num_edges = set([])\n\t\tfor _node_col in range(num_nodes):\n\t\t\tif _node_row != _node_col:\n\t\t\t\t_num_edges.add(_node_col)\n\t\t_undirected_graph[_node_row] = _num_edges\n\treturn _undirected_graph\n\ndef UPA(n,m):\n\t'''Compute randomly generated additional nodes from m to n\n\tstarting from a complete graph of m nodes.'''\n\tV = range(0,m)\n\tE = make_complete_ugraph(m)\n\ttotal_in_degrees = m*(m-1)\n\trandomly_added_nodes = 0\n\tfor i in range(m,n):\n\t\ttotal_in_degrees += randomly_added_nodes\n\t\tV_prime = 0\n\n##########################################################\n# code to create random_order -> \n\ndef random_order(ugraph):\n\t'''Takes a graph and returns a list of the nodes in the graph in some random order.'''\n\tV = ugraph.keys()\n\tn = len(V)\n\trandom_node_order = random.sample(V,n)\n\treturn random_node_order \n\n\n##########################################################\n# Code to determine optimal p for the undirected ER graph\ndef optimal_p(trials, p):\n\t'''Takes a number of trials, and a list of p values in order to\n\tfind the optimal value p such that the number of edges in the ER graph\n\tis approximately the same as the Computer Network and UPA graph'''\n\ttrial_results = {}\n\ttotal_edges_per_trial = 0\n\tfor percent in p:\n\t\ttrial_results[percent] = set()\n\t\tfor trial in range(trials):\n\t\t\ttest = undirected_ER(1239, percent)\n\t\t\tfor node in test.keys():\n\t\t\t\ttotal_edges_per_trial += len(test[node])\n\t\t\tsingle_count_edges = total_edges_per_trial/2.\n\t\t\ttrial_results[percent].add(single_count_edges)\n\t\t\ttotal_edges_per_trial = 0\n\treturn trial_results\n\n\ndef calculate_out_degrees(ugraph):\n\ttotal_edges_per_trial = 0\n\tfor node in ugraph.keys():\n\t\ttotal_edges_per_trial += len(ugraph[node])\n\tans = total_edges_per_trial/2\n\treturn ans\n\ndef copy_graph(graph):\n \"\"\"\n Make a copy of a graph\n \"\"\"\n new_graph = {}\n for node in graph:\n new_graph[node] = set(graph[node])\n return new_graph\n\ndef delete_node(ugraph, node):\n \"\"\"\n Delete a node from an undirected graph\n \"\"\"\n neighbors = ugraph[node]\n ugraph.pop(node)\n for neighbor in neighbors:\n ugraph[neighbor].remove(node)\n\n\n##########################################################\n# Compute Resilience of ER, UPA and Computer Network when removing one node at a time\ndef calculate_network_resilience(ugraph):\n\tugraph_copy = copy_graph(ugraph)\n\tattack_nodes = random_order(ugraph_copy)\n\tcc_sizes = compute_resilience(ugraph_copy,attack_nodes)\n\treturn cc_sizes\n\n\n\n#lst = [0.002,0.0025,0.003]\n#testing = optimal_p(50,lst)\n#for each in lst:\n#\tprint each, \":\", sum(testing[each])/len(testing[each])\n# RESULTS\n#0.002 : 3063.57142857\n#0.0025 : 3839.0\n#0.003 : 4594.82608696"} {"blob_id": "08d88a8909d01428901208e29b08240944144e29", "repo_name": "jiejie168/hash_leetcodes", "path": "/BinaryTreePostorderTraversal.py", "length_bytes": 2132, "score": 3.65625, "int_score": 4, "content": "__author__ = 'Jie'\n\"\"\"\n145. Binary Tree Postorder Traversal\n\nGiven a binary tree, return the postorder traversal of its nodes' values.\nExample:\nInput: [1,null,2,3]\n 1\n \\\n 2\n /\n 3\n\nOutput: [3,2,1]\nFollow up: Recursive solution is trivial, could you do it iteratively?\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\nclass Solution:\n def postorderTraversal(self, root: TreeNode):\n # naive algorithm, using recursive\n res=[]\n self.helper(root,res)\n return res\n\n def helper(self,root,res):\n if root is None:\n # the terminate condition\n return\n if root.left !=None:\n self.helper(root.left,res)\n if root.right !=None:\n self.helper(root.right,res)\n res.append(root.val)\n\n def postorderTraversal_2(self,root):\n # use the iterative method\n # adopt the reverse_postorderTraversal: pseudo code of recursive.\n # rev_postorder(root):\n # if root is None:\n # return\n # print (node.val)\n # rev_postorder(root-> right)\n # rev_postorder(root-> left)\n\n if root is None:\n return\n stack1=[] # initialize stacks\n stack2=[] # stack for store the reversed results\n stack1.append(root)\n while stack1:\n # iterative for the reverse-postorder\n curr=stack1.pop()\n stack2.append(curr.val)\n if curr.left !=None:\n # be careful! the stack is LIFO, so last search right node in reverse,\n # equal to fist push left node in stack\n stack1.append(curr.left)\n if curr.right!=None:\n stack1.append(curr.right)\n while stack2:\n # reversed the output of stack2\n node=stack2.pop()\n stack1.append(node)\n return stack1\nsolution=Solution()\nroot=TreeNode(1)\nroot.right=TreeNode(2)\nroot.right.left=TreeNode(3)\nans=solution.postorderTraversal_2(root)\nprint (ans)\n"} {"blob_id": "61c9ffb88e669b86595ade35218920e949a50cb3", "repo_name": "wulfebw/algorithms", "path": "/scripts/recursion/product_sequence.py", "length_bytes": 1128, "score": 3.828125, "int_score": 4, "content": "\nimport numpy as np\n\ndef compute_prod_seq_term(n):\n '''\n O(n) ? or O(n^2) ?\n how many recursive calls are made? n \n how much work per call? n \n so O(n^2)\n the recurrence is T(n) = T(n-1) + O(n)\n which you can't apply the master theorem to \n but you can just logic it out\n there are n levels to this tree \n each time you do the current levels worth of work \n but this turns out to be O(n) work at each level \n so overall it's O(n^2)\n '''\n if n == 0:\n return 0\n first = int((n - 1) * n / 2) + 1\n last = first + n\n return np.prod(range(first, last)) + compute_prod_seq_term(n-1)\n\ndef compute_prod_better(n):\n '''\n\n '''\n\n def recurse(c, i):\n if c == n + 1:\n return 0 \n else:\n v = np.prod(range(i, i + c))\n return v + recurse(c + 1, i + c)\n return recurse(1, 1)\n\nif __name__ == '__main__':\n inputs = [\n 1,\n 5,\n 7\n ]\n expect = [\n 1,\n 365527,\n 6006997207\n ]\n for i,e in zip(inputs, expect):\n print(e)\n print(compute_prod_seq_term(i))\n print(compute_prod_better(i))"} {"blob_id": "3310ebaeeb45761e15c82f0b8db3eb4f0c81ad79", "repo_name": "leilalu/algorithm", "path": "/\u5251\u6307offer/\u7b2c\u4e00\u904d/search/29.\u65cb\u8f6c\u6570\u7ec4\u7684\u6700\u5c0f\u6570\u5b57.py", "length_bytes": 4045, "score": 4.0, "int_score": 4, "content": "\"\"\"\n\u9898\u76ee\u63cf\u8ff0\n\n\u628a\u4e00\u4e2a\u6570\u7ec4\u6700\u5f00\u59cb\u7684\u82e5\u5e72\u4e2a\u5143\u7d20\u642c\u5230\u6570\u7ec4\u7684\u672b\u5c3e\uff0c\u6211\u4eec\u79f0\u4e4b\u4e3a\u6570\u7ec4\u7684\u65cb\u8f6c\u3002\n\u8f93\u5165\u4e00\u4e2a\u3010\u975e\u9012\u51cf\u6392\u5e8f\u3011\u7684\u6570\u7ec4\u7684\u4e00\u4e2a\u3010\u65cb\u8f6c\u3011\uff0c\u8f93\u51fa\u65cb\u8f6c\u6570\u7ec4\u7684\u6700\u5c0f\u5143\u7d20\u3002\n\u4f8b\u5982\u6570\u7ec4{3,4,5,1,2}\u4e3a{1,2,3,4,5}\u7684\u4e00\u4e2a\u65cb\u8f6c\uff0c\u8be5\u6570\u7ec4\u7684\u6700\u5c0f\u503c\u4e3a1\u3002\nNOTE\uff1a\u7ed9\u51fa\u7684\u6240\u6709\u5143\u7d20\u90fd\u5927\u4e8e0\uff0c\u82e5\u6570\u7ec4\u5927\u5c0f\u4e3a0\uff0c\u8bf7\u8fd4\u56de0\u3002\n\n\"\"\"\n\n\nclass Solution1:\n def minNumberInRotateArray(self, rotateArray):\n \"\"\"\n \u66b4\u529b\u6cd5\uff1a\u904d\u5386\u6240\u6709\u7684\u5143\u7d20\n \u89c2\u5bdf\u65cb\u8f6c\u6570\u7ec4\uff0c\u65cb\u8f6c\u6570\u7ec4\u6700\u5927\u7684\u5143\u7d20\u5e94\u8be5\u4e0e\u6700\u5c0f\u7684\u5143\u7d20\u76f8\u90bb\uff0c\u4e14\u6700\u5927\u503c\u5728\u5de6\uff0c\u6700\u5c0f\u503c\u5728\u53f3\uff0c\u5373\u5de6\u8fb9\u5927\u4e8e\u53f3\u8fb9\n \u539f\u6570\u7ec4\u662f\u4ece\u5de6\u5230\u53f3\u975e\u9012\u51cf\u7684\uff0c\u5373\u5de6\u8fb9\u5c0f\u4e8e\u53f3\u8fb9\n \u56e0\u6b64\u627e\u5230\u65cb\u8f6c\u6570\u7ec4\u4e2d\u5de6\u8fb9\u5927\u4e8e\u53f3\u8fb9\u7684\u5730\u65b9\u5c31\u80fd\u627e\u5230\u6700\u5c0f\u503c\u3002\n\n \u9700\u8981\u6ce8\u610f\u7684\u662f\uff0c\u7531\u4e8e\u6570\u7ec4\u662f\u975e\u9012\u51cf\u7684\uff0c\u56e0\u6b64\u5f53\u6700\u5927\u503c\u4e0e\u6700\u5c0f\u503c\u76f8\u7b49\u65f6\uff0c\u6574\u4e2a\u6570\u7ec4\u7684\u5143\u7d20\u90fd\u76f8\u7b49\uff0c\u90fd\u53ea\u6709\u4e00\u4e2a\u6570\uff0c\u76f4\u63a5\u8fd4\u56de\u8fd9\u4e2a\u6570\u5373\u53ef\u3002\n\n \u65f6\u95f4\u590d\u6742\u5ea6\u662fO(n)\n \u7a7a\u95f4\u590d\u6742\u5ea6\u662fO(1)\n\n \"\"\"\n if len(rotateArray) == 0:\n return 0\n for i in range(len(rotateArray)):\n if rotateArray[i] < rotateArray[i-1]:\n return rotateArray[i]\n # \u6700\u5927\u503c\u548c\u6700\u5c0f\u503c\u76f8\u7b49\n return rotateArray[0]\n\n\nclass Solution2:\n def minNumberInRotateArray(self, rotateArray):\n \"\"\"\n \u4e8c\u5206\u6cd5\uff1a\n \u770b\u5230\u6392\u5e8f\u6570\u7ec4\u5e94\u8be5\u60f3\u5230\u4e8c\u5206\u67e5\u627e\n \u89c2\u5bdf\u65cb\u8f6c\u6570\u7ec4\u7279\u70b9\uff0c\u65cb\u8f6c\u6570\u7ec4\u53ef\u4ee5\u5212\u5206\u4e3a\u4e24\u4e2a\u6392\u5e8f\u6570\u7ec4\uff0c\u5e76\u4e14\u524d\u9762\u7684\u5b50\u6570\u7ec4\u7684\u5143\u7d20\u90fd\u5927\u4e8e\u6216\u8005\u7b49\u4e8e\u540e\u9762\u5b50\u6570\u7ec4\u7684\u5143\u7d20\u3002\u6700\u5c0f\u503c\u6070\u597d\u662f\u8fd9\u4e24\u4e2a\u5143\u7d20\u7684\u5206\u754c\u7ebf\n \u9996\u5143\u7d20\u5e94\u8be5\u5927\u4e8e\u6216\u8005\u7b49\u4e8e\u6700\u540e\u4e00\u4e2a\u5143\u7d20 \u6545 rotateArray[left] >= rotateArray[right]\n\n \u5982\u679c\u4e2d\u95f4\u5143\u7d20\u4f4d\u4e8e\u524d\u9762\u7684\u9012\u589e\u5b50\u6570\u7ec4\uff0c\u90a3\u4e48\u5b83\u5e94\u8be5\u5927\u4e8e\u6216\u8005\u7b49\u4e8e\u9996\u5143\u7d20\uff0c\u6700\u5c0f\u503c\u5e94\u8be5\u5728\u4e2d\u95f4\u5143\u7d20\u53f3\u4fa7 left = mid left\u4ecd\u7136\u5728\u524d\u9762\u7684\u9012\u589e\u5b50\u6570\u7ec4\n \u5982\u679c\u4e2d\u95f4\u5143\u7d20\u4f4d\u4e8e\u540e\u9762\u7684\u9012\u589e\u5b50\u6570\u7ec4\uff0c\u90a3\u4e48\u5b83\u5e94\u8be5\u5c0f\u4e8e\u6216\u8005\u7b49\u4e8e\u5c3e\u5143\u7d20\uff0c\u6700\u5c0f\u503c\u5e94\u8be5\u5728\u4e2d\u95f4\u5143\u7d20\u5de6\u4fa7 right = mid right\u4ecd\u7136\u5728\u540e\u9762\u7684\u9012\u589e\u5b50\u6570\u7ec4\n\n \u6700\u7ec8left\u6307\u5411\u524d\u9762\u6570\u7ec4\u7684\u6700\u540e\u4e00\u4e2a\u5143\u7d20\uff0cright\u6307\u5411\u540e\u9762\u6570\u7ec4\u7684\u7b2c\u4e00\u4e2a\u5143\u7d20\uff0c\u5373\u4e3a\u6700\u5c0f\u503c\uff0c\u8fbe\u5230\u5faa\u73af\u7ed3\u675f\u7684\u6761\u4ef6\u3002\n \u6700\u7ec8\u8fd4\u56de\u53f3\u8fb9\u7684\u5143\u7d20\n\n \u9700\u8981\u6ce8\u610f\u7684\u7279\u4f8b\uff1a\n 1\u3001\u5982\u679c\u628a\u6392\u5e8f\u6570\u7ec4\u7684\u524d\u97620\u4e2a\u5143\u7d20\u642c\u5230\u6700\u540e\u9762\uff0c\u90a3\u4e48\u8fd8\u662f\u6392\u5e8f\u6570\u7ec4\u672c\u8eab\uff0c\u5e94\u8be5\u8fd4\u56de\u7b2c\u4e00\u4e2a\u5143\u7d20 \u56e0\u6b64\u628a\u3010mid\u521d\u59cb\u5316\u4e3a0\u3011\n\n \u91c7\u7528\u4e86\u4e8c\u5206\u67e5\u627e\uff0c\u56e0\u6b64\u65f6\u95f4\u590d\u6742\u5ea6\u662fO(logn)\n \u7a7a\u95f4\u590d\u6742\u5ea6\u662fO(1)\n\n \"\"\"\n\n if len(rotateArray) == 0:\n return 0\n\n left = 0\n right = len(rotateArray) - 1\n # \u5982\u679c\u628a\u6392\u5e8f\u6570\u7ec4\u7684\u524d\u97620\u4e2a\u5143\u7d20\u642c\u5230\u6700\u540e\u9762\uff0c\u90a3\u4e48\u8fd8\u662f\u6392\u5e8f\u6570\u7ec4\u672c\u8eab\uff0c\u5e94\u8be5\u8fd4\u56de\u7b2c\u4e00\u4e2a\u5143\u7d20 \u56e0\u6b64\u628a\u3010mid\u521d\u59cb\u5316\u4e3a0\u3011\n mid = 0\n while rotateArray[left] >= rotateArray[right]:\n if right - left == 1:\n mid = right\n break\n mid = left + ((right - left) >> 1)\n\n # \u5982\u679c \u4e0b\u6807\u4e3a left right \u548c mid \u7684\u4e09\u4e2a\u5143\u7d20\u76f8\u7b49\n # \u5219\u53ea\u80fd\u91c7\u53d6\u987a\u5e8f\u67e5\u627e\n if rotateArray[left] == rotateArray[mid] and rotateArray[mid] == rotateArray[right]:\n return self.minInOrder(rotateArray, left, right)\n\n if rotateArray[mid] >= rotateArray[left]:\n left = mid\n elif rotateArray[mid] <= rotateArray[right]:\n right = mid\n\n return rotateArray[mid]\n\n def minInOrder(self, rotateArray, start, end):\n res = rotateArray[0]\n for i in range(start+1, end+1):\n if res > rotateArray[i]:\n res = rotateArray[i]\n return res\n\n\nif __name__ == '__main__':\n rotateArray = [1, 0, 1, 1, 1, 1]\n s = Solution2()\n res = s.minNumberInRotateArray(rotateArray)\n print(res)"} {"blob_id": "4796317d41e3a78627fe1a524c8e348c905fd24a", "repo_name": "goalong/lc", "path": "/v1/72.edit-distance.106836202.ac.py", "length_bytes": 1196, "score": 3.625, "int_score": 4, "content": "#\n# [72] Edit Distance\n#\n# https://leetcode.com/problems/edit-distance/description/\n#\n# algorithms\n# Hard (32.45%)\n# Total Accepted: 110.6K\n# Total Submissions: 340.7K\n# Testcase Example: '\"\"\\n\"\"'\n#\n# \n# Given two words word1 and word2, find the minimum number of steps required to\n# convert word1 to word2. (each operation is counted as 1 step.)\n# \n# \n# \n# You have the following 3 operations permitted on a word:\n# \n# \n# \n# a) Insert a character\n# b) Delete a character\n# c) Replace a character\n# \n#\nclass Solution(object):\n def minDistance(self, word1, word2):\n \"\"\"\n :type word1: str\n :type word2: str\n :rtype: int\n \"\"\"\n #\n len1 = len(word1)\n len2 = len(word2)\n # initialization\n dp = [ [0 for j in xrange(len2 + 1)] for i in xrange(len1 + 1) ]\n for i in xrange(len1 + 1):\n dp[i][0] = i\n for j in xrange(len2 + 1):\n dp[0][j] = j\n # dp\n for i in xrange(1, len1 + 1):\n for j in xrange(1, len2 + 1):\n dp[i][j] = dp[i-1][j-1] if word1[i-1] == word2[j-1] else min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1\n return dp[len1][len2]\n \n"} {"blob_id": "b01da5d8d51c5d7e4017041b91f58876ffcf532c", "repo_name": "CvsBurak/test-cases", "path": "/python-cases/largestrange.py", "length_bytes": 664, "score": 3.71875, "int_score": 4, "content": "# gets the largest range of numbers contained in the array\ndef largestRange(arr):\n nums = {x:0 for x in arr} #creating hashmap for elements in arr\n left = right = 0\n \n for num in arr:\n if nums[num] == 0:\n left_count = num - 1\n right_count = num + 1\n \n \n while left_count in nums:\n nums[left_count] = 1\n left_count -= 1\n left_count += 1\n \n while right_count in nums:\n nums[right_count] = 1\n right_count += 1\n right_count -= 1\n \n if (right - left) <= (right_count - left_count):\n right = right_count\n left = left_count\n \n return [left, right]\n \n"} {"blob_id": "3eebb69e178befbda33ea9fe8289474751af63b8", "repo_name": "Reyloso/Test_Ingenieria_datos", "path": "/fibonacci.py", "length_bytes": 2958, "score": 4.1875, "int_score": 4, "content": "\nfrom math import log10, sqrt\n\n\"\"\"\nSerie Fibonacci\nLa secuencia de Fibonacci es una secuencia de n\u00fameros con la relaci\u00f3n:\n\ud835\udc39\ud835\udc5b=\ud835\udc39\ud835\udc5b-1\ud835\udc39\ud835\udc5b-2, donde \ud835\udc391=1 y \ud835\udc392=1\nResulta que \ud835\udc39541 contiene 113 d\u00edgitos y es el primer n\u00famero de Fibonacci donde los\n\u00faltimos 9 d\u00edgitos son una secuencia pan-digital (que contiene todos los n\u00fameros del 1 al 9,\npero no es necesario que est\u00e9n en orden). Por otro lado \ud835\udc392749 contiene 757 d\u00edgitos y es el\nprimer n\u00famero de Fibonacci donde los primeros 9 d\u00edgitos son una secuencia pan-digital. \ud835\udc39\ud835\udc58 es\nel primer n\u00famero de Fibonacci donde los primeros 9 d\u00edgitos son una secuencia pan-digital y\ndonde los \u00faltimos 9 d\u00edgitos tambi\u00e9n son una secuencia pan-digital.\n\u00bfCu\u00e1nto es \ud835\udc3e?\n\nserie fibonacci es una serie infinita en la que la suma de dos n\u00fameros consecutivos \nsiempre da como resultado el siguiente n\u00famero (1+1=2; 13+21=34).\n\nLos n\u00fameros y las f\u00f3rmulas pandigitales son aquellas expresiones matem\u00e1ticas en cuya construcci\u00f3n \naparecen al menos una vez todos los d\u00edgitos que constituyen la base de numeraci\u00f3n en la que est\u00e1n escritos. La base 10 es la m\u00e1s usada para construir expresiones \npandigitales, pues se trata de la base m\u00e1s peque\u00f1a que usa todos los guarismos existentes (0, 1, 2, ,3 ,4 ,5, 6, 7, 8, 9) para denotar n\u00fameros.\n\n\"\"\"\n\n# en este caso se utiliza una formula racion de oro\nM = 1000000000\n# segun la formula se le saca la raiz cuadrada a 5\nsqrt5 = sqrt(5)\n# esto da solo los primeros 10 digitos\nfn = (sqrt5+1)/2\n# siguiendo la formula halla el logaritmo de fn\nphi = log10(fn)\n# y luego se procede a hallar el logaritmo a raiz cuadrada de 5\nlogsqrt5 = log10(sqrt5)\n\ndef test(n):\n \"\"\"fucion que valida si n es un numero pan digital mientras no contenga todos los numeros\"\"\"\n if n < 100000000: return False\n flags = [0]*10\n flags[0] = 1\n while n > 0:\n n, m = n//10, n%10\n if flags[m]: return False\n flags[m] = 1\n return True\n\ndef run():\n a, b, k = 1, 1, 2\n while True:\n \"\"\" while que buscar la serie fibonacci entre todos los numeros de la serie hasta llegar a \ud835\udc392749 \"\"\"\n a, b, k = b, a+b, k+1\n a, b, k = b % M, (a+b)%M, k+1\n # se comprueba si el numero cumple con las condiciones de pan digital\n if test(b):\n # se k se multiplica por el log de fn y se le resta el logaritmo de la raiz cuadrada de 5\n phik = phi*k-logsqrt5\n # se halla n donde 10 elevenado a la potencia de la variable donde se almaceno el resultado de la multiplicacion anterior \n # menos el logaritmo de fn por el valor de k mas 9 y luego se usa // para hacer una divicion entre 10 el resultado sera un numero entero\n n = int(10**(phik-int(phi*k)+9))//10\n # se usa de forma recursiva esta funcion para determinar si el valor de n cumple las condiciones para ser pandigital\n if test(n): break\n\n print(\"el valor de k es\", k)\n\nrun()\n\n"} {"blob_id": "052572c6897362cac7d2c19f51709bb55315c9d8", "repo_name": "shuai000/Localization-HMM", "path": "/hmm.py", "length_bytes": 21125, "score": 3.546875, "int_score": 4, "content": "\"\"\"\n1. Hidden Markov Based Module\n2. Ref: Lawrence tutorial on HMM & selected application in speech recognition\n3. Author: Shuai Sun 05/09/2018\n-----------------------------------------------------------------------------\nParameter needs to be specified once a HMM model instance is initialized\n\"\"\"\nimport numpy as np\nimport scipy.io as sio\nimport scipy.stats as stats\nfrom math import log, exp\nimport matplotlib.pyplot as plt\n\n\nclass HiddenMarkov:\n\n def __init__(self, para_hmm, specification=False):\n \"\"\"\n Called right after setting the HMM model\n Set the hidden Markov parameters\n :param para_hmm: dictionary format\n :return:\n \"\"\"\n assert 'state_num' in para_hmm, \" HMM state number is not provided!\"\n self.Ns = para_hmm['state_num']\n self.Pi = np.ones(self.Ns) / self.Ns\n\n assert 'anchor_num' in para_hmm, \" HMM anchor number is not provided!\"\n self.Na = para_hmm['anchor_num']\n\n assert 'initial_p' in para_hmm, \" HMM state initial probability is not provided!\"\n self.Pi = para_hmm['initial_p']\n assert self.Pi.shape[0] == self.Ns, \" Number of state doesn't match model initial probability size! \"\n\n assert 'transition_p' in para_hmm, \" HMM state transition probability is not provided!\"\n self.Pt = para_hmm['transition_p']\n self.log_pt = np.zeros((self.Ns, self.Ns))\n for i in range(self.Ns):\n for j in range(self.Ns):\n if self.Pt[i, j] != 0:\n self.log_pt[i, j] = log(self.Pt[i, j])\n else:\n self.log_pt[i, j] = float('-inf')\n assert self.Pt.shape == (self.Ns, self.Ns), \" Number of state doesn't match model transition probability\"\n\n assert 'training_type' in para_hmm, \" HMM training type is not provided!\"\n # 1. from_loading 2. from_external 3. from_data\n training_from = para_hmm['training_type']\n if training_from == 'from_loading':\n self.training() # load training parameter\n elif training_from == 'from_external':\n if 'mean' in para_hmm:\n self.mean = para_hmm['mean']\n assert self.mean.shape == (self.Na, self.Ns), \\\n \" Number of state/observation don't match model mean size!\"\n else:\n assert False, \" NO mean parameter provided to the model!\"\n if 'cov' in para_hmm:\n self.cov = para_hmm['cov']\n assert self.cov.shape == (self.Na, self.Na, self.Ns), \\\n \"Number of state/observation don't match model cov size!\"\n else:\n assert False, \"NO COV parameter provided to the model!\"\n elif training_from == 'not_provided':\n pass\n else:\n raise Exception('training_type is in wrong format: from_loading, from_external or not_provided!')\n\n assert 'likelihood_from' in para_hmm, \"HMM observation filename is not provided!\"\n if para_hmm['likelihood_from'] == 'from_external': # filename in None means likelihood is provided outside\n assert 'likelihood' in para_hmm, \"HMM observation likelihood is not provided\"\n self.likelihood = para_hmm['likelihood']\n assert self.likelihood.shape[1] == self.Ns, \"Number of state doesn't match likelihood data size\"\n elif para_hmm['likelihood_from'] == 'from_file':\n assert 'filename' in para_hmm, \"HMM evaluation data filename is not provided!\"\n data, status = self.data_extraction(para_hmm['filename'], 0)\n self.likelihood = self.get_likelihood(data, status)\n elif para_hmm['likelihood_from'] == 'not_provided':\n pass\n else:\n raise Exception(\"Likelihood from is not in the library!\")\n\n if specification: # Print out the HMM model set up in the console\n self.model_specification(para_hmm)\n\n def set_likelihood(self, likelihood_value):\n self.likelihood = likelihood_value\n assert self.likelihood.shape[1] == self.Ns, \"Number of state doesn't match likelihood data size\"\n\n @staticmethod\n def state_estimation(alpha):\n st = alpha.argmax(axis=1)\n st = st[:] + 1 # physically map to state index\n return st\n\n def set_gaussin(self, mu, cov):\n self.mean = mu\n self.cov = cov\n\n assert self.mean.shape == (self.Na, self.Ns), \"Number of state and observation don't match model mean size!\"\n assert self.cov.shape == (self.Na, self.Na, self.Ns), \"Number of state/observation don't match model cov size!\"\n\n def model_specification(self, para):\n print(\"\\n\\n-------- HIDDEN MARKOV MODEL ---------\")\n print(\"State num: {}\".format(self.Ns))\n if para['training_type'] == 'not_provided':\n print(\"Training data is not specified initially, provided later!\")\n else:\n print(\"Training data is from: {}\".format(para['training_type']))\n\n if para['likelihood_from'] == 'not_provided':\n print(\"Likelihood data is not specified initially, provided later!\")\n else:\n print(\"Likelihood is from: {}\".format(para['likelihood_from']))\n print(\"-------- HIDDEN MARKOV MODEL ---------\\n\")\n\n def forward_process(self, p_type='none', interval_index=None, prior=None):\n \"\"\"\n Hidden Markov Model standard forward process\n func: Recursively compute forward variable\n alpha_t(i) = p(O_[1:t], q_t = S_i|lambda)\n :param p_type: propagation type: 'none', 'posterior', 'logform' (logform is not used, has to be approximated)\n :return: forward variable and estimation based on purely forward process\n \"\"\"\n if interval_index is None:\n like_value = self.likelihood\n else:\n assert len(interval_index) == 2, \"interval format wrong!\"\n assert interval_index[1] > interval_index[0], \"interval format wrong!\"\n like_value = self.likelihood[interval_index[0]:interval_index[1] + 1, :]\n alpha = np.zeros((like_value.shape[0], self.Ns))\n\n # Forward Algorithm\n if p_type == 'none':\n for i_time in range(like_value.shape[0]):\n if i_time == 0: # initialization\n alpha[i_time, :] = self.Pi * like_value[i_time, :] # Eq.(19)\n else: # induction\n alpha[i_time, :] = self.forward_propagation(alpha[i_time - 1, :]) \\\n * like_value[i_time, :] # Eq. (20)\n s_forward = self.state_estimation(alpha)\n return s_forward, alpha\n elif p_type == 'posterior':\n ct = np.zeros(like_value.shape[0])\n # initialization, if no pripr provided, then it is assumed as uniform\n if prior is None:\n alpha[0, :] = self.Pi * like_value[0, :] # Eq.(19)\n else:\n alpha[0, :] = prior * like_value[0, :]\n ct[0] = sum(alpha[0, :])\n alpha[0, :] = alpha[0, :] / ct[0]\n # induction\n for i_time in range(1, like_value.shape[0]):\n alpha[i_time, :] = self.forward_propagation(alpha[i_time - 1, :]) \\\n * like_value[i_time, :] # Eq. (20)\n ct[i_time] = sum(alpha[i_time, :])\n alpha[i_time, :] = alpha[i_time, :] / ct[i_time] # scaling p(si,o_1:t) -> p(si|o_1:t)\n log_likelihood = sum(np.log(ct))\n s_forward = self.state_estimation(alpha)\n return s_forward, alpha, log_likelihood, ct\n elif p_type == 'logform':\n for i_time in range(like_value.shape[0]):\n if i_time == 0: # initialization\n for i in range(self.Ns):\n alpha[i_time, i] = np.log(self.Pi[i]) + np.log(like_value[i_time, i])\n else:\n alpha[i_time, :] = self.forward_propagation(alpha[i_time - 1, :], p_type='log')\n for i in range(self.Ns):\n alpha[i_time, i] = alpha[i_time, i] + np.log(like_value[i_time, i])\n log_likelihood = 0\n for i in range(self.Ns):\n log_likelihood = log_likelihood + exp(alpha[-1, i])\n log_likelihood = log(log_likelihood)\n s_forward = self.state_estimation(alpha)\n return s_forward, alpha, log_likelihood\n\n def forward_propagation(self, alpha_p, p_type='none'):\n\n if p_type == 'none':\n alpha_n = np.sum(alpha_p * self.Pt.T, axis=1)\n elif p_type == 'log':\n alpha_n = np.zeros(len(alpha_p))\n for j in range(self.Ns):\n for i in range(self.Ns):\n alpha_n[j] = alpha_n[j] + exp(alpha_p[i] + np.log(self.Pt[i, j]))\n alpha_n[j] = np.log(alpha_n[j])\n return alpha_n\n\n def backward_process(self, p_type='none', scaling_factor=None, interval_index=None):\n\n if interval_index is None:\n like_value = self.likelihood\n else:\n assert len(interval_index) == 2, \"interval format wrong!\"\n assert interval_index[1] > interval_index[0], \"interval format wrong!\"\n like_value = self.likelihood[interval_index[0]:interval_index[1] + 1, :]\n beta = np.zeros((like_value.shape[0], self.Ns))\n\n if p_type == 'none':\n # 1. initialization\n beta[-1, :] = 1\n # 2. induction (propagation back)\n for i_time in range(like_value.shape[0] - 2, -1, -1):\n beta[i_time, :] = self.back_propagation(beta[i_time + 1, :], like_value[i_time + 1, :])\n elif p_type == 'posterior':\n assert scaling_factor is not None, \"The scaling fator is not provided!\"\n beta[-1, :] = 1 / scaling_factor[-1]\n for i_time in range(like_value.shape[0] - 2, -1, -1):\n beta[i_time, :] = self.back_propagation(beta[i_time + 1, :], like_value[i_time + 1, :])\n beta[i_time, :] = beta[i_time, :] / scaling_factor[i_time]\n return beta\n\n def back_propagation(self, beta_p, like_value):\n beta_n = np.sum(beta_p * like_value * self.Pt, axis=1)\n return beta_n\n\n def forward_backward(self, p_type='posterior', window_length=None, e_position='middle'):\n \"\"\"\n Forward-Backward algorithm for optimal state estimation\n This optimality criterion maximizes the expected number of correct individual states\n j = arg max_(i){y_t(i) = p(qt = Si | O, lambda)}\n :param filename: filename of txt that contains RSS data\n :param window_length, the sliding window length for the batch processing based forward backward algorithm\n if it is none, then the whole data sequence is processed\n otherwise, it is window sliding based, move one step forward each time\n -----.------\n -----.------\n :param e_position, by default, 'middle', the middle one is output as current estimate within the windonw length\n 'front', 'end' are the alternative\n :return: the estimated state sequence, st, as well as the posterior probability, yita\n \"\"\"\n\n if window_length is None: # process the whole data sequence\n if p_type == 'none':\n alpha = self.forward_process()[1]\n beta = self.backward_process()\n elif p_type == 'posterior':\n output = self.forward_process(p_type=p_type)\n alpha = output[1]\n ct = output[3]\n beta = self.backward_process(p_type=p_type, scaling_factor=ct)\n\n yita = alpha * beta\n st = self.state_estimation(yita)\n return st, yita\n else: # sliding window based processing\n end_time = self.likelihood.shape[0]\n st = np.zeros(end_time)\n yita = np.zeros((end_time, self.Ns))\n\n if e_position == 'middle':\n e_index = int(window_length / 2)\n elif e_position == 'front':\n e_index = 0\n elif e_position == 'end':\n e_index = -1\n else:\n pass # drop an error here\n\n assert window_length > 1, \"window length can't be less than one!\"\n window_length = window_length - 1 # python start from zero\n # initial step\n interval = [0, window_length]\n output = self.forward_process(p_type=p_type, interval_index=interval, prior=None)\n alpha = output[1]\n ct = output[3]\n beta = self.backward_process(p_type=p_type, scaling_factor=ct, interval_index=interval)\n\n yita_temp = alpha * beta\n st_temp = self.state_estimation(yita_temp)\n # assign from begiing to the middle point\n yita[0:e_index + 1, :] = yita_temp[0:e_index + 1, :]\n st[0:e_index + 1] = st_temp[0: e_index + 1]\n\n for i_time in range(1, end_time - window_length):\n interval = [i_time, i_time + window_length]\n output = self.forward_process(p_type=p_type, interval_index=interval, prior=yita_temp[0, :])\n alpha = output[1]\n ct = output[3]\n beta = self.backward_process(p_type=p_type, scaling_factor=ct, interval_index=interval)\n\n yita_temp = alpha * beta\n st_temp = self.state_estimation(yita_temp)\n\n if i_time == end_time - window_length - 1:\n # the end of sliding window, take the estimate result of all\n yita[i_time + e_index: end_time, :] = yita_temp[e_index:window_length + 1, :]\n st[i_time + e_index: end_time] = st_temp[e_index:window_length + 1]\n else: # normal sliding process\n yita[i_time + e_index, :] = yita_temp[e_index, :]\n st[i_time + e_index] = st_temp[e_index]\n return st, yita\n\n def likelihood_com(self, data, status):\n \"\"\"\n Function: compute likelihood based on multivariate Gaussian distribution\n :param data: RSS for all anchors, note that\n :param status: indicator of which anchor is active, the probability evaluation\n will change size based on status's configuration\n :return: likelihood probability, normalized to one\n \"\"\"\n likelihood = np.zeros(self.Ns)\n if data.any():\n for i in range(self.Ns):\n mean_i = self.mean[status, i]\n cov_i = self.cov[:, :, i][status][:, status] # take the sub-covariance\n likelihood[i] = stats.multivariate_normal.pdf(\n data, mean_i, cov_i)\n norm_sum = likelihood.sum()\n likelihood = likelihood / norm_sum\n else:\n likelihood[:] = 1 / self.Ns\n return likelihood\n\n def get_likelihood(self, data, status):\n\n likelihood = np.zeros((data.shape[0], self.Ns))\n\n for i_time in range(data.shape[0]):\n tempstatus = np.where(status[i_time, :] == 1)[0]\n tempdata = data[i_time, :][tempstatus]\n\n # Following is due to requirement from stats library\n # maybe not efficient\n reformat_data = np.zeros((1, len(tempstatus)))\n reformat_data[0, :] = tempdata\n\n likelihood[i_time, :] = self.likelihood_com(reformat_data, tempstatus)\n\n return likelihood\n\n def training(self, t_type='load', train_data=[]):\n if t_type == 'load':\n self.mean = sio.loadmat('data/mean_x.mat')['mean_x']\n self.cov = sio.loadmat('data/cov_x.mat')['cov_x']\n elif t_type == 'list': # I don't understand the meaning of list nowadays\n rx_num = train_data[0].shape[1]\n state_num = len(train_data)\n train_mean = np.zeros((rx_num, state_num))\n train_cov = np.zeros((rx_num, rx_num, state_num))\n for idx, val in enumerate(train_data):\n tmp_mean = val.mean(axis=0)\n tmp_error = val - tmp_mean\n tmp_cov = np.dot(tmp_error.T, tmp_error) / (val.shape[0] - 1)\n train_mean[:, idx] = tmp_mean\n train_cov[:, :, idx] = tmp_cov\n return train_mean, train_cov\n\n def para_estimation(self, re_type='posterior', max_iternum=10):\n \"\"\"\n Function: Estimate HMM parameter (Pt, Pi) using EM algorithm\n Ref: Rabiner tutorial paper 05/10/2018\n :param re_type: control the forward and backward process (scaled or not)\n by default it is scaled\n :param max_iternum: the maximum iteration number used\n :return: estimated Pt, Pi, and log_likelihood sequence for each iteration\n IMPORTANT: please note that it automatically update self.Pt and self.Pi in the instance\n \"\"\"\n if re_type == 'posterior':\n a, alpha, c, ct = self.forward_process(p_type=re_type)\n beta = self.backward_process(p_type=re_type, scaling_factor=ct)\n log_likelihood = sum(np.log(ct))\n elif re_type == 'none':\n a, alpha, = self.forward_process(p_type=re_type)\n beta = self.backward_process(p_type=re_type)\n log_likelihood = log(sum(alpha[-1, :]))\n\n like_value = self.likelihood\n finish_time = alpha.shape[0]\n log_likelihood_all = np.zeros(max_iternum + 1)\n log_likelihood_all[0] = log_likelihood\n count = 0\n increment_likelihood = 1\n while count < max_iternum and increment_likelihood > 1e-6:\n print(\"Iteration: \", count + 1)\n count = count + 1\n # Estimation for transition probability\n transition_p = np.zeros((self.Ns, self.Ns))\n for i in range(self.Ns):\n for j in range(self.Ns):\n num = 0\n den = 0\n for t in range(finish_time - 1):\n num = num + alpha[t, i] * self.Pt[i, j] * like_value[t + 1, j] * beta[t + 1, j]\n den = den + alpha[t, i] * beta[t, i]\n transition_p[i, j] = num / den\n transition_p[i, :] = transition_p[i, :] / sum(transition_p[i, :])\n # Estimation for initial probability\n initial_p = alpha[0, :] * beta[0, :]\n initial_p = initial_p / sum(initial_p)\n self.Pi = initial_p # update initial probability\n self.Pt = transition_p # update transition probability\n # re-compute forward and backward variables\n if re_type == 'posterior':\n a, alpha, c, ct = self.forward_process(p_type=re_type)\n beta = self.backward_process(p_type=re_type, scaling_factor=ct)\n log_likelihood_new = sum(np.log(ct))\n elif re_type == 'none':\n a, alpha, = self.forward_process(p_type=re_type)\n beta = self.backward_process(p_type=re_type)\n log_likelihood_new = np.log(sum(alpha[-1, :]))\n increment_likelihood = (log_likelihood_new - log_likelihood) / abs(log_likelihood)\n log_likelihood = log_likelihood_new\n log_likelihood_all[count] = log_likelihood_new\n\n log_likelihood_all = log_likelihood_all[0: count + 1]\n return transition_p, initial_p, log_likelihood_all\n\n\nif __name__ == '__main__':\n import pickle\n\n state_num, anchor_num = 12, 8\n save_file = 'data1104.txt'\n # mean, cov, likelihood\n f = open(save_file, 'rb')\n trained_para = pickle.load(f)\n f.close()\n\n Pt = np.array([[.6, .4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [.25, .5, .25, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, .2, .4, .2, 0, 0, .2, 0, 0, 0, 0, 0], [0, 0, .25, .5, .25, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, .25, .5, .25, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0.25, .5, 0, .25, 0, 0, 0, 0],\n [0, 0, .1, 0, 0, 0, .4, .2, .15, 0, 0, 0.15], [0, 0, 0, 0, 0, 0.25, .25, .5, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, .25, 0, .5, .25, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, .4, .6, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, .6, .4], [0, 0, 0, 0, 0, 0, .25, 0, 0, 0, .25, .5]])\n\n para_hmm = {'state_num': state_num, 'anchor_num': anchor_num, 'initial_p': 1 / state_num * np.ones(state_num),\n 'transition_p': Pt, 'training_type': 'from_external',\n 'mean': trained_para[0], 'cov': trained_para[1],\n 'likelihood_from': 'from_external', 'likelihood': trained_para[2]}\n\n hmm = HiddenMarkov(para_hmm, specification=True)\n\n # parameter re-estimation\n pt_hmm, ip, max_likeli = hmm.para_estimation(max_iternum=2)\n\n print(\"The trained transition is:\")\n print(pt_hmm)\n\n fig, ax = plt.subplots(1, 2, figsize=(8, 4), dpi=80, facecolor='w', edgecolor='r')\n a1 = ax[0].matshow(Pt, cmap='viridis')\n a2 = ax[1].matshow(pt_hmm, cmap='viridis')\n plt.show()\n\n"} {"blob_id": "c37a1aef6c44f1ee72f8b818f894ae73b99416dd", "repo_name": "cody-brock/toy-problems", "path": "/valid_pandrome_2.py", "length_bytes": 2126, "score": 3.671875, "int_score": 4, "content": "# Runtime: 92 ms, faster than 81.22% of Python online submissions for Valid Palindrome II.\n# Memory Usage: 14.4 MB, less than 33.69% of Python online submissions for Valid Palindrome II.\nclass Solution(object):\n def validPalindrome_improved(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n \n l = 0\n r = len(s)-1\n \n while l < r:\n if s[l] != s[r]:\n del_l = s[l+1:r+1]\n del_r = s[l:r]\n return self._isPalindrome(del_l) or self._isPalindrome(del_r)\n l += 1\n r -= 1\n \n return True\n\n def _isPalindrome(self, s):\n return s == s[::-1]\n\ndef validPalindrome_naive(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n \n # Helper function used to recursively verify palindromes\n def helper(str, left, right, skip_used):\n while left <= right:\n\n # If we encounter a non-palindromic duo...\n if s[left] != s[right]:\n\n # If we have already deleted a character, return False\n if skip_used:\n return False\n\n # If we have not yet deleted a character, then...\n if not skip_used:\n \n # Recursively call function with each pointer adjusted\n # and having marked skip_used as True\n if helper(str, left, right-1, True) == True:\n return True\n \n if helper(str, left+1, right, True) == True:\n return True\n \n # If neither of the above returned True, we return False\n return False\n\n # The letters matched, so we move our pointers closer\n left = left + 1\n right = right - 1\n \n # If our pointers are now touching or crossed, then we have \n # verified all characters and can return True\n if left >= right:\n return True\n \n return helper(s, 0, len(s)-1, False)"} {"blob_id": "2f8861a8d5d3c2d1697436e94c4ebd6da2f36316", "repo_name": "miblazej/pie", "path": "/lista_start_stop.py", "length_bytes": 3366, "score": 3.65625, "int_score": 4, "content": "from list1 import ListNode\nfrom lists_function import add_end\n\n# Funckja przyjmujaca trzy elementy :\n# Pierwszy czlon listy\n# start oraz stop, elementy listy od start do stop wlacznie powinny miec zamieniona kolejnosc\n# pierwszy element czlonu listy ma indeks jeden zakladam ze glowa nie jest pustym elementem\n\n\ndef odwrocSubListe(glowa, start, stop):\n # stworzenie czlonow listy majacych przechowac wskazniki do pierwszego czlonu\n # zamiany oraz ostatniego czlonu zamiany\n # do zrobienia jutro\n start_zmiany = ListNode(0, glowa)\n for _ in range(1, start):\n start_zmiany = start_zmiany.next\n # w tym momencie start_zmiany jest poczatkiem kt\u00f3r\u0105 mam odwr\u00f3ci\u0107\n # proces odwrocenia listy\n sublista_iter = start_zmiany.next\n for _ in range(stop - start):\n temp = sublista_iter.next\n sublista_iter.next, temp.next, start_zmiany.next = (\n temp.next, start_zmiany.next, temp)\n return glowa.next\n\n\ndef odwrocListe(glowa):\n pre = glowa\n glowa = glowa.next\n pre.next = None\n while(1):\n pre, glowa.next, glowa = (glowa, pre, glowa.next)\n if (glowa.next is None):\n break\n glowa.next = pre\n return glowa\n\n\nL1 = ListNode(1)\nlast = L1\nfor i in range(2, 10, 2):\n L2 = ListNode(i)\n add_end(last, L2)\n last = L2\n\n# napisz program ktory zabieraj jako imput pojedynczo polaczona liste oraz nie niegatywne\n# liczby typu int k oraz odwraca wtedy k czesci. Jezeli liczba czlonow n w liscie nie jest\n# mnoznikiem liczby k zostaw ostatnie n modulo k czlonow niezmienionych. Nie zmieniaj wartosci\n# ktore sa zapisane w czlonach\n\n\ndef coenty(L1, k):\n if (k < 1):\n return L1\n elif (k == 1):\n return odwrocListe(L1)\n # caly proces wydaje sie byc troche niejasny dla mnie z powodu braku swojej uzytecznosci\n # mimo tego opracowalem algorytm polegajacy na zmianie wskaznika w co k-tym elemencie\n # co w rezultacie skutkuje zamiana miejsc w szeregu listy na pozycjach k orz k-1\n # w zwiazku z dowolnym k podanym na wejscu funkcji potrzebny jest licznik resetujacy sie\n # po kazdej operacji zamiany potrzebna bedzie zmiana wartosci czterech zmiennych\n # 1. wskaznik na element k-1 ma wskazywac na element k\n # 2. wskaznik na element k+1 ma wskazywc na element k-1\n # 3. wskaznik na element k ma wskazywac na element k+1\n # deklaracja zmiennej licznik\n licznik = 2\n # przeprowdzanie operacji opisanych wczesniej sa potrzebne\n # 1. pre_2 - obiekt ktorego pole next nalezy zmienic w przypadku licznikia == k\n # 2. prze - obiekt ktorego pole next nalezy zmienic w przypadku licznika == k\n # 3. aktualny - obiekt ktorego pole next nalezy zmienic w przypadku licnzika == k\n while(L1.next is not None):\n if (licznik == k):\n n = L1.next\n nn = L1.next.next\n nnn = L1.next.next.next\n nn.next = n # wskaznik z elementu o indeksie 2 wskazuje na drugi element\n n.next = nnn # wskaznik z elementu o indeksie 1 wskazuje na czwarty element\n L1 = nnn # zmiana aktualnej pozycji okna na pierwszy element nastepujacy po zmianie indeksow\n licznik = 1 # potrzebne aby zachowac odstepy o szerokosci k\n else:\n # update licznika oraz update zmiennej L1\n licznik += 1\n L1 = L1.next\n return L1\n\n\ncoenty(L1, 2)\n"} {"blob_id": "7cac553480088b7bf613799900690ce9388e7447", "repo_name": "erijpkema/slurm-jobinfo", "path": "/pynumparser.py", "length_bytes": 14702, "score": 3.703125, "int_score": 4, "content": "#!/usr/bin/python2\n#\n# Works with either Python v2.7+ or v3.3+\n#\n\"\"\"\nThis module provides two classes for use in parsing string form of numbers and\nnumber sequences: NumberSequence and Number.\n\n1. pynumparser.NumberSequence\n\n * Simple parsing for intuitive representation of number sequences.\n * Optional lower and/or upper limits can be enforced.\n * Handles integer or floating point numbers.\n * Subsequences can have step values other than one (1).\n * Designed to work well with an argparse.ArgumentParser, including well\n formed errors when syntax or limits are violated.\n * Provides a class method to convert number sequences into the string form:\n\n * Parsing Examples:\n \"5\" ==> (5,)\n \"1,3,8\" ==> (1, 3, 8)\n \"8-10,30\" ==> (8, 9, 10, 30)\n \"5-30/5,100\" ==> (5, 10, 15, 20, 25, 30, 100)\n \"8,10+3\" ==> (8, 10, 11, 12, 13)\n\n * Encoding Example:\n (5, 10, 15, 20, 25, 30, 100, 101, 102, 110) ==> \"5-30/5,100-102,110\"\n\n2. pynumparser.Number\n\n * Simple way to impose limits on numbers from command line or config files.\n * Either or both lower and upper limits can be provided.\n * Handles integer and floating point numbers.\n * Designed to work well with an argparse.ArgumentParser, including well\n formed errors when limits are violated.\n\nExample Usage:\n\n #!/usr/bin/env python\n import argparse\n import pynumrange\n\n # Use in an argparser to parse a sequence or a limited number:\n parser = argparse.ArgumentParser(description=\"pynumrange example\")\n parser.add_argument('-n', '--numbers', default=[],\n help=\"A sequence of numbers from 0..100\",\n type=pynumrange.NumberSequence(int, limits=(0, 100))\n parser.add_argument('-i', '--int', default=[], action='append',\n help=\"A number in the range 1..10; multiple use okay\",\n type=pynumrange.Number(int, limits=(1, 10))\n parser.add_argument('direct', nargs='*')\n opts = parser.parse_args()\n print(\"ArgumentParser: numbers = %s\" % opts.numbers)\n\n ## Or just create a parser and call it directly:\n num_parser = pynumrange.NumberSequence(float, limits=(-1000, +1000))\n for number in opts.direct:\n num_range = num_parser(number)\n print('Direct from (\"%s\"): %s' % (number, num_range))\n\"\"\"\n\nimport math\nimport re\nversion = '1.4.1'\n\ndescription = ('A library to parse arguments of numbers and number ' +\n 'sequences, usable directly or with argparse. Allows' +\n ' concise representation of contiguous or non-contiguous' +\n ' sequences. Example: 1,5-10,40-50/5,200+100/25')\n\n_SEQPATT = re.compile('^(.*[^-+e])([-+])([-+]?[.0-9][^-+]*([Ee][-+]?[0-9]+)?)$')\n\n\nclass NumberSequence(object):\n \"\"\"This class parses concise numeric patterns into a numeric\n sequence, intended to be used directly, or with\n argparse.ArgumentParser. Numeric patterns are of the form:\n\n SEQUENCE := SUBSEQ [ ',' SEQUENCE ]\n SUBSEQ := LOWER [ '-' UPPER [ '/' STRIDE ]]\n SUBSEQ := LOWER [ '+' INCREMENT [ '/' STRIDE ]]\n\n Where all terminals (LOWER, UPPER, STRIDE) must be valid numbers.\n Example: \"1,5-7,20-30/5\" would return: (1, 5, 6, 7, 20, 25, 30)\n Example: \"10-40/17,1+2\" would return: (10, 27, 34, 1, 2, 3)\n\n Instances can also efficiently test for membership in a sequence, eg:\n\n VALID_INPUTS = \"0,10-20\"\n parser = pynumparser.NumberSequence(int)\n\n if parser.contains(VALID_INPUTS, num):\n handle_user_input(num)\"\"\"\n\n def __init__(self, numtype=int, limits=None, generator=False):\n self.numtype = numtype\n self.generator = generator\n if numtype not in (int, float):\n raise ValueError(\"NumberSequence: Invalid numeric type: \" +\n str(numtype))\n self.lowest, self.highest = limits or (None, None)\n self.error = None\n\n def __repr__(self):\n text = self.numtype.__name__.capitalize() + \"Sequence\"\n if None not in (self.lowest, self.highest):\n text += \" (from %s to %s)\" % (self.lowest, self.highest)\n elif self.lowest is not None:\n text += \" (at least %s)\" % self.lowest\n elif self.highest is not None:\n text += \" (not over %s)\" % self.highest\n if self.error:\n text += ', ERROR: \"%s\"' % self.error\n return text\n\n @classmethod\n def _range(cls, lower, upper, delta):\n while lower <= upper:\n yield lower\n lower += delta\n\n def _error(self, tag, fmt, *args):\n self.error = tag\n raise ValueError(\"NumberSequence: \" + (tag and tag + \" \") +\n (fmt.format(args) if args else fmt))\n\n def _subsequences(self, text):\n for nss, subseq in enumerate(text.split(',')):\n if not subseq:\n self._error(\"Empty subsequence\",\n \"Subsequence #{} is empty\", nss)\n tag = \"Subsequence \\\"{}\\\": \".format(subseq)\n if '/' in subseq:\n if '-' not in subseq[1:] and '+' not in subseq[1:]:\n self._error(\"Missing UPPER\",\n tag + \"STEP w/o UPPER (\\\"{}\\\")\", subseq)\n lowup, step = subseq.split('/')\n try:\n step = self.numtype(step)\n except Exception:\n self._error(\"Invalid STEP\",\n tag + \"Invalid STEP(\\\"{}\\\")\", step)\n if step <= 0:\n self._error(\"STEP must be positive\", tag +\n \"STEP must be positive (\\\"{}\\\")\".format(step))\n else:\n lowup, step = subseq, 1\n\n # We handle all of: \"-5\", \"2\", \"-3-5\", \"-3--1\", \"3-21\",\n # and \"1e-5-1.001e-5/1e-8\", \"-20+10\", \"-2e+2+1e02\"\n seq = _SEQPATT.match(lowup)\n if seq:\n lower, sep, upper = seq.group(1, 2, 3)\n try:\n lower = self.numtype(lower)\n except ValueError:\n self._error(\"Invalid LOWER\", tag +\n \"LOWER({}) is invalid\".format(lower))\n try:\n upper = self.numtype(upper)\n except ValueError:\n self._error(\"Invalid UPPER\", tag +\n \"UPPER({}) is invalid\".format(upper))\n if sep == '+':\n upper += lower\n if upper < lower:\n self._error(\"UPPER self.highest:\n self._error(\"UPPER too large\", tag +\n \"UPPER({}) cannot be greater than ({})\".format(\n upper, self.highest))\n\n yield (tag, nss, subseq, lower, upper, step)\n\n def xparse(self, text):\n \"\"\"This is a generator for the numbers that 'parse()' returns.\n Use this (rather than 'parse()') in the same way you would use\n 'xrange()' in lieu of 'range()'.\"\"\"\n self.error = None\n for nss, tag, subseq, lower, upper, step in self._subsequences(text):\n for num in self._range(lower, upper, step):\n yield num\n\n def contains(self, text, number):\n \"\"\"Returns true if the given NUMBER is contained in this range.\"\"\"\n if isinstance(number, (tuple, list)):\n return tuple(self.contains(text, num) for num in number)\n try:\n number = self.numtype(number)\n except (TypeError, ValueError):\n return False\n for nss, tag, subseq, lower, upper, step in self._subsequences(text):\n if number in (lower, upper):\n return True\n if lower < number and number < upper:\n if (number - lower) % step == 0:\n return True\n elif self.numtype == float:\n # We compare to within 10 PPM (0.001%); arbitrary but good.\n epsilon = step / 1e5\n if (abs(number - lower + epsilon) % step) < 2 * epsilon:\n return True\n return False\n\n def parse(self, text):\n \"\"\"This returns a tuple of numbers.\"\"\"\n return tuple(self.xparse(text))\n\n def __call__(self, text):\n if self.generator:\n return self.xparse(text)\n return self.parse(text)\n\n @classmethod\n def encode(cls, sequence):\n \"\"\"Convert a list/tuple of numbers into a string form. This uses the\n \"str(n)\" operator for each piece, there is no explicit formatting.\n\n @param sequence the tuple or list of numbers to be combined.\n @returns a str form for the sequence.\"\"\"\n\n if not sequence:\n return \"\"\n\n # Return the delta that occurs most often in the given SEQ.\n def delta(seq, start=1, width=4):\n seq = seq[start:start + width]\n if len(seq) < 2:\n return 1\n # First order delta.\n _seq = [seq[i + 1] - seq[i] for i in range(len(seq) - 1)]\n # Count and sorted.\n pairs = [(_seq.count(i), i) for i in set(_seq)]\n pairs.append((2, 1)) # favor '1'\n return sorted(pairs, reverse=True)[0][1]\n\n # Start with the first number, and iterate looking ahead for longer\n # runs of the same step value.\n result = []\n base = sequence[0]\n last = base\n term = str(base)\n ndel = delta(sequence, 0)\n for i, num in enumerate(sequence[1:]):\n if num == (last + ndel):\n last += ndel\n continue\n # Use \"4,5\" not \"4-5\"\n if last == (base + ndel):\n result.append(term)\n term = str(last)\n\n # With a \"-\" and maybe a \"/\".\n elif last > base:\n term += \"-\" + str(last)\n if ndel != 1:\n term += \"/\" + str(ndel)\n result.append(term)\n ndel = delta(sequence, i + 2)\n base = num\n last = base\n term = str(base)\n if last > base:\n term += \"-\" + str(last)\n if ndel != 1:\n term += \"/\" + str(ndel)\n result.append(term)\n return \",\".join(result)\n\n\nclass Number(object):\n \"\"\"This class can be used directly or with argparse.ArgumentParser,\n to parse numbers and enforce lower and/or upper limits on their values.\n\n Example:\n * Number(limits=(0,100))\n Would return an int value, which must be from 0 to 100, inclusive.\n * Number(limits=(5,None))\n Would return an int value, which must be no less than 5.\n * Number(numtype=float, limits=(-1000, 1000))\n Would return a float value, from -1000 to 1000 inclusive.\n \"\"\"\n def __init__(self, numtype=int, limits=None):\n if numtype not in (int, float):\n raise ValueError(\"Number: Invalid numeric type: \" +\n str(numtype))\n self.lowest, self.highest = limits or (None, None)\n self.numtype = numtype\n self.typename = {int: 'Integer', float: 'Float'}.get(self.numtype)\n self.error = None\n\n def __repr__(self):\n text = self.typename\n if None not in (self.lowest, self.highest):\n text += \" (from %s to %s)\" % (self.lowest, self.highest)\n elif self.lowest is not None:\n text += \" (at least %s)\" % self.lowest\n elif self.highest is not None:\n text += \" (not over %s)\" % self.highest\n if self.error:\n text += ', ERROR: \"%s\"' % self.error\n return text\n\n def _error(self, tag, fmt, *args):\n self.error = tag\n raise ValueError(\"{}: {}{}\".format(self.typename, (tag and tag + \" \"),\n fmt.format(args) if args else fmt))\n\n def parse(self, text):\n \"\"\"This returns a tuple of numbers.\"\"\"\n self.error = None\n try:\n value = self.numtype(text)\n except ValueError:\n self._error(\"Parse Error\",\n \"invalid {} value: '{}'\".format(self.typename, text))\n self._isvalid(value, error=True)\n return value\n\n def contains(self, number):\n \"\"\"Returns true if the given NUMBER is valid and within the limits.\"\"\"\n if isinstance(number, (tuple, list)):\n return tuple(self.contains(num) for num in number)\n # We explicitly allow testing if a float range contains an integer:\n if self.numtype is float and isinstance(number, int):\n number = float(number)\n return self._isvalid(number, error=False)\n\n def _isvalid(self, number, error):\n # Raise the error, or just return False.\n call = self._error if error else lambda *args: False\n if not isinstance(number, self.numtype):\n return call(\"Invalid Type\",\n \"Invalid {} value ({})\".format(\n self.typename.lower(), number))\n elif math.isinf(number):\n return call(\"Infinite Value\",\n \"Numeric values cannot be infinite ({})\".format(number))\n elif self.lowest is not None and number < self.lowest:\n return call(\"Too Low\",\n \"Value ({}) must not be less than {}\".format(\n number, self.lowest))\n elif self.highest is not None and number > self.highest:\n return call(\"Too High\",\n \"Value ({}) must not be higher than {}\".format(\n number, self.highest))\n return True\n\n def __call__(self, text):\n return self.parse(text)\n"} {"blob_id": "cf34ecf9f1f6c0cc0c0b792c262c701454bd1eac", "repo_name": "lamstephanie/sasmodels", "path": "/sasmodels/kernelcl.py", "length_bytes": 19823, "score": 4.125, "int_score": 4, "content": "\"\"\"\nGPU driver for C kernels\n\nThere should be a single GPU environment running on the system. This\nenvironment is constructed on the first call to :func:`env`, and the\nsame environment is returned on each call.\n\nAfter retrieving the environment, the next step is to create the kernel.\nThis is done with a call to :meth:`GpuEnvironment.make_kernel`, which\nreturns the type of data used by the kernel.\n\nNext a :class:`GpuData` object should be created with the correct kind\nof data. This data object can be used by multiple kernels, for example,\nif the target model is a weighted sum of multiple kernels. The data\nshould include any extra evaluation points required to compute the proper\ndata smearing. This need not match the square grid for 2D data if there\nis an index saying which q points are active.\n\nTogether the GpuData, the program, and a device form a :class:`GpuKernel`.\nThis kernel is used during fitting, receiving new sets of parameters and\nevaluating them. The output value is stored in an output buffer on the\ndevices, where it can be combined with other structure factors and form\nfactors and have instrumental resolution effects applied.\n\nIn order to use OpenCL for your models, you will need OpenCL drivers for\nyour machine. These should be available from your graphics card vendor.\nIntel provides OpenCL drivers for CPUs as well as their integrated HD\ngraphics chipsets. AMD also provides drivers for Intel CPUs, but as of\nthis writing the performance is lacking compared to the Intel drivers.\nNVidia combines drivers for CUDA and OpenCL in one package. The result\nis a bit messy if you have multiple drivers installed. You can see which\ndrivers are available by starting python and running:\n\n import pyopencl as cl\n cl.create_some_context(interactive=True)\n\nOnce you have done that, it will show the available drivers which you\ncan select. It will then tell you that you can use these drivers\nautomatically by setting the PYOPENCL_CTX environment variable.\n\nSome graphics cards have multiple devices on the same card. You cannot\nyet use both of them concurrently to evaluate models, but you can run\nthe program twice using a different device for each session.\n\nOpenCL kernels are compiled when needed by the device driver. Some\ndrivers produce compiler output even when there is no error. You\ncan see the output by setting PYOPENCL_COMPILER_OUTPUT=1. It should be\nharmless, albeit annoying.\n\"\"\"\nimport os\nimport warnings\nimport logging\n\nimport numpy as np\n\ntry:\n import pyopencl as cl\n # Ask OpenCL for the default context so that we know that one exists\n cl.create_some_context(interactive=False)\nexcept Exception as exc:\n warnings.warn(\"OpenCL startup failed with ***\"+str(exc)+\"***; using C compiler instead\")\n raise RuntimeError(\"OpenCL not available\")\n\n# CRUFT: pyopencl < 2017.1 (as of June 2016 needs quotes around include path)\ndef _quote_path(v):\n \"\"\"\n Quote the path if it is not already quoted.\n\n If v starts with '-', then assume that it is a -I option or similar\n and do not quote it. This is fragile: -Ipath with space needs to\n be quoted.\n \"\"\"\n return '\"'+v+'\"' if v and ' ' in v and not v[0] in \"\\\"'-\" else v\n\nif hasattr(cl, '_DEFAULT_INCLUDE_OPTIONS'):\n cl._DEFAULT_INCLUDE_OPTIONS = [_quote_path(v) for v in cl._DEFAULT_INCLUDE_OPTIONS]\n\nfrom pyopencl import mem_flags as mf\nfrom pyopencl.characterize import get_fast_inaccurate_build_options\n\nfrom . import generate\n\n# The max loops number is limited by the amount of local memory available\n# on the device. You don't want to make this value too big because it will\n# waste resources, nor too small because it may interfere with users trying\n# to do their polydispersity calculations. A value of 1024 should be much\n# larger than necessary given that cost grows as npts^k where k is the number\n# of polydisperse parameters.\nMAX_LOOPS = 2048\n\n\nENV = None\ndef environment():\n \"\"\"\n Returns a singleton :class:`GpuEnvironment`.\n\n This provides an OpenCL context and one queue per device.\n \"\"\"\n global ENV\n if ENV is None:\n ENV = GpuEnvironment()\n return ENV\n\ndef has_type(device, dtype):\n \"\"\"\n Return true if device supports the requested precision.\n \"\"\"\n if dtype == generate.F32:\n return True\n elif dtype == generate.F64:\n return \"cl_khr_fp64\" in device.extensions\n elif dtype == generate.F16:\n return \"cl_khr_fp16\" in device.extensions\n else:\n return False\n\ndef get_warp(kernel, queue):\n \"\"\"\n Return the size of an execution batch for *kernel* running on *queue*.\n \"\"\"\n return kernel.get_work_group_info(\n cl.kernel_work_group_info.PREFERRED_WORK_GROUP_SIZE_MULTIPLE,\n queue.device)\n\ndef _stretch_input(vector, dtype, extra=1e-3, boundary=32):\n \"\"\"\n Stretch an input vector to the correct boundary.\n\n Performance on the kernels can drop by a factor of two or more if the\n number of values to compute does not fall on a nice power of two\n boundary. The trailing additional vector elements are given a\n value of *extra*, and so f(*extra*) will be computed for each of\n them. The returned array will thus be a subset of the computed array.\n\n *boundary* should be a power of 2 which is at least 32 for good\n performance on current platforms (as of Jan 2015). It should\n probably be the max of get_warp(kernel,queue) and\n device.min_data_type_align_size//4.\n \"\"\"\n remainder = vector.size % boundary\n if remainder != 0:\n size = vector.size + (boundary - remainder)\n vector = np.hstack((vector, [extra] * (size - vector.size)))\n return np.ascontiguousarray(vector, dtype=dtype)\n\n\ndef compile_model(context, source, dtype, fast=False):\n \"\"\"\n Build a model to run on the gpu.\n\n Returns the compiled program and its type. The returned type will\n be float32 even if the desired type is float64 if any of the\n devices in the context do not support the cl_khr_fp64 extension.\n \"\"\"\n dtype = np.dtype(dtype)\n if not all(has_type(d, dtype) for d in context.devices):\n raise RuntimeError(\"%s not supported for devices\"%dtype)\n\n source = generate.convert_type(source, dtype)\n # Note: USE_SINCOS makes the intel cpu slower under opencl\n if context.devices[0].type == cl.device_type.GPU:\n source = \"#define USE_SINCOS\\n\" + source\n options = (get_fast_inaccurate_build_options(context.devices[0])\n if fast else [])\n program = cl.Program(context, source).build(options=options)\n #print(\"done with \"+program)\n return program\n\n\n# for now, this returns one device in the context\n# TODO: create a context that contains all devices on all platforms\nclass GpuEnvironment(object):\n \"\"\"\n GPU context, with possibly many devices, and one queue per device.\n \"\"\"\n def __init__(self):\n # find gpu context\n #self.context = cl.create_some_context()\n\n self.context = None\n if 'PYOPENCL_CTX' in os.environ:\n self._create_some_context()\n\n if not self.context:\n self.context = _get_default_context()\n\n # Byte boundary for data alignment\n #self.data_boundary = max(d.min_data_type_align_size\n # for d in self.context.devices)\n self.queues = [cl.CommandQueue(context, context.devices[0])\n for context in self.context]\n self.compiled = {}\n\n def has_type(self, dtype):\n \"\"\"\n Return True if all devices support a given type.\n \"\"\"\n dtype = generate.F32 if dtype == 'fast' else np.dtype(dtype)\n return any(has_type(d, dtype)\n for context in self.context\n for d in context.devices)\n\n def get_queue(self, dtype):\n \"\"\"\n Return a command queue for the kernels of type dtype.\n \"\"\"\n for context, queue in zip(self.context, self.queues):\n if all(has_type(d, dtype) for d in context.devices):\n return queue\n\n def get_context(self, dtype):\n \"\"\"\n Return a OpenCL context for the kernels of type dtype.\n \"\"\"\n for context, queue in zip(self.context, self.queues):\n if all(has_type(d, dtype) for d in context.devices):\n return context\n\n def _create_some_context(self):\n \"\"\"\n Protected call to cl.create_some_context without interactivity. Use\n this if PYOPENCL_CTX is set in the environment. Sets the *context*\n attribute.\n \"\"\"\n try:\n self.context = [cl.create_some_context(interactive=False)]\n except Exception as exc:\n warnings.warn(str(exc))\n warnings.warn(\"pyopencl.create_some_context() failed\")\n warnings.warn(\"the environment variable 'PYOPENCL_CTX' might not be set correctly\")\n\n def compile_program(self, name, source, dtype, fast=False):\n \"\"\"\n Compile the program for the device in the given context.\n \"\"\"\n key = \"%s-%s%s\"%(name, dtype, (\"-fast\" if fast else \"\"))\n if key not in self.compiled:\n context = self.get_context(dtype)\n logging.info(\"building %s for OpenCL %s\"\n % (key, context.devices[0].name.strip()))\n program = compile_model(context, source, np.dtype(dtype), fast)\n self.compiled[key] = program\n return self.compiled[key]\n\n def release_program(self, name):\n \"\"\"\n Free memory associated with the program on the device.\n \"\"\"\n if name in self.compiled:\n self.compiled[name].release()\n del self.compiled[name]\n\ndef _get_default_context():\n \"\"\"\n Get an OpenCL context, preferring GPU over CPU, and preferring Intel\n drivers over AMD drivers.\n \"\"\"\n # Note: on mobile devices there is automatic clock scaling if either the\n # CPU or the GPU is underutilized; probably doesn't affect us, but we if\n # it did, it would mean that putting a busy loop on the CPU while the GPU\n # is running may increase throughput.\n #\n # Macbook pro, base install:\n # {'Apple': [Intel CPU, NVIDIA GPU]}\n # Macbook pro, base install:\n # {'Apple': [Intel CPU, Intel GPU]}\n # 2 x nvidia 295 with Intel and NVIDIA opencl drivers installed\n # {'Intel': [CPU], 'NVIDIA': [GPU, GPU, GPU, GPU]}\n gpu, cpu = None, None\n for platform in cl.get_platforms():\n # AMD provides a much weaker CPU driver than Intel/Apple, so avoid it.\n # If someone has bothered to install the AMD/NVIDIA drivers, prefer them over the integrated\n # graphics driver that may have been supplied with the CPU chipset.\n preferred_cpu = platform.vendor.startswith('Intel') or platform.vendor.startswith('Apple')\n preferred_gpu = platform.vendor.startswith('Advanced') or platform.vendor.startswith('NVIDIA')\n for device in platform.get_devices():\n if device.type == cl.device_type.GPU:\n # If the existing type is not GPU then it will be CUSTOM or ACCELERATOR,\n # so don't override it.\n if gpu is None or (preferred_gpu and gpu.type == cl.device_type.GPU):\n gpu = device\n elif device.type == cl.device_type.CPU:\n if cpu is None or preferred_cpu:\n cpu = device\n else:\n # System has cl.device_type.ACCELERATOR or cl.device_type.CUSTOM\n # Intel Phi for example registers as an accelerator\n # Since the user installed a custom device on their system and went through the\n # pain of sorting out OpenCL drivers for it, lets assume they really do want to\n # use it as their primary compute device.\n gpu = device\n\n # order the devices by gpu then by cpu; when searching for an available device by data type they\n # will be checked in this order, which means that if the gpu supports double then the cpu will never\n # be used (though we may make it possible to explicitly request the cpu at some point).\n devices = []\n if gpu is not None:\n devices.append(gpu)\n if cpu is not None:\n devices.append(cpu)\n return [cl.Context([d]) for d in devices]\n\n\nclass GpuModel(object):\n \"\"\"\n GPU wrapper for a single model.\n\n *source* and *model_info* are the model source and interface as returned\n from :func:`generate.make_source` and :func:`generate.make_model_info`.\n\n *dtype* is the desired model precision. Any numpy dtype for single\n or double precision floats will do, such as 'f', 'float32' or 'single'\n for single and 'd', 'float64' or 'double' for double. Double precision\n is an optional extension which may not be available on all devices.\n Half precision ('float16','half') may be available on some devices.\n Fast precision ('fast') is a loose version of single precision, indicating\n that the compiler is allowed to take shortcuts.\n \"\"\"\n def __init__(self, source, model_info, dtype=generate.F32):\n self.info = model_info\n self.source = source\n self.dtype = generate.F32 if dtype == 'fast' else np.dtype(dtype)\n self.fast = (dtype == 'fast')\n self.program = None # delay program creation\n\n def __getstate__(self):\n return self.info, self.source, self.dtype, self.fast\n\n def __setstate__(self, state):\n self.info, self.source, self.dtype, self.fast = state\n self.program = None\n\n def make_kernel(self, q_vectors):\n if self.program is None:\n compiler = environment().compile_program\n self.program = compiler(self.info['name'], self.source, self.dtype,\n self.fast)\n is_2d = len(q_vectors) == 2\n kernel_name = generate.kernel_name(self.info, is_2d)\n kernel = getattr(self.program, kernel_name)\n return GpuKernel(kernel, self.info, q_vectors, self.dtype)\n\n def release(self):\n \"\"\"\n Free the resources associated with the model.\n \"\"\"\n if self.program is not None:\n environment().release_program(self.info['name'])\n self.program = None\n\n def __del__(self):\n self.release()\n\n# TODO: check that we don't need a destructor for buffers which go out of scope\nclass GpuInput(object):\n \"\"\"\n Make q data available to the gpu.\n\n *q_vectors* is a list of q vectors, which will be *[q]* for 1-D data,\n and *[qx, qy]* for 2-D data. Internally, the vectors will be reallocated\n to get the best performance on OpenCL, which may involve shifting and\n stretching the array to better match the memory architecture. Additional\n points will be evaluated with *q=1e-3*.\n\n *dtype* is the data type for the q vectors. The data type should be\n set to match that of the kernel, which is an attribute of\n :class:`GpuProgram`. Note that not all kernels support double\n precision, so even if the program was created for double precision,\n the *GpuProgram.dtype* may be single precision.\n\n Call :meth:`release` when complete. Even if not called directly, the\n buffer will be released when the data object is freed.\n \"\"\"\n def __init__(self, q_vectors, dtype=generate.F32):\n # TODO: do we ever need double precision q?\n env = environment()\n self.nq = q_vectors[0].size\n self.dtype = np.dtype(dtype)\n self.is_2d = (len(q_vectors) == 2)\n # TODO: stretch input based on get_warp()\n # not doing it now since warp depends on kernel, which is not known\n # at this point, so instead using 32, which is good on the set of\n # architectures tested so far.\n self.q_vectors = [_stretch_input(q, self.dtype, 32) for q in q_vectors]\n context = env.get_context(self.dtype)\n self.global_size = [self.q_vectors[0].size]\n #print(\"creating inputs of size\", self.global_size)\n self.q_buffers = [\n cl.Buffer(context, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=q)\n for q in self.q_vectors\n ]\n\n def release(self):\n \"\"\"\n Free the memory.\n \"\"\"\n for b in self.q_buffers:\n b.release()\n self.q_buffers = []\n\n def __del__(self):\n self.release()\n\nclass GpuKernel(object):\n \"\"\"\n Callable SAS kernel.\n\n *kernel* is the GpuKernel object to call\n\n *model_info* is the module information\n\n *q_vectors* is the q vectors at which the kernel should be evaluated\n\n *dtype* is the kernel precision\n\n The resulting call method takes the *pars*, a list of values for\n the fixed parameters to the kernel, and *pd_pars*, a list of (value,weight)\n vectors for the polydisperse parameters. *cutoff* determines the\n integration limits: any points with combined weight less than *cutoff*\n will not be calculated.\n\n Call :meth:`release` when done with the kernel instance.\n \"\"\"\n def __init__(self, kernel, model_info, q_vectors, dtype):\n q_input = GpuInput(q_vectors, dtype)\n self.kernel = kernel\n self.info = model_info\n self.res = np.empty(q_input.nq, q_input.dtype)\n dim = '2d' if q_input.is_2d else '1d'\n self.fixed_pars = model_info['partype']['fixed-' + dim]\n self.pd_pars = model_info['partype']['pd-' + dim]\n\n # Inputs and outputs for each kernel call\n # Note: res may be shorter than res_b if global_size != nq\n env = environment()\n self.queue = env.get_queue(dtype)\n self.loops_b = cl.Buffer(self.queue.context, mf.READ_WRITE,\n 2 * MAX_LOOPS * q_input.dtype.itemsize)\n self.res_b = cl.Buffer(self.queue.context, mf.READ_WRITE,\n q_input.global_size[0] * q_input.dtype.itemsize)\n self.q_input = q_input\n\n self._need_release = [self.loops_b, self.res_b, self.q_input]\n\n def __call__(self, fixed_pars, pd_pars, cutoff):\n real = (np.float32 if self.q_input.dtype == generate.F32\n else np.float64 if self.q_input.dtype == generate.F64\n else np.float16 if self.q_input.dtype == generate.F16\n else np.float32) # will never get here, so use np.float32\n\n #print \"pars\", fixed_pars, pd_pars\n res_bi = self.res_b\n nq = np.uint32(self.q_input.nq)\n if pd_pars:\n cutoff = real(cutoff)\n loops_N = [np.uint32(len(p[0])) for p in pd_pars]\n loops = np.hstack(pd_pars) \\\n if pd_pars else np.empty(0, dtype=self.q_input.dtype)\n loops = np.ascontiguousarray(loops.T, self.q_input.dtype).flatten()\n #print(\"loops\",Nloops, loops)\n\n #import sys; print(\"opencl eval\",pars)\n #print(\"opencl eval\",pars)\n if len(loops) > 2 * MAX_LOOPS:\n raise ValueError(\"too many polydispersity points\")\n\n loops_bi = self.loops_b\n cl.enqueue_copy(self.queue, loops_bi, loops)\n loops_l = cl.LocalMemory(len(loops.data))\n #ctx = environment().context\n #loops_bi = cl.Buffer(ctx, mf.READ_ONLY|mf.COPY_HOST_PTR, hostbuf=loops)\n dispersed = [loops_bi, loops_l, cutoff] + loops_N\n else:\n dispersed = []\n fixed = [real(p) for p in fixed_pars]\n args = self.q_input.q_buffers + [res_bi, nq] + dispersed + fixed\n self.kernel(self.queue, self.q_input.global_size, None, *args)\n cl.enqueue_copy(self.queue, self.res, res_bi)\n\n return self.res\n\n def release(self):\n \"\"\"\n Release resources associated with the kernel.\n \"\"\"\n for v in self._need_release:\n v.release()\n self._need_release = []\n\n def __del__(self):\n self.release()\n"} {"blob_id": "b91fc18dceeeab75ab202a8fc938a7eedeeb4874", "repo_name": "srinathalla/python", "path": "/algo/dp/hard/MinimumDistanceToTypeAWord.py", "length_bytes": 988, "score": 3.65625, "int_score": 4, "content": "import string\n\n\nclass Solution:\n def minimumDistance(self, word: str) -> int:\n def dist(c1, c2):\n if c1 is None:\n return 0\n x1, y1 = keyboard[c1]\n x2, y2 = keyboard[c2]\n return abs(x1-x2) + abs(y1-y2)\n\n def helper(i, f1, f2):\n print(\"i :\" + str(i) + \" f1: \" + str(f1) + \" f2: \" + str(f2))\n if i == len(word):\n return 0\n if (i, f1, f2) in memo:\n return memo[(i, f1, f2)]\n choice1 = dist(f1, word[i]) + helper(i + 1, word[i], f2)\n choice2 = dist(f2, word[i]) + helper(i + 1, f1, word[i])\n memo[(i, f1, f2)] = min(choice1, choice2)\n # print(memo)\n return memo[(i, f1, f2)]\n\n keyboard = {}\n for i, c in enumerate(string.ascii_uppercase):\n keyboard[c] = (i//6, i % 6)\n\n memo = {}\n return helper(0, None, None)\n\n\ns = Solution()\nprint(s.minimumDistance(\"CAKE\"))\n"} {"blob_id": "1c4e2748b376fbe867ce2a8c27b5a27563509e9c", "repo_name": "rwtodd/small_programs_2018", "path": "/bishop_puzzle/python_version/bishop_puzzle.py", "length_bytes": 4249, "score": 3.546875, "int_score": 4, "content": "sign = lambda v: (1,-1)[v < 0]\nimport copy\n\nclass Board():\n ROWS = 4\n COLS = 5\n \n @staticmethod\n def empty_places():\n result = []\n for _ in range(Board.ROWS):\n result.append([0]*Board.COLS)\n return result\n\n def __init__(self, places, prev=None, move=None):\n self.places = places\n self.prev = prev\n self.move = move\n self.hash_code = Board.compute_hash(places)\n\n def compute_attacks(self):\n ap = Board.empty_places()\n p = 0\n def set_ap(dx,dy):\n ap[dy][dx] |= p\n for y in range(Board.ROWS):\n for x in range(Board.COLS):\n p = self.places[y][x]\n if p > 0:\n Board.bishop_foreach(x,y,set_ap)\n self.attacked_places = ap\n\n def __hash__(self):\n return self.hash_code\n\n def __eq__(self, other):\n return self.hash_code == other.hash_code\n\n def display(self):\n Board.print(self.places)\n if self.move:\n x1,y1,x2,y2 = self.move\n print(f'{Board.desc_square(x1,y1)} -> {Board.desc_square(x2,y2)}', end='\\n\\n')\n\n def attacked(self, x, y, p):\n \"\"\" tells if a piece p is attacked at (x,y) \"\"\"\n return (self.attacked_places[y][x] & (3-p)) != 0\n\n def try_move(self, x1, y1, x2, y2):\n \"\"\"returns a new board if the move is legal\"\"\"\n p = self.places[y1][x1]\n if (not self.attacked(x2, y2, p)) and self.clear_path(x1,y1,x2,y2):\n places = copy.deepcopy(self.places)\n places[y1][x1], places[y2][x2] = 0, p\n return Board(places,self,(x1,y1,x2,y2))\n return None\n\n def clear_path(self, x1, y1, x2, y2):\n \"\"\" tells if the path between (x1,y1) and (x2,y2) is clear \"\"\"\n xdir, ydir = sign(x2-x1), sign(y2-y1)\n x,y = x1, y1\n while x != x2:\n x, y = x+xdir, y+ydir\n if self.places[y][x] != 0: return False\n return True\n\n @staticmethod\n def desc_square(x,y):\n return \"ABCDEFGHIJKL\"[x] + str(y+1) \n\n @staticmethod\n def print(places):\n for row in places:\n for p in row:\n if p == 0: print('-', end='')\n elif p == 1: print('W', end='')\n elif p == 2: print('B', end='')\n else: print('X', end='')\n print()\n print()\n\n @staticmethod \n def compute_hash(places):\n hash = 0\n for row in places:\n for val in row:\n hash = (hash << 2) | (val & 3)\n return hash\n\n @staticmethod\n def bishop_foreach(cx, cy, doit):\n x, y = max(cx-cy,0), max(cy-cx,0)\n len = min( Board.COLS - x, Board.ROWS - y )\n for idx in range(len): \n doit(x,y)\n x, y = x + 1, y + 1\n x, y = max(cx-(Board.ROWS-1)+cy, 0), min(cy+cx,(Board.ROWS-1))\n len = min( Board.COLS - x, y + 1 )\n for idx in range(len):\n if x != cx: doit(x,y)\n x, y = x + 1, y - 1\n\ndef next_moves(board, seen):\n x,y,p = 0,0,0\n moves = [] \n board.compute_attacks()\n def gen_move(x2,y2):\n nb = board.try_move(x,y,x2,y2)\n if (nb is not None) and (nb.hash_code not in seen):\n seen.add(nb.hash_code)\n moves.append(nb)\n for y in range(Board.ROWS):\n for x in range(Board.COLS):\n p = board.places[y][x]\n if p != 0:\n Board.bishop_foreach(x,y,gen_move)\n return moves\n \n\ndef make_initial_places():\n pl = Board.empty_places()\n for y in range(Board.ROWS):\n pl[y][0] = 1\n pl[y][-1] = 2 \n return pl\n\ndef make_winning_places():\n pl = Board.empty_places()\n for y in range(Board.ROWS):\n pl[y][0] = 2\n pl[y][-1] = 1 \n return pl\n\ndef solve():\n initial_board = Board(make_initial_places())\n winning_board = Board(make_winning_places())\n\n seen = set()\n seen.add(initial_board.hash_code)\n\n backlog = [ initial_board ]\n iteration = 0\n winner = None\n while (winner is None) and (len(backlog) > 0): \n iteration = iteration + 1\n backlog = [ nxt for m in backlog for nxt in next_moves(m,seen) ]\n print(f'{iteration}: Backlog is {len(backlog)} deep.')\n winner = next(filter(lambda m: m == winning_board, backlog), None)\n while winner:\n winner.display()\n winner = winner.prev\n print(f'{len(seen)} boards considered.')\n\nif __name__ == '__main__':\n solve()\n"} {"blob_id": "67e5a175e8e6067ffa3986f0418157a05e2059e6", "repo_name": "jorzel/codefights", "path": "/arcade/core/maximumSum.py", "length_bytes": 1259, "score": 4.09375, "int_score": 4, "content": "\"\"\"\nMedium\n\nCodewriting\n\n300\n\nYou are given an array of integers a. A range sum query is defined by a pair of non-negative integers l and r (l <= r). The output to a range sum query on the given array a is the sum of all the elements of a that have indices from l to r, inclusive.\n\nYou have the array a and a list of range sum queries q. Find an algorithm that can rearrange the array a in such a way that the total sum of all of the query outputs is maximized, and return this total sum.\n\nExample\n\nFor a = [9, 7, 2, 4, 4] and q = [[1, 3], [1, 4], [0, 2]], the output should be\nmaximumSum(a, q) = 62.\n\nYou can get this sum if the array a is rearranged to be [2, 9, 7, 4, 4]. In that case, the first range sum query [1, 3] returns the sum 9 + 7 + 4 = 20, the second query [1, 4] returns the sum 9 + 7 + 4 + 4 = 24, and the third query [0, 2] returns the sum 2 + 9 + 7 = 18. The total sum will be 20 + 24 + 18 = 62.\n\"\"\"\n\n\nfrom collections import defaultdict\n\ndef maximumSum(a, q):\n freq = defaultdict(int)\n for range_start, range_stop in q:\n for ind in range(range_start, range_stop + 1):\n freq[ind] += 1\n _sum = 0\n for x, y in zip(sorted(freq.values(), reverse=True), sorted(a, reverse=True)):\n _sum += x*y\n return _sum\n"} {"blob_id": "d6ab63644aa8875f4e893589cc0d9b05132d19fb", "repo_name": "wolflop/leetcode", "path": "/\u4e09\u6570\u4e4b\u548c\u7b49\u4e8e0.py", "length_bytes": 797, "score": 3.5625, "int_score": 4, "content": "# -*- coding:utf-8 -*-\n\nclass solution:\n def __init__(self, nums):\n self.nums = nums\n def threeSum(self):\n output=[]\n '''\n \u7b97\u6cd5\u590d\u6742\u5ea6\u6700\u9ad8\uff0c\u76ca\u7406\u89e3\u3002\n \u4f9d\u6b21\u5faa\u73af\uff0c\u4ece\u800c\u9009\u51fa\u4e0d\u540c\u7684\u503c\uff0c\u4f46\u662f\u76f8\u52a0\u7b49\u4e8e0\u7684\u3002\n '''\n for countA in range(len(self.nums)):\n # print(countA)\n for countB in range(countA, len(self.nums)):\n for countC in range(countB, len(self.nums)):\n if countA != countB and countA != countC and countB != countC:\n if self.nums[countC] + self.nums[countA] + self.nums[countB] == 0:\n output.append([self.nums[countA], self.nums[countB], self.nums[countC]])\n print(output)\n return output\n \n"} {"blob_id": "ffcb28fd554d602a775ffd81e22af51b655476c3", "repo_name": "Mystery-College-of-The-Adapts/artificial-intelligence", "path": "/projects/TSP/GA/tsp_ga.py", "length_bytes": 2584, "score": 3.796875, "int_score": 4, "content": "import random\nimport time\nimport statistics\nimport itertools\nimport functools\nimport matplotlib.pyplot as plt\nimport matplotlib\nmatplotlib.style.use('seaborn')\nimport numpy as np\n\n\n\n\n#------------------- Representing Cities--------------------------#\nclass Point(complex):\n \"\"\"Cities are represented as Points,\n which are a subclass of complex numbers.\"\"\"\n\n\n x = property(lambda p: p.real)\n y = property(lambda p: p.imag)\n\nCity = Point\n\n\ndef Cities(n, width=900, height=600, seed=1234):\n \"Make a set of n cities, each with random coordinates within a (width x height) rectangle.\"\n random.seed(seed * n)\n return frozenset((City(random.randrange(width), random.randrange(height))\n for c in range(n)))\n\n\n#-------------------Distance Between two cities ------------------#\ndef distance(A, B):\n \"\"\"Function to calculate the distance between two points\"\"\"\n return abs(A - B)\n\n\n#------------------------ Tours----------------------------------#\ndef alltours(cities):\n \"\"\"Return a list of tours, each a permutation of cities, but\n each one starting with the same city.\n\n So let's arbitrarily say that all tours must start with the first city in\n the set of cities. We'll just pull the first city out, and then tack\n it back on to all the permutations of the rest of the cities.\n This helps us keep all non-redundant tours only.\n \"\"\"\n start = first(cities)\n return [[start] + Tour(rest)\n for rest in itertools.permutations(cities - {start})]\n\ndef first(collection):\n \"\"\"Start iterating over collection, and return the first element\n \"\"\"\n return next(iter(collection))\n\nTour = list # Tours are implemented as lists of cities.\n\n\ndef tour_length(tours):\n \"The total of distances between each pair of consecutive cities in the tour.\"\n dist_air = []\n for i in range(len(tours)):\n dist_air.append(sum([distance(tours[i][j], tours[i][j-1]) for j in range(len(tours[i]))]))\n\n return dist_air\n\n\n\n#---------------------- Plotting------------------------------------#\ndef plot_tour(tour):\n \"Plot the cities as circles and the tour as lines between them.\"\n plot_lines(list(tour) + [tour[0]])\n\ndef plot_lines(points, style='bo-'):\n \"Plot lines to connect a series of points.\"\n plt.plot([p.x for p in points], [p.y for p in points], style)\n plt.axis('scaled'); plt.axis('off')\n plt.show()\n\n\n\nif __name__ == \"__main__\":\n cities = Cities(5)\n #print(cities)\n #print(alltours(cities))\n tour_length(alltours(cities))\n for i in alltours(cities):\n plot_tour(i)\n"} {"blob_id": "6a35ef60803d375ac5a0ec9243cfcf10333e30f5", "repo_name": "Albert840529/SC-Projects", "path": "/python_Projects/boggle_game_solver/anagram.py", "length_bytes": 3121, "score": 4.1875, "int_score": 4, "content": "\"\"\"\nFile: anagram.py\nName: Albert\n----------------------------------\nThis program recursively finds all the anagram(s)\nfor the word input by user and terminates when the\ninput string matches the EXIT constant defined\nat line 19\n\nIf you correctly implement this program, you should see the\nnumber of anagrams for each word listed below:\n * arm -> 3 anagrams\n * contains -> 5 anagrams\n * stop -> 6 anagrams\n * tesla -> 10 anagrams\n * spear -> 12 anagrams\n\"\"\"\n\n# Constants\nFILE = 'dictionary.txt' # This is the filename of an English dictionary\nEXIT = '-1' # Controls when to stop the loop\nlst = []\nnum_run = 0\nnum_words = 0\nd = {} # Dict which count each alphabet in a word, e.g : apple ->\n # d = {'a': 1, 'p':2, 'l':1, 'e':1}\n\n\ndef main():\n global d, num_words, num_run\n read_dictionary()\n print('Welcome to stanCode \\\"Anagram Generator\\\"(or -1 to quit)')\n while True:\n search = input('Find anagrams for: ')\n if search == EXIT:\n break\n else:\n search = search.lower() # case insensitive\n d = duplicate(search)\n test = find_anagrams(search)\n print(f'{num_words} anagrams: {test}')\n print(f'Number of runs: {num_run}')\n num_words = 0 # count how many anagrams\n num_run = 0 # count the recursion times\n\n\ndef read_dictionary():\n global lst\n with open(FILE, 'r') as f:\n for line in f:\n line = line.split()\n lst += line\n\n\ndef find_anagrams(s):\n \"\"\"\n :param s: search str\n :return: a list of anagrams\n \"\"\"\n print('Searching...')\n return find_anagrams_helper(s, '', [])\n\n\ndef find_anagrams_helper(s, ans, ans_lst):\n global lst, num_run, num_words, d\n num_run += 1\n if len(s) == len(ans):\n # Base case\n if ans in lst:\n # If ans is a word in lst\n if ans not in ans_lst:\n print(f'Found: {ans}')\n print('Searching...')\n ans_lst.append(ans)\n num_words += 1\n return ans_lst\n else:\n for word in d:\n if d[word] > 0:\n # choose\n ans += word\n d[word] -= 1\n # explore\n if has_prefix(ans):\n find_anagrams_helper(s, ans, ans_lst)\n # un-choose\n ans = ans[:len(ans)-1]\n d[word] += 1\n return ans_lst\n\n\ndef has_prefix(sub_s):\n \"\"\"\n :param sub_s: str\n :return: bool\n To check whether sub_sting has prefix in lst (Words-Dictionary)\n \"\"\"\n global lst\n for word in lst:\n if word.startswith(sub_s):\n return True\n return False\n\n\ndef duplicate(s):\n \"\"\"\n :param s: search word\n :return: Dict\n This is the fxn to count each alphabet in a word\n \"\"\"\n d_check = {}\n for i in range(len(s)):\n if s[i] in d_check:\n d_check[s[i]] += 1\n else:\n d_check[s[i]] = 1\n return d_check\n\n\n\nif __name__ == '__main__':\n main()\n"} {"blob_id": "a7cdc61c0c6975feefdfeddb8ae710d7e5988b24", "repo_name": "lubical/LeetCode", "path": "/LeetCodePython/py86.py", "length_bytes": 1750, "score": 3.71875, "int_score": 4, "content": "# \u7ed9\u5b9a\u4e00\u4e2a\u94fe\u8868\u548c\u4e00\u4e2a\u7279\u5b9a\u503c x\uff0c\u5bf9\u94fe\u8868\u8fdb\u884c\u5206\u9694\uff0c\u4f7f\u5f97\u6240\u6709\u5c0f\u4e8e x \u7684\u8282\u70b9\u90fd\u5728\u5927\u4e8e\u6216\u7b49\u4e8e x \u7684\u8282\u70b9\u4e4b\u524d\u3002\n\n# \u4f60\u5e94\u5f53\u4fdd\u7559\u4e24\u4e2a\u5206\u533a\u4e2d\u6bcf\u4e2a\u8282\u70b9\u7684\u521d\u59cb\u76f8\u5bf9\u4f4d\u7f6e\u3002\n\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution:\n def partition(self, head: ListNode, x: int) -> ListNode:\n dummy1 = ListNode(0)\n dummy2 = ListNode(0)\n p = dummy1\n q = dummy2\n while head: # \u53cc\u94fe\u62c6\u5206\u518d\u5408\u5e76\n if head.val < x:\n p.next = head\n p = p.next\n else:\n q.next = head\n q = q.next\n head = head.next\n p.next = dummy2.next\n q.next = None\n return dummy1.next\n\nclass Solution2: # \u6cd5\u4e8c\uff1a\u7c7b\u4f3c\u5192\u6ce1\u6392\u5e8f\uff0c\u5148\u94fe\u8868\u9006\u5e8f\uff0c\u5f80\u524d\u63d2\u5165\uff0c\u518d\u9006\u5e8f\u4e00\u6b21\u8fd4\u56de\u7ed3\u679c\n def partition(self, head: ListNode, x: int) -> ListNode:\n if not head:\n return head\n p = head\n tail = None\n while p: # \u5148\u9006\u5e8f\uff0c\u540c\u65f6\u63d2\u5165\n q = p.next\n if p.val >= x or not tail or tail.val < x:\n p.next = tail\n tail = p\n else:\n look_p_pre = tail\n while look_p_pre.next and look_p_pre.next.val >= x: # \u67e5\u627e\u63d2\u5165\u7684\u4f4d\u7f6e\n look_p_pre = look_p_pre.next\n p.next = look_p_pre.next\n look_p_pre.next = p\n \n p = q\n \n \n p_pre = None\n p = tail\n while p.next: # \u518d\u4e00\u6b21\u9006\u5e8f\u56de\u6765\n q = p.next\n p.next = p_pre\n p_pre = p\n p = q\n p.next = p_pre\n \n return p"} {"blob_id": "0a675149f9d758ee39cd7256a8d30216d2c46353", "repo_name": "hermanmk/AI-AStar", "path": "/Util.py", "length_bytes": 7892, "score": 3.765625, "int_score": 4, "content": "# coding=UTF-8\nfrom turtle import *\n\n__author__ = '\u00d8yvind & Herman'\n\n# Dictionary with the different arc costs based on the square's value\nterrains = {'.': 1, 'w': 100, 'm': 50, 'f': 10, 'g': 5, 'r': 1, 'A': 1, 'B': 1}\n# Dictionary with terrain colors for the graphics\ncolors = {'.': '#ffffff', '#': '#000000', 'w': '#3f51b5', 'm': '#9e9e9e',\n 'f': '#4caf50', 'g': '#8bc34a', 'r': '#795548', 'A': '#ff0000', 'B': '#00ff00'}\n\n# Initial position and speed of the pencil\nspeed(0)\npenup()\nsetpos(-500, 200)\npendown()\nscreensize(1000, 1000)\n\n\nclass Square:\n \"\"\"\n Class representing a single square on the board, also referenced as a \"node\"\n \"\"\"\n\n def __init__(self, value, x, y):\n self.value = value\n self.x = x\n self.y = y\n self.h = -1\n self.g = 0\n self.f = 0\n self.children = []\n self.parent = None\n\n def __pos__(self):\n return self.x, self.y\n\n def __str__(self):\n return self.value + '(' + str(self.x) + ', ' + str(self.y) + ')'\n\n def heuristic(self, other_sq):\n self.h = abs(self.x - other_sq.x) + abs(self.y - other_sq.y)\n\n def get_arc_cost(self):\n return terrains[self.value]\n\n def calculate_f(self):\n self.f = self.g + self.h\n\n def add_child(self, child):\n if not self.has_child(child):\n self.children.append(child)\n\n def has_child(self, child):\n return child in self.children\n\n def set_parent(self, parent):\n self.parent = parent\n\n def __eq__(self, other):\n return self.x == other.x and self.y == other.y\n\n\ndef read_from_file(file):\n board = []\n start = -1\n goal = -1\n with open('boards/' + file + '.txt', 'r') as f:\n y = 0\n for line in f:\n x = 0\n row = []\n for char in line.strip():\n row.append(Square(char, x, y))\n if char == 'A':\n start = Square(char, x, y)\n elif char == 'B':\n goal = Square(char, x, y)\n x += 1\n fillcolor(colors[char])\n # Draws a square for each node in the board with a color based on node type\n begin_fill()\n for i in range(4):\n forward(30)\n left(90)\n end_fill()\n forward(30)\n board.append(row)\n y += 1\n penup()\n # Go back to start position for x and the new y position for the next row to be drawn\n goto(-500, ycor() - 30)\n pendown()\n\n return [board, start, goal]\n\n\ndef print_list(l):\n for n in l:\n print(str(n.f) + ' - ' + str(n))\n\n\ndef draw_best_route(final_route):\n \"\"\"\n Draws the optimal route/path AFTER the algorithm has found it\n \"\"\"\n shape('turtle')\n fillcolor('purple')\n pencolor('purple')\n pensize(4)\n speed(1)\n # Finds the start position of the node in the graphical grid\n start_pos_x = (final_route[0].x) * 30\n start_pos_y = (final_route[0].y - 1) * -30\n penup()\n # Sets the start position of the drawn path in the middle of the start node\n setpos(-500 + start_pos_x + 15, 200 + start_pos_y - 15)\n pendown()\n # Draws right, left, down or up based on the position of the next node in the list\n for i in range(0, len(final_route) - 1):\n if final_route[i].x < final_route[i + 1].x:\n goto(xcor() + 30, ycor())\n elif final_route[i].x > final_route[i + 1].x:\n goto(xcor() - 30, ycor())\n elif final_route[i].y < final_route[i + 1].y:\n goto(xcor(), ycor() - 30)\n else:\n goto(xcor(), ycor() + 30)\n done()\n\n\ndef draw_closed(x, y):\n \"\"\"\n Draws the recently closed (visited) node\n \"\"\"\n square_pos_x = x * 30\n square_pos_y = (y - 1) * -30\n penup()\n # Sets the position on the position (15, 25) in the square of size (30,30) and draws a filled circle\n setpos(-500 + square_pos_x + 15, 200 + square_pos_y - 25)\n pendown()\n fillcolor('#ff9800')\n begin_fill()\n circle(10)\n end_fill()\n\n\ndef draw_open(x, y):\n \"\"\"\n Draws the newly opened (discovered) node\n \"\"\"\n square_pos_x = x * 30\n square_pos_y = (y - 1) * -30\n penup()\n pencolor('#ff9800')\n # Sets the position on the position (15, 25) in the square of size (30,30) and draws a filled circle\n setpos(-500 + square_pos_x + 15, 200 + square_pos_y - 25)\n pendown()\n circle(10)\n\n\ndef attach_and_eval(node, parent, goal):\n \"\"\"\n Part of the A* algorithm. Sets the parent of the node and calculates the g-, h- and f-function\n \"\"\"\n node.set_parent(parent)\n node.g = parent.g + node.get_arc_cost()\n node.heuristic(goal)\n node.f = node.g + node.h\n\n\ndef propagate_path_improvements(parent):\n \"\"\"\n When a cheaper path to a node is found, this method recursively updates all its children\n \"\"\"\n for child in parent.children:\n if parent.g + 1 < child.g:\n child.set_parent(parent)\n child.g = parent.g + child.get_arc_cost()\n child.f = child.g + child.h\n # Recursive call to propagate possible path improvements to all children of the children\n propagate_path_improvements(child)\n\n\ndef handle_solution(node, start_sq):\n \"\"\"\n Backtracks all the nodes of the optimal path and prints them chronologically\n \"\"\"\n final_route = []\n while True: # Find the best path by backtracking through all the parents, starting with the goal node\n final_route.insert(0, node)\n if node == start_sq:\n break\n node = node.parent\n print('Best path from A to B:')\n print_list(final_route)\n draw_best_route(final_route)\n\n\ndef a_star(board_name, draw_real_time):\n \"\"\"\n The core of the A* algorithm with the agenda loop and main conditionals\n \"\"\"\n # Initializing the board through reading the file\n init = read_from_file(board_name) # Returns a list containing the full board, start and goal square\n board = init[0]\n start_sq = init[1]\n goal_sq = init[2]\n open_nodes = []\n closed = []\n start_sq.heuristic(goal_sq)\n start_sq.f = start_sq.g + start_sq.h\n open_nodes.append(start_sq)\n neighbors = [[-1, 0], [0, -1], [1, 0], [0, 1]]\n while open_nodes:\n node = open_nodes.pop()\n closed.append(node)\n if draw_real_time:\n draw_closed(node.x, node.y)\n print(node)\n if node == goal_sq: # We have arrived at the solution\n handle_solution(node, start_sq)\n break\n for n in neighbors:\n # Make sure the neighbor is a valid square on the board\n if len(board) > (node.y + n[0]) >= 0 and len(board[node.y]) > (node.x + n[1]) >= 0:\n child = board[node.y + n[0]][node.x + n[1]]\n if child.value != '#': # Checking if the node is an obstacle, and thus not accessible\n node.add_child(child)\n if child not in closed and child not in open_nodes: # We have not yet generated this node\n attach_and_eval(child, node, goal_sq)\n open_nodes.append(child)\n if draw_real_time:\n draw_open(child.x, child.y)\n elif node.g + child.get_arc_cost() < child.g: # Found a cheaper path to this node, thus a better parent\n attach_and_eval(child, node, goal_sq) # Recalculate the costs for the node\n if child in closed: # If the node was already visited, make sure the children are also updated\n propagate_path_improvements(child)\n # Sort the open_nodes list in descending order based on the f-function, so that pop gets the least costly node\n open_nodes.sort(key=lambda s: s.f, reverse=True)\n"} {"blob_id": "c8111b281867e5cdb7a3a20e6d8069231129d308", "repo_name": "sercandenoglu/ExerciseWithPython", "path": "/Determinat_Calculate.py", "length_bytes": 2981, "score": 3.875, "int_score": 4, "content": "import copy\r\n\r\ndef GetMatrix():\r\n #get matrix from user\r\n print(\"If you want to exit, please write \\\"exit\\\"\")\r\n print(\"You can split with ',' each value\")\r\n print(\"Please enter each row\")\r\n matrix = []\r\n counter = 1\r\n while True:\r\n row = input(f\"Enter {counter}. row: \")\r\n\r\n if row == \"exit\":\r\n break\r\n else:\r\n matrix.append(row.split(\",\"))\r\n counter += 1\r\n return matrix\r\n\r\ndef SquareMatrixCheck(matrix):\r\n #it is square matrix check\r\n for i in matrix:\r\n if len(i) != len(matrix):\r\n return False\r\n else:\r\n return True\r\n\r\ndef TwotoTwo(matrix):\r\n #If matrix is two to two\r\n x1 = int(matrix[0][0]) * int(matrix[1][1])\r\n x2 = int(matrix[0][1]) * int(matrix[1][0])\r\n return x1 - x2\r\n\r\ndef Sarrus(matrix):\r\n #If matrix is three to three\r\n temporaryMatrix = matrix.copy()\r\n temporaryMatrix.append(matrix[0])\r\n temporaryMatrix.append(matrix[1])\r\n temporarySumForPositive = []\r\n temproraySumForNegative = []\r\n\r\n #left to right sum\r\n for n in range(3):\r\n counter = 0\r\n product = 1\r\n #temporary values for result\r\n x = []\r\n for j in range(n, n + 3, 1):\r\n x.append(temporaryMatrix[j][counter])\r\n counter += 1\r\n for i in x:\r\n product *= int(i)\r\n temporarySumForPositive.append(product)\r\n\r\n #right to left sum\r\n for n in range(3):\r\n counter = 2\r\n product = 1\r\n #temporary values for result\r\n x = []\r\n for j in range(n, n + 3, 1):\r\n x.append(temporaryMatrix[j][counter])\r\n counter -= 1\r\n for i in x:\r\n product *= int(i)\r\n temproraySumForNegative.append(product)\r\n\r\n return sum(temporarySumForPositive) - sum(temproraySumForNegative)\r\n\r\ndef MultilineMatrix(matrix):\r\n determinant = 0\r\n for i in range(len(matrix)):\r\n if matrix[i][0] != 0:\r\n temporaryMatrix = copy.deepcopy(matrix)\r\n temporaryDeterminant = temporaryMatrix[i][0] * ((-1) ** ((i+1) + 1))\r\n #now we are erasing rows and columns\r\n del temporaryMatrix[i]\r\n for j in range(len(temporaryMatrix)):\r\n del temporaryMatrix[j][0]\r\n\r\n if len(temporaryMatrix) == 3:\r\n temporaryDeterminant *= Sarrus(temporaryMatrix)\r\n else:\r\n temporaryDeterminant *= MultilineMatrix(temporaryMatrix)\r\n determinant += temporaryDeterminant\r\n return determinant\r\n\r\n\r\nmatrix = GetMatrix()\r\nif SquareMatrixCheck(matrix) is True and len(matrix) > 0:\r\n if len(matrix) == 1:\r\n print(f\"Determinant is {matrix[0][0]}\")\r\n elif len(matrix) == 2:\r\n print(f\"Determinant is {TwotoTwo(matrix)}\")\r\n elif len(matrix) == 3:\r\n print(f\"Determinant is {Sarrus(matrix)}\")\r\n else:\r\n print(f\"Determinant is {MultilineMatrix(matrix)}\")\r\nelse:\r\n print(\"Matrix is not square\")\r\n\r\n"} {"blob_id": "0725747b9015941bac5f87ff3c5a9372ab9fd5cc", "repo_name": "uoshvis/py-data-structures-and-algorithms", "path": "/sorting_and_selection/selection.py", "length_bytes": 1527, "score": 4.15625, "int_score": 4, "content": "# An example of prune-and-search design pattern\nimport random\n\n\ndef binary_search(data, target, low, high):\n \"\"\"Return True if target is found in indicated portion of a Python list.\n The search only considers the portion from data[low] to data[high] inclusive.\n \"\"\"\n if low > high:\n return False # interval is empty; no match\n else:\n mid = (low + high) // 2\n if target == data[mid]: # found a matcha\n return True\n elif target < data[mid]:\n # recur on the portion left of the middle\n return binary_search(data, target, low, mid - 1)\n else:\n # recur on the portion right of the middle\n return binary_search(data, target, mid + 1, high)\n\n\n# randomized quick-select algorithm\n# runs in O(n) expected time, O(n^2) time in the worst case\n\ndef quick_select(S, k):\n \"\"\"Return the kth smallest element of list S, for k from 1 to len(S).\"\"\"\n if len(S) == 1:\n return S[0]\n pivot = random.choice(S) # pick random pivot element from S\n L = [x for x in S if x < pivot]\n E = [x for x in S if x == pivot]\n G = [x for x in S if pivot < x]\n if k <= len(L):\n return quick_select(L, k) # kth smallest lies in L\n elif k <= len(L) + len(E):\n return pivot # kth smallest equal to pivot\n else:\n j = k - len(L) - len(E) # new selection parameter\n return quick_select(G, j) # kth smallest is jth in G\n"} {"blob_id": "6935349bd6516c47a274c2cf6c0938a1ae7dc1be", "repo_name": "brightsunp/learn", "path": "/leetcode/DCP_61-70.py", "length_bytes": 12616, "score": 3.75, "int_score": 4, "content": "#!/usr/bin/python\n# coding=utf-8\n'''\n__author__ = 'sunp'\n__date__ = '2019/1/24'\n'''\nimport unittest, random\nfrom collections import defaultdict, OrderedDict\n\n\nclass Solution1(object):\n '''Google\n\n Implement integer exponentiation. That is, implement the pow(x, y) function, where x and y are integers and returns x^y.\n Do this faster than the naive method of repeated multiplication.\n For example, pow(2, 10) should return 1024.\n '''\n def pow(self, x, y):\n # divide and conquer\n if y == 0:\n return 1\n if y == -(1 << 31):\n y >>= 1\n x *= x\n if y < 0:\n y = -y\n x = 1 / x\n half = self.pow(x * x, y >> 1)\n return half * x if y & 1 else half\n\n\nclass Solution2(object):\n '''Facebook\n\n There is an N by M matrix of zeroes. Given N and M, write a function to count the number of ways of starting at the top-left corner and getting to the bottom-right corner. You can only move right or down.\n\n Given a 2 by 2 matrix, you should return 2, since there are two ways to get to the bottom-right:\n - Right, then down\n - Down, then right\n Given a 5 by 5 matrix, there are 70 ways to get to the bottom-right.\n '''\n def ways(self, M, N):\n # dp\n dp = [[1 for _ in range(N)] for _ in range(M)]\n for i in range(1, M):\n for j in range(1, N):\n dp[i][j] = dp[i-1][j] + dp[i][j-1]\n return dp[-1][-1]\n\n\nclass Solution3(object):\n '''Microsoft*\n\n Given a 2D matrix of characters and a target word, write a function that returns whether the word can be found in the matrix by going left-to-right, or up-to-down.\n\n Given the following matrix:\n [['F', 'A', 'C', 'I'],\n ['O', 'B', 'Q', 'P'],\n ['A', 'N', 'O', 'B'],\n ['M', 'A', 'S', 'S']]\n and the target word 'FOAM', you should return true, since it's the leftmost column. Similarly, given the target word 'MASS', you should return true, since it's the last row.\n '''\n def search(self, matrix, word):\n # backtracking\n self.matrix = matrix\n self.word = word\n self.m = len(matrix)\n self.n = len(matrix[0])\n for i in range(self.m):\n for j in range(self.n):\n if self._dfs(i, j, 0, self.matrix[i][j]):\n return True\n return False\n\n def _dfs(self, i, j, k, tmp):\n if self.word[k] != tmp[k]:\n return False\n if k == len(self.word) - 1:\n return True\n return ((i < self.m - 1 and self._dfs(i+1, j, k+1, tmp+self.matrix[i+1][j])) or\n (j < self.n - 1 and self._dfs(i, j+1, k+1, tmp+self.matrix[i][j+1])))\n\n\nclass Solution4(object):\n '''Google\n\n A knight's tour is a sequence of moves by a knight on a chessboard such that all squares are visited once.\n Given N, write a function to return the number of knight's tours on an N by N chessboard.\n '''\n pass\n\n\nclass Solution5(object):\n '''Amazon*\n\n Given a N by M matrix of numbers, print out the matrix in a clockwise spiral.\n For example, given the following matrix:\n [[1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20]]\n You should print out the following:\n [1, 2, 3, 4, 5, 10, 15, 20, 19, 18, 17, 16, 11, 6, 7, 8, 9, 14, 13, 12]\n '''\n def spiral1(self, matrix):\n # brute\n res = []\n row_beg, col_beg, row_end, col_end = 0, 0, len(matrix)-1, len(matrix[0])-1\n while row_beg < row_end and col_beg < col_end:\n for j in range(col_beg, col_end+1):\n res.append(matrix[row_beg][j])\n row_beg += 1\n for i in range(row_beg, row_end+1):\n res.append(matrix[i][col_end])\n col_end -= 1\n for j in range(col_end, col_beg-1, -1):\n res.append(matrix[row_end][j])\n row_end -= 1\n for i in range(row_end, row_beg-1, -1):\n res.append(matrix[i][col_beg])\n col_beg += 1\n return res\n\n def spiral2(self, matrix):\n # transpose\n if not matrix:\n return []\n row = list(matrix.pop(0))\n t = list(zip(*matrix))[::-1]\n return row + self.spiral2(t)\n\n\nclass Solution6(object):\n '''Square*\n\n Assume you have access to a function toss_biased() which returns 0 or 1 with a probability that's not 50-50 (but also not 0-100 or 100-0). You do not know the bias of the coin.\n Write a function to simulate an unbiased coin toss.\n '''\n def toss_unbiased1(self):\n # P(01) = P(10) = p*(1-p)\n while True:\n x = self._toss_biased()\n y = self._toss_biased()\n if x == 0 and y == 1:\n return 0\n if x == 1 and y == 0:\n return 1\n\n def toss_unbiased2(self):\n # frequency => probability\n n_experiments = 100000\n res_biased = {1: 0, 0: 0}\n res_unbiased = {1: 0, 0: 0}\n for i in range(n_experiments):\n coin = self._toss_biased()\n res_biased[coin] += 1\n coin = not coin if i & 1 else coin\n res_unbiased[coin] += 1\n assert round(res_biased[0] / n_experiments, 2) == 0.7\n assert round(res_biased[1] / n_experiments, 2) == 0.3\n assert round(res_unbiased[0] / n_experiments, 2) == 0.5\n assert round(res_unbiased[1] / n_experiments, 2) == 0.5\n\n def _toss_biased(self):\n return 0 if random.random() < 0.7 else 1\n\n\nclass Solution7(object):\n '''Google*\n\n Implement an LFU (Least Frequently Used) cache. It should be able to be initialized with a cache size n, and contain the following methods:\n - set(key, value): sets key to value. If there are already n items in the cache and we are adding a new item, then it should also remove the least frequently used item. If there is a tie, then the least recently used key should be removed.\n - get(key): gets the value at key. If no such key exists, return null.\n Each operation should run in O(1) time.\n '''\n def __init__(self, capacity):\n self.remain = capacity\n self.min_freq = 1\n self.d_key = {}\n self.d_freq = defaultdict(OrderedDict)\n\n def get(self, key):\n if key not in self.d_key:\n return None\n self._update(key)\n return self.d_key[key][0]\n\n def set(self, key, value):\n if key in self.d_key:\n self._update(key, value)\n else:\n self.d_key[key] = (value, 1)\n self.d_freq[1][key] = (value, 1)\n if self.remain == 0:\n removed = self.d_freq[self.min_freq].popitem(last=False)\n del self.d_key[removed[0]]\n else:\n self.remain -= 1\n self.min_freq = 1\n\n def _update(self, key, new_val=None):\n value, freq = self.d_key[key]\n if new_val:\n value = new_val\n del self.d_freq[freq][key]\n if len(self.d_freq[self.min_freq]) == 0:\n self.min_freq += 1\n self.d_key[key] = (value, freq+1)\n self.d_freq[freq+1][key] = (value, freq+1)\n\n\nclass Solution8(object):\n '''Google\n\n On our special chessboard, two bishops attack each other if they share the same diagonal. This includes bishops that have another bishop located between them, i.e. bishops can attack through pieces.\n You are given N bishops, represented as (row, column) tuples on a M by M chessboard. Write a function to count the number of pairs of bishops that attack each other. The ordering of the pair doesn't matter: (1, 2) is considered the same as (2, 1).\n For example, given M = 5 and the list of bishops:\n (0, 0)\n (1, 2)\n (2, 2)\n (4, 0)\n The board would look like this:\n [b 0 0 0 0]\n [0 0 b 0 0]\n [0 0 b 0 0]\n [0 0 0 0 0]\n [b 0 0 0 0]\n You should return 2, since bishops 1 and 3 attack each other, as well as bishops 3 and 4.\n '''\n def attacks(self, M, bishops):\n # traverse diagonals\n res = 0\n for i in range(M):\n res += self._backslash(bishops, M, i, 0)\n res += self._slash(bishops, M, i, 0)\n if i != 0:\n res += self._backslash(bishops, M, 0, i)\n res += self._slash(bishops, M, M-1, i)\n return res\n\n def _backslash(self, bishops, M, i, j):\n count = 0\n while i < M and j < M:\n if (i, j) in bishops:\n count += 1\n i, j = i+1, j+1\n return (count - 1) * count / 2\n\n def _slash(self, bishops, M, i, j):\n count = 0\n while i >= 0 and j < M:\n if (i, j) in bishops:\n count += 1\n i, j = i-1, j+1\n return (count - 1) * count / 2\n\n\nclass Solution9(object):\n '''Facebook\n\n Given a list of integers, return the largest product that can be made by multiplying any three integers.\n For example, if the list is [-10, -10, 5, 2], we should return 500, since that's -10 * -10 * 5.\n You can assume the list has at least three integers.\n '''\n def max1(self, nums):\n # backtracking\n self.res = nums[0]*nums[1]*nums[2]\n self._dfs(nums, 0, [])\n return self.res\n\n def _dfs(self, nums, pos, tmp):\n if len(tmp) == 3:\n self.res = max(self.res, tmp[0]*tmp[1]*tmp[2])\n return\n for i in range(pos, len(nums)):\n self._dfs(nums, i+1, tmp+[nums[i]])\n\n def max2(self, nums):\n # dp\n res = nums[0]*nums[1]*nums[2]\n two_max = two_min = nums[0]*nums[1]\n for i in range(2, len(nums)):\n res = max(res, two_max*nums[i], two_min*nums[i])\n for j in range(i):\n two_max = max(two_max, nums[j]*nums[i])\n two_min = min(two_min, nums[j]*nums[i])\n return res\n\n\nclass Solution10(object):\n '''Microsoft\n\n A number is considered perfect if its digits sum up to exactly 10.\n Given a positive integer n, return the n-th perfect number.\n For example, given 1, you should return 19. Given 2, you should return 28.\n '''\n def perfect(self, num):\n tmp = 0\n for char in str(num):\n tmp += int(char)\n return num*10 + (10-tmp)\n\n\nclass TestSolutions(unittest.TestCase):\n def test_solution1(self):\n sol = Solution1()\n\n self.assertEqual(sol.pow(2, 10), 1024)\n self.assertEqual(sol.pow(2, -2), 0.25)\n self.assertAlmostEqual(sol.pow(2.1, 3), 9.261)\n\n def test_solution2(self):\n sol = Solution2()\n\n self.assertEqual(sol.ways(1, 1), 1)\n self.assertEqual(sol.ways(2, 2), 2)\n self.assertEqual(sol.ways(5, 5), 70)\n\n def test_solution3(self):\n sol = Solution3()\n arg1 = [['F', 'A', 'C', 'I'],\n ['O', 'B', 'Q', 'P'],\n ['A', 'N', 'O', 'B'],\n ['M', 'A', 'S', 'S']]\n arg21 = 'FOAM'\n arg22 = 'MASS'\n arg23 = 'FBOS'\n\n self.assertTrue(sol.search(arg1, arg21))\n self.assertTrue(sol.search(arg1, arg22))\n self.assertFalse(sol.search(arg1, arg23))\n\n def test_solution5(self):\n sol = Solution5()\n arg = [[1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20]]\n res = [1, 2, 3, 4, 5, 10, 15, 20, 19, 18, 17, 16, 11, 6, 7, 8, 9, 14, 13, 12]\n\n self.assertEqual(sol.spiral1(arg), res)\n self.assertEqual(arg, [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]])\n self.assertEqual(sol.spiral2(arg), res)\n self.assertEqual(arg, [[6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]])\n\n def test_solution6(self):\n sol = Solution6()\n sol.toss_unbiased2()\n\n def test_solution8(self):\n sol = Solution8()\n arg1 = 5\n arg21 = [(0, 0), (1, 2), (2, 2), (4, 0)]\n arg22 = [(0, 0), (1, 2), (2, 2)]\n arg23 = [(0, 0), (1, 2), (2, 2), (4, 0), (4, 4)]\n\n self.assertEqual(sol.attacks(arg1, arg21), 2)\n self.assertEqual(sol.attacks(arg1, arg22), 1)\n self.assertEqual(sol.attacks(arg1, arg23), 4)\n\n def test_solution9(self):\n sol = Solution9()\n arg = [-10, -10, 5, 2, 3, 4]\n\n self.assertEqual(sol.max1(arg), 500)\n self.assertEqual(sol.max2(arg), 500)\n\n def test_solution10(self):\n sol = Solution10()\n\n self.assertEqual(sol.perfect(1), 19)\n self.assertEqual(sol.perfect(24), 244)\n self.assertEqual(sol.perfect(19), 190)\n\n\nif __name__ == '__main__':\n unittest.main()\n"} {"blob_id": "c7d95416131e6137c882824c363c571af7953d2a", "repo_name": "jakehoare/leetcode", "path": "/python_1_to_1000/803_Bricks_Falling_When_Hit.py", "length_bytes": 2235, "score": 4.0, "int_score": 4, "content": "_author_ = 'jake'\n_project_ = 'leetcode'\n\n# https://leetcode.com/problems/bricks-falling-when-hit/\n# We have a grid of 1s and 0s; the 1s in a cell represent bricks. A brick will not drop if and only if it is directly\n# connected to the top of the grid, or at least one of its (4-way) adjacent bricks will not drop.\n# We will do some erasures sequentially. Each time we want to do the erasure at the location (i, j),\n# the brick (if it exists) on that location will disappear, and then some other bricks may drop because of that erasure.\n# Return an array representing the number of bricks that will drop after each erasure in sequence.\n\n# Add all hits to grid, differentiating between those that hit a brick and those that are empty. Depth-first from the\n# top row to flag all bricks that are still attached. Add back each brick in reverse order. If a brick added back has a\n# neighbour that is attached, attach it and all connected bricks that are not already attached.\n# Time - O(mn)\n# Space - O(mn)\n\nclass Solution(object):\n def hitBricks(self, grid, hits):\n \"\"\"\n :type grid: List[List[int]]\n :type hits: List[List[int]]\n :rtype: List[int]\n \"\"\"\n rows, cols = len(grid), len(grid[0])\n nbors = ((1, 0), (0, 1), (-1, 0), (0, -1))\n\n for r, c in hits: # set to zero if a brick was hit, else set to -1\n grid[r][c] -= 1\n\n def dfs(row, col):\n if row < 0 or row >= rows or col < 0 or col >= cols:\n return 0\n if grid[row][col] != 1:\n return 0\n grid[row][col] = 2\n return 1 + sum(dfs(row + dr, col + dc) for dr, dc in nbors)\n\n for c in range(cols):\n dfs(0, c)\n\n def connected(r, c):\n if r == 0:\n return True\n return any(0 <= (r + dr) < rows and 0 <= (c + dc) < cols \\\n and grid[r + dr][c + dc] == 2 for dr, dc in nbors)\n\n result = []\n for r, c in reversed(hits):\n grid[r][c] += 1\n if grid[r][c] == 1 and connected(r, c):\n result.append(dfs(r, c) - 1) # ignore erased brick\n else:\n result.append(0)\n\n return result[::-1]\n\n"} {"blob_id": "079940073578f60fcd55e9161099277500c11c67", "repo_name": "YANYANYEAH/jianzhi-offor-python", "path": "/18_\u5220\u9664\u94fe\u8868\u8282\u70b9_1.py", "length_bytes": 1365, "score": 4.0, "int_score": 4, "content": "# -*- coding:utf-8 -*-\n# // \u9762\u8bd5\u989818\uff08\u4e00\uff09\uff1a\u5728O(1)\u65f6\u95f4\u5220\u9664\u94fe\u8868\u7ed3\u70b9\n# // \u9898\u76ee\uff1a\u7ed9\u5b9a\u5355\u5411\u94fe\u8868\u7684\u5934\u6307\u9488\u548c\u4e00\u4e2a\u7ed3\u70b9\u6307\u9488\uff0c\u5b9a\u4e49\u4e00\u4e2a\u51fd\u6570\u5728O(1)\u65f6\u95f4\u5220\u9664\u8be5\n# // \u7ed3\u70b9\u3002\n\n\nclass list_node:\n def __init__(self, x):\n self.value = x\n self.next = None\n\n def __del__(self):\n return\n\n\ndef connect_node(a,b):\n a.next = b\n\n\ndef deletd_node(x):\n if x.next == None:\n temp = head\n while temp.next != x:\n temp = temp.next\n temp.next = None # \u6ce8\u610f\uff1a\u5f53\u88ab\u5220\u9664\u7684\u4e3a\u6700\u6709\u4e00\u4e2a\u8282\u70b9\u7684\u65f6\u5019\uff0c\u524d\u4e00\u4e2a\u8282\u70b9next\u548cvalue\u90fd\u8981\u66f4\u6539\uff0c\u4e0d\u8981\u5fd8\u4e86\u6539value\n if head.next == None:\n return -1\n else:\n del x\n else:\n x.value = x.next.value\n temp = x.next\n x.next = x.next.next\n del temp\n\n\ndef print_list(head):\n temp = head # \u6ce8\u610f \u6253\u5370\u4ecetemp.next\u5f00\u59cb\uff0c\u6b64\u65f6\u5c31\u4e0d\u7528\u8fdb\u884c\u6700\u540e\u4e00\u6b65\u7684\u5224\u65ad\n while temp.next:\n print temp.next.value\n temp = temp.next\n\n\nif __name__ == '__main__':\n head = list_node(0)\n a = list_node(1)\n b = list_node(2)\n c = list_node(3)\n d = list_node(4)\n connect_node(head,a)\n connect_node(a,b)\n connect_node(b,c)\n connect_node(c,d)\n if deletd_node(a) != -1:\n print_list(head)\n else:\n print None"} {"blob_id": "3905ab034867db2d909a682ca7465fe8467b23dd", "repo_name": "dedekinds/pyleetcode", "path": "/A_jzoffer/\u5b57\u7b26\u4e32\u7684\u6392\u5217.py", "length_bytes": 708, "score": 3.78125, "int_score": 4, "content": "\u6709\u5fc5\u8981\u6700\u540esorted\u5417\uff1f\n\n# -*- coding:utf-8 -*-\nclass Solution:\n def finpermutation(self,s,res,ptr):\n if ptr == len(s):\n candi = ''.join(s)\n if candi not in res:\n res.append(''.join(s))\n\n for i in range(ptr,len(s)):\n temp = s[ptr]\n s[ptr] = s[i]\n s[i] = temp\n \n self.finpermutation(s,res,ptr+1)\n \n temp = s[ptr]\n s[ptr] = s[i]\n s[i] = temp\n \n \n def Permutation(self, ss):\n # write code here\n s = list(ss)\n res = []\n if len(ss) == 0:return res\n self.finpermutation(s,res,0)\n return sorted(res)"} {"blob_id": "55931f090ea97f6b398fe7991296ad62051718ad", "repo_name": "identor/code", "path": "/python/deck.py", "length_bytes": 18814, "score": 4.03125, "int_score": 4, "content": "# This class creates a single card of a deck. For simplicity, assume that Ace has a value of 1\r\n# and has the lowest value. King has a value of 13 and has the highest value.\r\n# Order of suits are clubs, spades, hearts and diamonds in ascending order\r\nclass Card:\r\n # spade (\"\\u2660\")\r\n # diamond (\"\\u2666\")\r\n # heart (\"\\u2764\")\r\n # clover (\"\\u2618\")\r\n suits = [\"\\u2618\", \"\\u2660\", \"\\u2764\", \"\\u2666\"]\r\n ranks = [\"null\", \"Ace\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\",\r\n \"8\", \"9\", \"10\", \"Jack\", \"Queen\", \"King\"] \r\n\r\n def __init__(self, suit=0, rank=0):\r\n self.suit = suit\r\n self.rank = rank\r\n\r\n def __str__(self):\r\n return (self.ranks[self.rank] + \" \" + self.suits[self.suit]) \r\n \r\n def __repr__(self):\r\n return self.__str__()\r\n\r\n def __cmp__(self, other):\r\n # check ranks\r\n if self.rank > other.rank: return 1\r\n if self.rank < other.rank: return -1\r\n # ranks are the same... check the suits\r\n if self.suit > other.suit: return 1\r\n if self.suit < other.suit: return -1\r\n # ranks are the same... it's a tie\r\n return 0\r\n def __lt__(self, other):\r\n return self.__cmp__(other) < 0\r\n\r\n def __le__(self, other):\r\n return self.__cmp__(other) < 0\r\n\r\n def __gt__(self, other):\r\n return self.__cmp__(other) > 0\r\n\r\n def __ge__(self, other):\r\n return self.__cmp__(other) >= 0\r\n\r\nclass Deck:\r\n def __init__(self):\r\n self.cards = []\r\n for suit in range(4):\r\n for rank in range(1, 14):\r\n self.cards.append(Card(suit, rank))\r\n\r\n def __str__(self):\r\n s = \"\"\r\n for i in range(len(self.cards)):\r\n s = s + str(self.cards[i]) + \"\\n\"\r\n return s \r\n\r\n # shuffles the deck\r\n def shuffle(self):\r\n import random\r\n num_cards = len(self.cards)\r\n for i in range(num_cards):\r\n j = random.randrange(i, num_cards)\r\n self.cards[i], self.cards[j] = self.cards[j], self.cards[i]\r\n\r\n # removes and return the top card of the deck\r\n def popCard(self):\r\n return self.cards.pop(0)\r\n#-------------------------------------------------------------------------------\r\nclass Hand:\r\n types = [\"high_card\", \"pair\", \"two_pair\", \"trio\", \"straight\", \"flush\",\r\n \"full\", \"quad\", \"straight_flush\"]\r\n \r\n def __init__(self, card_list = []):\r\n self.cards = sorted(card_list)\r\n self.cards.reverse()\r\n self.type = -1\r\n\r\n # removed the cards present in the current hand returns a sorted copy\r\n def removed(self, cards):\r\n result = sorted(self.cards)\r\n for i in range(len(cards)):\r\n result.remove(cards[i])\r\n return result\r\n \r\n def __str__(self):\r\n s = \"\"\r\n s = s + \"Hand Type: \" + self.getHandType\r\n for i in range(len(self.cards)):\r\n s = s + str(self.cards[i]) + \"\\n\"\r\n return s\r\n \r\n def getHandType(self):\r\n cards = []\r\n if len(self.getStraightFlush()) == 5:\r\n cards = self.getStraightFlush()\r\n self.type = 8\r\n elif len(self.getQuad()) == 4:\r\n cards = self.getQuad()\r\n self.type = 7\r\n elif len(self.getFull()) == 5:\r\n cards = self.getFull()\r\n self.type = 6\r\n elif len(self.getFlush()) == 5:\r\n cards = self.getFlush()\r\n self.type = 5\r\n elif len(self.getStraight()) == 5:\r\n cards = self.getStraight()\r\n self.type = 4\r\n elif len(self.getTrio()) == 3:\r\n cards = self.getTrio()\r\n self.type = 3\r\n elif len(self.getTwoPair()) == 4:\r\n cards = self.getTwoPair()\r\n self.type = 2\r\n elif len(self.getPair()) == 2:\r\n cards = self.getPair()\r\n self.type = 1\r\n else:\r\n self.type = 0\r\n \r\n r = self.removed(cards)\r\n r.sort()\r\n r.reverse()\r\n cards.extend(r)\r\n self.cards = cards\r\n return self.types[self.type] + \": \" + cards[0].__str__()\r\n\r\n def getPair(self):\r\n cards = sorted(self.cards)\r\n result = [Card(), Card()]\r\n card_len = len(cards)\r\n i = len(Card.ranks);\r\n while i > 0:\r\n same_rank = 0\r\n for j in range(card_len):\r\n if i == cards[j].rank:\r\n result[same_rank] = cards[j]\r\n same_rank = same_rank+1\r\n # highest pair is achieved\r\n if same_rank == 2:\r\n return result\r\n i = i - 1\r\n # failure in detecting a pair\r\n result = []\r\n return result\r\n\r\n def getTrio(self): \r\n cards = sorted(self.cards)\r\n result = [Card(), Card(), Card()]\r\n card_len = len(cards)\r\n i = len(Card.ranks);\r\n while i > 0:\r\n same_rank = 0\r\n for j in range(card_len):\r\n if i == cards[j].rank:\r\n result[same_rank] = cards[j]\r\n same_rank = same_rank+1\r\n # highest trio is achieved\r\n if same_rank == 3:\r\n return result\r\n i = i - 1\r\n # failure in detecting a trio\r\n result = []\r\n return result\r\n\r\n def getQuad(self):\r\n cards = sorted(self.cards)\r\n result = [Card(), Card(), Card(), Card()]\r\n card_len = len(cards)\r\n i = len(Card.ranks)\r\n while i > 0:\r\n same_rank = 0\r\n for j in range(card_len):\r\n if i == cards[j].rank:\r\n result[same_rank] = cards[j]\r\n same_rank = same_rank+1\r\n # highest quad is achieved\r\n if same_rank == 4:\r\n return result\r\n i = i - 1\r\n # failure in detecting a quad\r\n result = []\r\n return result\r\n\r\n def getFull(self):\r\n result = [Card(), Card(), Card(), Card(), Card()]\r\n # t represents the highest trio\r\n t = self.getTrio()\r\n if len(t) != 3:\r\n # failure in detecting a fullhouse: there are no trios in the current cards\r\n return []\r\n # t_rem is a list where the highest trio is removed from the current cards\r\n t_rem = self.removed(t)\r\n result[:len(t)] = t\r\n cards = sorted(t_rem) \r\n card_len = len(cards)\r\n i = len(Card.ranks)\r\n while i > 0:\r\n same_rank = 0\r\n for j in range(card_len):\r\n if i == cards[j].rank:\r\n result[same_rank+3] = cards[j]\r\n same_rank = same_rank+1\r\n # fullhouse is achieved\r\n if same_rank == 2:\r\n return result\r\n i = i - 1\r\n # failure in detecting a fullhouse\r\n result = []\r\n return result\r\n\r\n def getTwoPair(self):\r\n result = [Card(), Card(), Card(), Card()]\r\n # p represents the highest trio\r\n p = self.getPair()\r\n if len(p) != 2:\r\n # failure in detecting a Two Pair: there are no pairs in the current cards\r\n return []\r\n # p_rem is a list where the highest pair is removed from the current cards\r\n p_rem = self.removed(p)\r\n result[:len(p)] = p\r\n cards = sorted(p_rem) \r\n card_len = len(cards)\r\n i = len(Card.ranks)\r\n while i > 0:\r\n same_rank = 0\r\n for j in range(card_len):\r\n if i == cards[j].rank:\r\n result[same_rank+2] = cards[j]\r\n same_rank = same_rank+1\r\n # two pair is achieved\r\n if same_rank == 2:\r\n return result\r\n i = i - 1\r\n # failure in detecting a two pair\r\n result = []\r\n return result\r\n\r\n def getStraight(self):\r\n cards = sorted(self.cards)\r\n card_len = len(cards)\r\n result = [Card(), Card(), Card(), Card(), Card()]\r\n cards.reverse()\r\n ctr = 1\r\n \r\n for i in range(len(cards)-1):\r\n # check if a streak is encountered\r\n if cards[i].rank - cards[i+1].rank == 1:\r\n result[ctr-1] = cards[i]\r\n result[ctr] = cards[i+1]\r\n ctr = ctr + 1\r\n if ctr == 5:\r\n # streak is 5 straight is achieved\r\n return result\r\n # same rank: do nothing\r\n elif cards[i].rank - cards[i+1].rank == 0:\r\n pass\r\n # reset counter: streak is not encountered\r\n else:\r\n ctr = 1\r\n # failure in detecting a straight: no level 5 streak encountered \r\n return []\r\n\r\n def getFlush(self):\r\n cards = sorted(self.getFlushable())\r\n if len(cards) < 5:\r\n return []\r\n cards.reverse()\r\n card_len = len(cards)\r\n result = [Card(), Card(), Card(), Card(), Card()]\r\n i = len(Card.suits)-1;\r\n while i >= 0:\r\n same_suit = 0\r\n for j in range(card_len):\r\n if i == cards[j].suit:\r\n result[same_suit] = cards[j]\r\n same_suit = same_suit + 1\r\n if same_suit == 5:\r\n # flush is achieved\r\n return result\r\n i = i-1\r\n # failure in detecting a flush\r\n return []\r\n\r\n def getStraightFlush(self):\r\n # f represents a flushable in the current hand\r\n f = self.getFlushable()\r\n if len(f) <= 5:\r\n # no straight flush: current card is not a flushable\r\n return []\r\n cards = sorted(f)\r\n card_len = len(cards)\r\n result = [Card(), Card(), Card(), Card(), Card()]\r\n cards.reverse()\r\n ctr = 1\r\n for i in range(len(cards)-1):\r\n # check if a streak is encountered\r\n if cards[i].rank - cards[i+1].rank == 1:\r\n result[ctr-1] = cards[i]\r\n result[ctr] = cards[i+1]\r\n ctr = ctr + 1\r\n if ctr == 5:\r\n # streak is 5 straight is achieved\r\n return result\r\n # same rank: do nothing\r\n elif cards[i].rank - cards[i+1].rank == 0:\r\n pass\r\n # reset counter: streak is not encountered\r\n else:\r\n ctr = 1\r\n # failure in detecting a straight: no level 5 streak encountered \r\n return []\r\n \r\n \r\n # will return the cards that might represent a flush\r\n def getFlushable(self):\r\n cards = sorted(self.cards)\r\n cards.reverse()\r\n card_len = len(cards)\r\n # suits contains a list for the number of cards with the same suit\r\n suits = [0, 0, 0, 0]\r\n for i in range(len(Card.suits)):\r\n for j in range(card_len):\r\n if i == cards[j].suit:\r\n suits[i] = suits[i]+1\r\n # flushable index\r\n index = -1\r\n for i in range(len(suits)):\r\n # note: only 7 cards in a poker hand :. suit with len >= 5 is flushable\r\n if suits[i] >= 5:\r\n index = i\r\n if index == -1:\r\n return []\r\n else:\r\n result = []\r\n for i in range(card_len):\r\n if index == cards[i].suit:\r\n result.append(cards[i])\r\n return result\r\n # failure in detecting a flushable\r\n return []\r\n#-------------------------------------------------------------------------------\r\nclass Player:\r\n def __init__(self, money=0, hand = Hand()):\r\n self.hand = hand\r\n self.money = money\r\n\r\n def __str__(self):\r\n return \"money: \" + self.money.__str__() + \"| \" + self.hand.getHandType()\r\n\r\n def getHand(self):\r\n return self.hand\r\n \r\n def addCard(self, card):\r\n self.hand.cards.append(card)\r\n\r\n def addCards(self, cards):\r\n self.hand.cards.extend(cards)\r\n\r\n def getCards(self):\r\n return self.hand.cards\r\n\r\n def placeBet(self, bet):\r\n self.money = self.money - bet\r\n return bet\r\n#-------------------------------------------------------------------------------\r\nimport sys\r\nclass Game:\r\n \r\n def __init__(self):\r\n self.round = 0\r\n self.player = Player(1000, Hand())\r\n self.comp = Player(999999999999, Hand())\r\n self.deck = None\r\n self.deck = Deck()\r\n self.pot = 0\r\n self.deck.shuffle()\r\n input(\"Deck is ready and shuffled! press enter to continue...\")\r\n\r\n def showOption(self):\r\n print(\"Enter a number: \")\r\n print(\"1 > raise\")\r\n print(\"2 > fold\")\r\n print(\"3 > pass\")\r\n self.lnbr()\r\n try:\r\n i = int(input(\"input: \"))\r\n if i == 1:\r\n return 1\r\n elif i == 2:\r\n return 2\r\n elif i == 3:\r\n return\r\n else:\r\n return self.showOption()\r\n except ValueError:\r\n return self.showOption()\r\n\r\n def mainMenu(self):\r\n print(\"You are given an initial money of 1000\")\r\n print(\"Enter a number: \")\r\n print(\"1 > start game\")\r\n print(\"2 > quit\")\r\n self.lnbr()\r\n try:\r\n i = int(input(\"input: \"))\r\n if i == 1:\r\n self.player.money = 1000\r\n self.round = 1\r\n self.startRound(self.round)\r\n elif i == 2:\r\n exit(0)\r\n else:\r\n return self.mainMenu()\r\n except ValueError:\r\n return self.mainMenu()\r\n\r\n def endRoundMenu(self):\r\n print(\"Enter a number: \")\r\n print(\"1 > next round\")\r\n print(\"2 > main menu\")\r\n self.lnbr()\r\n try:\r\n i = int(input(\"input: \"))\r\n if i == 1:\r\n self.lnbr()\r\n return\r\n elif i == 2:\r\n input(\"back to main menu...\")\r\n self.mainMenu()\r\n else:\r\n return self.endRoundMenu()\r\n except ValueError:\r\n return self.endRoundMenu()\r\n\r\n def raiseBet(self):\r\n try:\r\n i = int(input(\"amount to raise: \"))\r\n return i\r\n except ValueError:\r\n return self.showOption()\r\n\r\n # draw cards\r\n def drawCard(self):\r\n return self.deck.popCard()\r\n\r\n def placeBet(self):\r\n if self.player.money == 0:\r\n print(\"Called!\")\r\n return\r\n c = self.showOption()\r\n if c == 1:\r\n bet = self.raiseBet()\r\n if bet > self.player.money:\r\n print(\"Invalid amount!!!\")\r\n self.placeBet()\r\n else:\r\n bet = self.player.money - (self.player.money-bet)\r\n self.player.money = self.player.money - bet\r\n self.pot = bet + bet\r\n elif c == 2:\r\n print(\"you folded get ready for the next round...\")\r\n input(\"press enter...\")\r\n self.lnbr()\r\n self.round = self.round + 1\r\n self.startRound(self.round)\r\n else:\r\n pass\r\n \r\n def match(self):\r\n self.player.hand.getHandType()\r\n self.comp.hand.getHandType()\r\n if self.player.hand.type > self.comp.hand.type:\r\n self.player.money = self.player.money + self.pot\r\n print(\"YOU WIN!!!!!!!\")\r\n elif self.player.hand.type == self.comp.hand.type:\r\n playerCard = self.player.hand.cards\r\n compCard = self.comp.hand.cards\r\n if playerCard[0].rank > compCard[0].rank:\r\n self.player.money = self.player.money + self.pot\r\n print(\"YOU WIN!!!!!!!\")\r\n elif self.player.hand.cards[0].rank == self.comp.hand.cards[0].rank:\r\n self.comp.money = self.comp.money + self.pot/2\r\n self.player.money = self.player.money + self.pot/2\r\n print(\"IT IS A TIE!\")\r\n else:\r\n self.comp.money = self.comp.money + self.pot\r\n print(\"YOU LOSE...\")\r\n else:\r\n print(\"YOU LOSE...\")\r\n self.showHand()\r\n self.showHand(\"comp\") \r\n input(\"press enter to continue...\") \r\n \r\n # start round\r\n def startRound(self, num):\r\n self.deal()\r\n self.placeBet()\r\n self.flop() \r\n self.placeBet()\r\n self.theTurn()\r\n self.placeBet()\r\n self.river()\r\n self.placeBet()\r\n self.match()\r\n self.round = self.round + 1\r\n if self.player.money < 1:\r\n print(\"You are bankrupt!\")\r\n input(\"press enter to return to main menu...\")\r\n self.mainMenu() \r\n self.endRoundMenu()\r\n self.startRound(self.round)\r\n\r\n def flop(self):\r\n input(\"The flop! press enter to continue...\")\r\n flop = [self.drawCard(), self.drawCard(), self.drawCard()]\r\n flop.sort()\r\n print(flop)\r\n self.player.addCards(flop)\r\n self.comp.addCards(flop)\r\n self.showHand()\r\n\r\n def theTurn(self): \r\n input(\"The turn! press enter to continue...\")\r\n turn = [self.drawCard()]\r\n turn.sort()\r\n print(turn)\r\n self.player.addCards(turn)\r\n self.comp.addCards(turn)\r\n self.showHand()\r\n\r\n def river(self): \r\n input(\"The river! press enter to continue...\")\r\n river = [self.drawCard()]\r\n river.sort()\r\n print(river)\r\n self.player.addCards(river)\r\n self.comp.addCards(river)\r\n self.showHand()\r\n \r\n def deal(self):\r\n self.player.hand = Hand()\r\n self.comp.hand = Hand()\r\n self.player.addCards([self.drawCard(), self.drawCard()])\r\n self.comp.addCards([self.drawCard(), self.drawCard()])\r\n self.showHand()\r\n \r\n # shows the hand of the specified player default \"player\")\r\n def showHand(self, player=\"player\"):\r\n if player == \"player\":\r\n print(\"YOUR HAND: \", self.player.getCards())\r\n print(\"CURRENT STAT--> \", self.player)\r\n elif player == \"comp\":\r\n print(\"COMP HAND: \", self.comp.hand.getHandType())\r\n self.lnbr()\r\n\r\n def lnbr(self):\r\n print(\"-----------------------------------------------------------------------------\")\r\n \r\n def start(self):\r\n self.mainMenu()\r\n#-------------------------------------------------------------------------------\r\n# start the game\r\nGame().start()\r\n#-------------------------------------------------------------------------------\r\n"} {"blob_id": "bbe3bfbeac20116cecb0b9736753ec1a8a1b216a", "repo_name": "jakehoare/leetcode", "path": "/python_1_to_1000/885_Spiral_Matrix_III.py", "length_bytes": 2281, "score": 4.3125, "int_score": 4, "content": "_author_ = 'jake'\n_project_ = 'leetcode'\n\n# https://leetcode.com/problems/spiral-matrix-iii/\n# On a 2 dimensional grid with R rows and C columns, we start at (r0, c0) facing east.\n# Here, the north-west corner of the grid is at the first row and column, and the south-east corner of the\n# grid is at the last row and column.\n# Now, we walk in a clockwise spiral shape to visit every position in this grid.\n# Whenever we would move outside the boundary of the grid, we continue our walk outside the grid\n# (but may return to the grid boundary later.)\n# Eventually, we reach all R * C spaces of the grid.\n# Return a list of coordinates representing the positions of the grid in the order they were visited.\n\n# Move in a spiral until all cells of the grid have been visited. Step along each side, then turn to next direction.\n# Each cell visited within the grid is appended to the result. Spiral has two sides of the same length, then two sides\n# of length + 1, etc.\n# Time - O(max(m, n)**2)\n# Space - O(mn)\n\nclass Solution(object):\n def spiralMatrixIII(self, R, C, r0, c0):\n \"\"\"\n :type R: int\n :type C: int\n :type r0: int\n :type c0: int\n :rtype: List[List[int]]\n \"\"\"\n moves = [[0, 1], [1, 0], [0, -1], [-1, 0]] # change in r and c foa move in each direction\n r, c = r0, c0\n direction = 0\n result = [[r0, c0]]\n side = 1 # current length of side of spiral\n\n while len(result) < R * C:\n\n dr, dc = moves[direction]\n\n for _ in range(side): # step along the side\n r += dr\n c += dc\n if 0 <= r < R and 0 <= c < C: # append to result if within bounds of grid\n result.append([r, c])\n\n direction = (direction + 1) % 4 # next direction\n dr, dc = moves[direction]\n\n for _ in range(side):\n r += dr\n c += dc\n if 0 <= r < R and 0 <= c < C:\n result.append([r, c])\n\n direction = (direction + 1) % 4\n side += 1 # after 2 sides of spiral, increase side length\n\n return result"} {"blob_id": "f9f7e8968a4b02fb6962d127e4be24411f9e4e85", "repo_name": "Muffinous/DAA", "path": "/BACKTRAKING/initbattle.py", "length_bytes": 1044, "score": 3.515625, "int_score": 4, "content": "def isFeasible(b, r, c):\n feasible = True\n i = 1\n while feasible and i <= r:\n columnFUp = b[r - i] != c\n diagonalFRUp = b[r - i] != c - i\n diagonalFLUp = b[r - i] != c + i\n feasible = columnFUp and diagonalFRUp and diagonalFLUp\n i += 1\n return feasible\n\n\ndef initbattle(b, row):\n n = len(b)\n if row >= n:\n is_sol = True\n else:\n is_sol = False\n col = 0\n while col < len(b) and not is_sol:\n if isFeasible(b, row, col):\n b[row] = col\n [b, is_sol] = initbattle(b, row + 1)\n if not is_sol:\n b[row] = 0\n col += 1\n return b, is_sol\n\n\nn, players = map(int, input().strip().split())\nif players == 0:\n print('ADELANTE')\n\nelse:\n board = [0] * n\n rows = list(map(int, input().strip().split()))\n\n for i in range(players):\n board[i] = rows[i]\n [b, sol] = initbattle(board, players)\n if sol:\n print('ADELANTE')\n else:\n print('VUELVE A EMPEZAR')"} {"blob_id": "05417a7dfae06dc4220c46805ba435c84e8ef627", "repo_name": "icelighting/leetcode", "path": "/\u6570\u7ec4\u4e0e\u5b57\u7b26\u4e32/\u87ba\u65cb\u77e9\u96352.py", "length_bytes": 1325, "score": 3.734375, "int_score": 4, "content": "'''\n\u7ed9\u5b9a\u4e00\u4e2a\u6b63\u6574\u6570 n\uff0c\u751f\u6210\u4e00\u4e2a\u5305\u542b 1 \u5230 n2 \u6240\u6709\u5143\u7d20\uff0c\n\u4e14\u5143\u7d20\u6309\u987a\u65f6\u9488\u987a\u5e8f\u87ba\u65cb\u6392\u5217\u7684\u6b63\u65b9\u5f62\u77e9\u9635\u3002\n'''\n\nclass Solution:\n def generateMatrix(self, n):\n \"\"\"\n :type n: int\n :rtype: List[List[int]]\n \"\"\"\n nlist = list(range(1,n**2+1))\n matrix = []\n for i in range(n):\n matrix.append(list(range(n)))\n print(matrix)\n counter = [0,0]\n s= 0\n m = n // 2\n for i in range(m):\n while counter[1] < n -1:\n matrix[counter[0]+i*1][counter[1]+i*1] = nlist[s]\n s += 1\n counter[1] += 1\n\n while counter[0] < n -1:\n matrix[counter[0]+i*1][counter[1]+i*1] = nlist[s]\n s += 1\n counter[0] += 1\n\n while counter[1] > 0:\n matrix[counter[0]+i*1][counter[1]+i*1] = nlist[s]\n s += 1\n counter[1] -= 1\n\n while counter[0] > 0:\n matrix[counter[0]+i*1][counter[1]+i*1] = nlist[s]\n s += 1\n counter[0] -= 1\n\n n -= 2\n if n % 2 != 0:\n matrix[m][m] = nlist[-1]\n return matrix\nif __name__ == '__main__':\n n = 3\n solute = Solution()\n print(solute.generateMatrix(7))"} {"blob_id": "461a54fb3c246ba90879c6ca2ce8e18f48996a53", "repo_name": "AndrejLehmann/my_pfn_2019", "path": "/Uebungen/Blatt08.Harkov.Lehmann.Music/Aufgabe1/Splitnumber/splitnumber.py", "length_bytes": 3126, "score": 3.75, "int_score": 4, "content": "#!/usr/bin/env python3\n# Bearbeitungszeit: 4.0h\nimport math\nimport sys\n\ntestArray = [2,3,3,3,3]\n\ndef quality_function(intArray):\n mean = sum(intArray)/len(intArray)\n quality = 0.\n for n in intArray:\n quality += (n - mean)**2\n quality = math.sqrt(quality)\n return quality\n\n#print(quality_function(testArray))\n\n\n\n\ndef split_number_rec(terms_of_sum, best_split, remain, terms_idx, l):\n '''\n terms_of_sum : list of positiv int numbers\n best_split : list with 2 values\n [0] = additive split with min quality value (default: None)\n [1] = quality value of [0] (default: None)\n remain : number for which the additive split from terms_of_sum[terms_idx:]\n suppose to be calculated\n l : is a list containing sums from terms_of_sum\n\n The result is saved in best_split\n '''\n\n print(remain,terms_of_sum[terms_idx])\n if remain == 0:\n l.append(terms_of_sum[terms_idx])\n print(l)\n if best_split[1] is None or quality_function(l) < best_split[1]:\n best_split[0] = l\n best_split[1] = quality_function(l)\n\n elif remain > terms_of_sum[terms_idx]:\n remain -= terms_of_sum[terms_idx]\n l.append(terms_of_sum[terms_idx])\n split_number_rec(terms_of_sum, best_split, remain, terms_idx, l)\n\n else:\n print(l)\n\n\ndef split_number(number, terms_of_sum):\n best_split = [None, None]\n l = []\n #split_number_rec(terms_of_sum, best_split, remain, terms_idx, l)\n split_number_rec(terms_of_sum, best_split, number, 0, []) # [2,2,2,2,3]\n split_number_rec(terms_of_sum, best_split, 5, 1, [2,2,2]) # [2,2,2,5]\n split_number_rec(terms_of_sum, best_split, 7, 1, [2,2]) # []\n split_number_rec(terms_of_sum, best_split, 9, 1, [2]) # [2,3,3,3]\n\n return best_split\n\n\nn = 11\nl = []\nS = [2, 3, 5]\nfor i in range(len(S)):\n split_number_rec(S, [None,None], n, i, l) # [2,2,2,2,3]\n l_ = l[:]\nsys.exit()\n\nn = 32\nl = []\nS = [7, 11, 13]\nsplit_number_rec(S, [None, None], n, 0, l) # [7,7,7,11]]\n\nn = 38\nl = []\nS = [7, 11, 13]\nsplit_number_rec(S, [None, None], n, 0, l) # [7,7,11,13]\n\nn = 45\nl = []\nS = [8, 9]\nsplit_numbers_test(S, [None, None], n, 0, l) # [9,9,9,9,9]]\nn = 47\nl = []\nS = [11, 12, 13, 14]\nsplit_numbers_test(S, [None, None], n, 0, l) # [11,12,12,12]]\nn = 47\nl = []\nS = [13, 14]\nsplit_numbers_test(S, [None, None], n, 0, l) # None\n\n\n\n\n\n\n'''\nS = [s1, s2, ..., si, ..., sk]\nsort(S)\nn = n1*s1 + n2*s2 + n3*s3 + ... + nk*sk\n\n\nSCAN PARAMETER SPACE ALGORITHM:\n 0 <= n1, n2, ..., ni, ..., nk <= N # parameter space for ni\n N = max( ni | ni*min(S) = ni*s1 <= n )\n go through all ni in parameter space to find n\n\n\nINT DIVIDE ALGORITHM:\n nk = n//sk\n rk = n%sk\n n(k-1) = rk//s(k-1)\n r(k-1) = rk%s(k-1)\n ...\n n2 = r3//s2\n r2 = r3%s2\n n1 = r2//s1\n r1 = r2%s1 = 0\n\n save quality\n\n n(k-1) = rk//s(k-1)\n r(k-1) = rk%s(k-1)\n ...\n n1 = r2//s1\n r1 = r2%s1 = 0\n\n compare quality\n replace with parameters with better quality\n\n n(k-2) = rk//s(k-2)\n r(k-2) = rk%s(k-2)\n ...\n\n'''\n"} {"blob_id": "bf1ddb812830daa6886923b1c2020741d9cea660", "repo_name": "BarY7/k_intervals_ex2", "path": "/assignment2.py", "length_bytes": 16261, "score": 3.71875, "int_score": 4, "content": "#################################\n# Your name:\n#################################\n\nfrom os.path import sameopenfile\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom numpy.lib.nanfunctions import nanmedian\nimport intervals\n\n\nclass Assignment2(object):\n \"\"\"Assignment 2 skeleton.\n\n Please use these function signatures for this assignment and submit this file, together with the intervals.py.\n \"\"\"\n\n def sample_from_D(self, m):\n \"\"\"Sample m data samples from D.\n Input: m - an integer, the size of the data sample.\n\n Returns: np.ndarray of shape (m,2) :\n A two dimensional array of size m that contains the pairs where drawn from the distribution P.\n \"\"\"\n xs = np.random.random_sample(m)\n ys = [0 for i in range(0, m)]\n for i in range(0, m):\n if((xs[i] >= 0.2 and xs[i] <= 0.4) or (xs[i] >= 0.6 and xs[i] <= 0.8)):\n ys[i] = np.random.choice([0, 1], size=1, p=[0.9, 0.1])[0]\n else:\n ys[i] = np.random.choice([0, 1], size=1, p=[0.2, 0.8])[0]\n return np.array([[xs[i], ys[i]] for i in range(0, m)])\n\n def draw_sample_intervals(self, m, k):\n \"\"\"\n Plots the data as asked in (a) i ii and iii.\n Input: m - an integer, the size of the data sample.\n k - an integer, the maximum number of intervals.\n\n Returns: None.\n \"\"\"\n samples = self.sample_from_D(m)\n samples = samples[samples[:, 0].argsort()]\n plt.scatter(samples[:, 0], samples[:, 1])\n plt.xlim(-0.1, 1.1)\n plt.ylim(-0.1, 1.1)\n plt.axvline(x=0.2)\n plt.axvline(x=0.4)\n plt.axvline(x=0.6)\n plt.axvline(x=0.8)\n (inters, best_err) = intervals.find_best_interval(\n samples[:, 0], samples[:, 1], 3)\n flat_inters = []\n for i in range(k):\n flat_inters.append(inters[i][0])\n flat_inters.append(inters[i][1])\n for interval in inters:\n dots = np.linspace(interval[0], interval[1], num=1000)\n plt.plot(dots, [-0.1] * 1000, linewidth=5)\n plt.xticks(flat_inters)\n plt.show()\n return inters\n\n def experiment_m_range_erm(self, m_first, m_last, step, k, T):\n \"\"\"Runs the ERM algorithm.\n Calculates the empirical error and the true error.\n Plots the average empirical and true errors.\n Input: m_first - an integer, the smallest size of the data sample in the range.\n m_last - an integer, the largest size of the data sample in the range.\n step - an integer, the difference between the size of m in each loop.\n k - an integer, the maximum number of intervals.\n T - an integer, the number of times the experiment is performed.\n\n Returns: np.ndarray of shape (n_steps,2).\n A two dimensional array that contains the average empirical error\n and the average true error for each m in the range accordingly.\n \"\"\"\n m_array = []\n for m in range(m_first, m_last+step, step):\n m_array.append(m)\n m_array = np.array(m_array)\n avg_empirical_array = np.array(\n [0 for x in range(m_first, m_last+step, step)], dtype=np.float32)\n avg_true_array = np.array(\n [0 for x in range(m_first, m_last+step, step)], dtype=np.float32)\n for t in range(0, T):\n for m in range(m_first, m_last+step, step):\n sample_array = self.sample_from_D(m)\n sample_array = sample_array[sample_array[:, 0].argsort()]\n xs = sample_array[:, 0]\n ys = sample_array[:, 1]\n all_intervals = intervals.find_best_interval(xs, ys, k)[0]\n # calculate empirical err\n sum = 0\n for index in range(len(xs)):\n is_in_any_interval = False\n for interval in all_intervals:\n if(self.is_in_interval(interval, xs[index])):\n is_in_any_interval = True\n if((is_in_any_interval and ys[index] == 0) or\n (not is_in_any_interval and ys[index] == 1)):\n sum = sum + 1\n empirical_err = sum/m\n true_err = self.calculate_error_from_intervals(all_intervals)\n avg_empirical_array[int(\n (m - m_first)/step)] = avg_empirical_array[int((m - m_first)/step)] + empirical_err/T\n avg_true_array[int(\n (m - m_first)/step)] = avg_true_array[int((m - m_first)/step)] + true_err/T\n line_emp, = plt.plot(m_array, avg_empirical_array)\n line_true, = plt.plot(m_array, avg_true_array)\n plt.xlabel(\"m\")\n plt.ylabel(\"error\")\n plt.legend([line_emp, line_true], ['Empirical Error', 'True Error'])\n plt.show()\n\n def experiment_k_range_erm(self, m, k_first, k_last, step):\n \"\"\"Finds the best hypothesis for k= 1,2,...,10.\n Plots the empirical and true errors as a function of k.\n Input: m - an integer, the size of the data sample.\n k_first - an integer, the maximum number of intervals in the first experiment.\n m_last - an integer, the maximum number of intervals in the last experiment.\n step - an integer, the difference between the size of k in each experiment.\n\n Returns: The best k value (an integer) according to the ERM algorithm.\n \"\"\"\n k_array, empirical_array, true_array = self.compute_errors_and_ks(\n m, k_first, k_last, step)\n line_emp, = plt.plot(k_array, empirical_array)\n line_true, = plt.plot(k_array, true_array)\n plt.xlabel(\"k\")\n plt.ylabel(\"error\")\n plt.legend([line_emp, line_true], ['Empirical Error', 'True Error'])\n plt.show()\n\n def experiment_k_range_srm(self, m, k_first, k_last, step):\n \"\"\"Runs the experiment in (d).\n Plots additionally the penalty for the best ERM hypothesis.\n and the sum of penalty and empirical error.\n Input: m - an integer, the size of the data sample.\n k_first - an integer, the maximum number of intervals in the first experiment.\n m_last - an integer, the maximum number of intervals in the last experiment.\n step - an integer, the difference between the size of k in each experiment.\n\n Returns: The best k value (an integer) according to the SRM algorithm.\n \"\"\"\n k_array, empirical_array, true_array, penalty_array, penalty_emp_sum_array = self.compute_errors_and_ks_srm(\n m, k_first, k_last, step)\n line_emp, = plt.plot(k_array, empirical_array)\n line_true, = plt.plot(k_array, true_array)\n line_penalty, = plt.plot(k_array, penalty_array)\n line_emp_penalty_sum, = plt.plot(k_array, penalty_emp_sum_array)\n plt.xlabel(\"k\")\n plt.ylabel(\"value\")\n plt.legend([line_emp, line_true, line_penalty, line_emp_penalty_sum], [\n 'Empirical Error', 'True Error', 'Penalty', 'Penalty+Empirical'])\n plt.show()\n\n def cross_validation(self, m, T):\n \"\"\"Finds a k that gives a good test error.\n Chooses the best hypothesis based on 3 experiments.\n Input: m - an integer, the size of the data sample.\n T - an integer, the number of times the experiment is performed.\n\n Returns: The best k value (an integer) found by the cross validation algorithm.\n \"\"\"\n k_first = 1\n k_last = 10\n step = 1\n k_array = []\n for k in range(k_first, k_last+step, step):\n k_array.append(k)\n k_array = np.array(k_array)\n result = []\n for t in range(0, T):\n empirical_array = np.array(\n [0 for x in range(k_first, k_last+step, step)], dtype=np.float32)\n intervals_for_k = [0 for x in range(k_first, k_last+step, step)]\n sample_array_full = self.sample_from_D(m)\n for k in range(k_first, k_last+step, step):\n sample_array = sample_array_full[:int(0.8*m)]\n sample_array = sample_array[sample_array[:, 0].argsort()]\n xs = sample_array[:, 0]\n ys = sample_array[:, 1]\n all_intervals = intervals.find_best_interval(xs, ys, k)[0]\n # empirical_err,true_err = self.calculate_errors(sample_array,k,all_intervals)\n # empirical_array[int(\n # (k - k_first)/step)] = empirical_array[int((k - k_first)/step)] + empirical_err\n intervals_for_k[int(\n (k - k_first)/step)] = all_intervals\n for k in range(k_first, k_last+step, step):\n sample_array = sample_array_full[int(0.8*m):]\n sample_array = sample_array[sample_array[:, 1].argsort()]\n empirical_err, true_err = self.calculate_errors(\n sample_array, k, intervals_for_k[int((k - k_first)/step)])\n empirical_array[int(\n (k - k_first)/step)] = empirical_array[int((k - k_first)/step)] + empirical_err\n result.append(np.argmin(empirical_array) + 1)\n print(\"OPTIMAL SOLUTION is\")\n print(result)\n return result,\n\n #################################\n # Place for additional methods\n\n def calculate_errors(self, sample_array, k, all_intervals=[]):\n xs = sample_array[:, 0]\n ys = sample_array[:, 1]\n if(len(all_intervals) == 0):\n all_intervals = intervals.find_best_interval(xs, ys, k)[0]\n # calculate empirical err\n sum = 0\n for index in range(len(xs)):\n is_in_any_interval = False\n for interval in all_intervals:\n if(self.is_in_interval(interval, xs[index])):\n is_in_any_interval = True\n if((is_in_any_interval and ys[index] == 0) or\n (not is_in_any_interval and ys[index] == 1)):\n sum = sum + 1\n empirical_err = sum/len(sample_array)\n true_err = self.calculate_error_from_intervals(all_intervals)\n return empirical_err, true_err\n # check if value is in interval\n\n def is_in_interval(self, interval, value):\n if(interval[0] <= value and interval[1] >= value):\n return True\n return False\n\n def calculate_intervals_intersection(self, int_a, int_b):\n if(int_a[1] < int_b[0] or int_b[1] < int_a[0]):\n return 0\n if(int_a[0] <= int_b[0] and int_a[1] >= int_b[1]):\n return int_b[1] - int_b[0]\n if(int_b[0] < int_a[0] and int_b[1] > int_a[1]):\n return int_a[1] - int_a[0]\n if(int_a[0] < int_b[0] and int_a[1] < int_b[1]):\n return int_a[1] - int_b[0]\n if(int_b[0] < int_a[0] and int_b[1] < int_a[1]):\n return int_b[1] - int_a[0]\n\n def calculate_error_from_intervals(self, list_of_1_intervals):\n p_intervals = [(0, 0.2), (0.2, 0.4), (0.4, 0.6), (0.6, 0.8), (0.8, 1)]\n axis_pointer = 0\n err_sum = 0\n for p_interval in p_intervals:\n total_for_interval = 0\n for x in list_of_1_intervals:\n total_for_interval = total_for_interval + \\\n self.calculate_intervals_intersection(p_interval, x)\n total_for_interval = total_for_interval / \\\n (p_interval[1] - p_interval[0])\n if (p_interval == (0.2, 0.4) or p_interval == (0.6, 0.8)):\n err_sum = err_sum + (total_for_interval *\n 0.18 + (1-total_for_interval)*0.02)\n else:\n err_sum = err_sum + (total_for_interval *\n 0.04 + (1-total_for_interval)*0.16)\n return err_sum\n\n def calculate_penalty(self, n, k, delta):\n first = 8/n\n first_ln = np.log(40)\n second_ln = np.log((np.e * n)/(k))\n return np.sqrt(first*(first_ln + 2*k*second_ln))\n\n def compute_errors_and_ks(self, m, k_first, k_last, step):\n k_array = []\n for k in range(k_first, k_last+step, step):\n k_array.append(k)\n k_array = np.array(k_array)\n empirical_array = np.array(\n [0 for x in range(k_first, k_last+step, step)], dtype=np.float32)\n true_array = np.array(\n [0 for x in range(k_first, k_last+step, step)], dtype=np.float32)\n sample_array = self.sample_from_D(m)\n sample_array = sample_array[sample_array[:, 0].argsort()]\n for k in range(k_first, k_last+step, step):\n xs = sample_array[:, 0]\n ys = sample_array[:, 1]\n all_intervals = intervals.find_best_interval(xs, ys, k)[0]\n # calculate empirical err\n sum = 0\n for index in range(len(xs)):\n is_in_any_interval = False\n for interval in all_intervals:\n if(self.is_in_interval(interval, xs[index])):\n is_in_any_interval = True\n if((is_in_any_interval and ys[index] == 0) or\n (not is_in_any_interval and ys[index] == 1)):\n sum = sum + 1\n empirical_err = sum/m\n true_err = self.calculate_error_from_intervals(all_intervals)\n empirical_array[int(\n (k - k_first)/step)] = empirical_array[int((k - k_first)/step)] + empirical_err\n true_array[int(\n (k - k_first)/step)] = true_array[int((k - k_first)/step)] + true_err\n return k_array, empirical_array, true_array\n\n def compute_errors_and_ks_srm(self, m, k_first, k_last, step):\n k_array = []\n for k in range(k_first, k_last+step, step):\n k_array.append(k)\n k_array = np.array(k_array)\n empirical_array = np.array(\n [0 for x in range(k_first, k_last+step, step)], dtype=np.float32)\n true_array = np.array(\n [0 for x in range(k_first, k_last+step, step)], dtype=np.float32)\n penalty_array = np.array(\n [0 for x in range(k_first, k_last+step, step)], dtype=np.float32)\n penalty_emp_sum_array = np.array(\n [0 for x in range(k_first, k_last+step, step)], dtype=np.float32)\n sample_array = self.sample_from_D(m)\n sample_array = sample_array[sample_array[:, 0].argsort()]\n for k in range(k_first, k_last+step, step):\n xs = sample_array[:, 0]\n ys = sample_array[:, 1]\n all_intervals = intervals.find_best_interval(xs, ys, k)[0]\n # calculate empirical err\n sum = 0\n for index in range(len(xs)):\n is_in_any_interval = False\n for interval in all_intervals:\n if(self.is_in_interval(interval, xs[index])):\n is_in_any_interval = True\n if((is_in_any_interval and ys[index] == 0) or\n (not is_in_any_interval and ys[index] == 1)):\n sum = sum + 1\n empirical_err = sum/m\n true_err = self.calculate_error_from_intervals(all_intervals)\n penalty = self.calculate_penalty(m, k, 0.1)\n err_penalty_sum = penalty + empirical_err\n empirical_array[int(\n (k - k_first)/step)] = empirical_array[int((k - k_first)/step)] + empirical_err\n true_array[int(\n (k - k_first)/step)] = true_array[int((k - k_first)/step)] + true_err\n penalty_array[int(\n (k - k_first)/step)] = penalty_array[int((k - k_first)/step)] + penalty\n penalty_emp_sum_array[int(\n (k - k_first)/step)] = penalty_emp_sum_array[int((k - k_first)/step)] + err_penalty_sum\n return k_array, empirical_array, true_array, penalty_array, penalty_emp_sum_array\n\n #################################\n\n\nif __name__ == '__main__':\n ass = Assignment2()\n ass.draw_sample_intervals(100, 3)\n ass.experiment_m_range_erm(10, 100, 5, 3, 100)\n ass.experiment_k_range_erm(1500, 1, 10, 1)\n ass.experiment_k_range_srm(1500, 1, 10, 1)\n ass.cross_validation(1500, 3)\n"} {"blob_id": "d98e120b8fcd06c7636977ee0f35e26e07d39193", "repo_name": "wang264/JiuZhangLintcode", "path": "/Algorithm/L2/optional/573_build-post-office-ii.py", "length_bytes": 3843, "score": 4.25, "int_score": 4, "content": "# 573. Build Post Office II\n# \u4e2d\u6587English\n# Given a 2D grid, each cell is either a wall 2, an house 1 or empty 0 (the number zero, one, two), find a place to\n# build a post office so that the sum of the distance from the post office to all the houses is smallest.\n#\n# Return the smallest sum of distance. Return -1 if it is not possible.\n#\n# Example\n# Example 1:\n#\n# Input\uff1a[[0,1,0,0,0],[1,0,0,2,1],[0,1,0,0,0]]\n# Output\uff1a8\n# Explanation\uff1a Placing a post office at (1,1), the distance that post office to all the house sum is smallest.\n# Example 2:\n#\n# Input\uff1a[[0,1,0],[1,0,1],[0,1,0]]\n# Output\uff1a4\n# Explanation\uff1a Placing a post office at (1,1), the distance that post office to all the house sum is smallest.\n# Notice\n# You cannot pass through wall and house, but can pass through empty.\n# You only build post office on an empty.\n\n# 573. \u90ae\u5c40\u7684\u5efa\u7acb II\n# \u4e2d\u6587English\n# \u7ed9\u51fa\u4e00\u4e2a\u4e8c\u7ef4\u7684\u7f51\u683c\uff0c\u6bcf\u4e00\u683c\u53ef\u4ee5\u4ee3\u8868\u5899 2 \uff0c\u623f\u5b50 1\uff0c\u4ee5\u53ca\u7a7a 0 (\u7528\u6570\u5b570,1,2\u6765\u8868\u793a)\uff0c\u5728\u7f51\u683c\u4e2d\u627e\u5230\u4e00\u4e2a\u4f4d\u7f6e\u53bb\u5efa\u7acb\u90ae\u5c40\uff0c\u4f7f\u5f97\u6240\u6709\u7684\u623f\u5b50\u5230\u90ae\u5c40\u7684\u8ddd\u79bb\u548c\u662f\u6700\u5c0f\u7684\u3002\n# \u8fd4\u56de\u6240\u6709\u623f\u5b50\u5230\u90ae\u5c40\u7684\u6700\u5c0f\u8ddd\u79bb\u548c\uff0c\u5982\u679c\u6ca1\u6709\u5730\u65b9\u5efa\u7acb\u90ae\u5c40\uff0c\u5219\u8fd4\u56de-1.\n#\n# Example\n# \u6837\u4f8b 1:\n#\n# \u8f93\u5165\uff1a[[0,1,0,0,0],[1,0,0,2,1],[0,1,0,0,0]]\n# \u8f93\u51fa\uff1a8\n# \u89e3\u91ca\uff1a \u5728(1,1)\u5904\u5efa\u7acb\u90ae\u5c40\uff0c\u6240\u6709\u623f\u5b50\u5230\u90ae\u5c40\u7684\u8ddd\u79bb\u548c\u662f\u6700\u5c0f\u7684\u3002\n# \u6837\u4f8b 2:\n#\n# \u8f93\u5165\uff1a[[0,1,0],[1,0,1],[0,1,0]]\n# \u8f93\u51fa\uff1a4\n# \u89e3\u91ca\uff1a\u5728(1,1)\u5904\u5efa\u7acb\u90ae\u5c40\uff0c\u6240\u6709\u623f\u5b50\u5230\u90ae\u5c40\u7684\u8ddd\u79bb\u548c\u662f\u6700\u5c0f\u7684\u3002\n# Notice\n# \u4f60\u4e0d\u80fd\u7a7f\u8fc7\u623f\u5b50\u548c\u5899\uff0c\u53ea\u80fd\u7a7f\u8fc7\u7a7a\u5730\u3002\n# \u4f60\u53ea\u80fd\u5728\u7a7a\u5730\u5efa\u7acb\u90ae\u5c40\u3002\n\nEMPTY = 0\nHOUSE = 1\nWALL = 2\nINFINITY = float('inf')\nDIRECTIONS = [(0, 1), (1, 0), (-1, 0), (0, -1)]\n\nimport sys\nfrom collections import deque\n\n\nclass Solution:\n \"\"\"\n @param grid: a 2D grid\n @return: An integer\n \"\"\"\n\n def shortestDistance(self, grid):\n # write your code here\n if not grid:\n return -1\n\n num_rows = len(grid)\n num_cols = len(grid[0])\n sum_dist = [[0] * (num_cols) for _ in range(num_rows)] # total distance to house for EMPTY land (i,j)\n count = [[0] * (num_cols) for _ in range(num_rows)] # total number of house accessible for EMPTY land (i,j)\n\n total_houses_count = 0\n for i in range(num_rows):\n for j in range(num_cols):\n if grid[i][j] == HOUSE:\n self.bfs(grid, i, j, sum_dist, count)\n total_houses_count += 1\n\n min_dist = sys.maxsize\n for i in range(num_rows):\n for j in range(num_cols):\n if count[i][j] == total_houses_count and sum_dist[i][j] < min_dist:\n min_dist = sum_dist[i][j]\n\n return min_dist if min_dist != sys.maxsize else -1\n\n def bfs(self, grid, x, y, dist, count):\n queue = deque([(x, y)])\n visited = set()\n visited.add((x, y))\n\n level = 0\n while queue:\n n = len(queue)\n for _ in range(n):\n x, y = queue.popleft()\n if dist[x][y] == sys.maxsize:\n dist[x][y] = 0\n\n dist[x][y] += level\n for dx, dy in DIRECTIONS:\n new_x, new_y = x + dx, y + dy\n if (new_x, new_y) in visited:\n continue\n\n if not self.is_valid_path(grid, new_x, new_y):\n continue\n\n count[new_x][new_y] += 1\n queue.append((new_x, new_y))\n visited.add((new_x, new_y))\n level += 1\n\n def is_valid_path(self, grid, x, y):\n return 0 <= x < len(grid) and 0 <= y < len(grid[0]) and grid[x][y] == EMPTY\n\n\nsol = Solution()\nsol.shortestDistance(grid=[[0, 1, 0, 0, 0], [1, 0, 0, 2, 1], [0, 1, 0, 0, 0]])"} {"blob_id": "afc9899cba244fbfb6f16d84dfc806ed523a1e80", "repo_name": "cklll/competitive-programming", "path": "/leetcode/max-product-subarray.py", "length_bytes": 2366, "score": 3.515625, "int_score": 4, "content": "# https://leetcode.com/problems/maximum-product-subarray/submissions/\n\nfrom typing import List\n\n# very stupid approach\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n # split to list of list, separated by 0\n # it's easier to handle\n\n nums_of_nums = []\n current_nums = []\n current_max = nums[0]\n for num in nums:\n if num == 0:\n current_max = 0 # just in case if all other nums are negative\n if current_nums:\n nums_of_nums.append(current_nums)\n current_nums = []\n else:\n current_nums.append(num)\n\n if len(current_nums) > 0:\n nums_of_nums.append(current_nums)\n\n # the result will be either:\n # 1. when number of negative numbers is even, product of all nums\n # 2. when is odd, product until last negative number (excluding),\n # OR product from 2nd negative number\n for sub_nums in nums_of_nums:\n # use stupid approach.\n num_of_neg = 0\n first_neg_index = -1\n last_neg_index = -1\n for i in range(len(sub_nums)):\n num = sub_nums[i]\n if num < 0:\n num_of_neg += 1\n if first_neg_index == -1:\n first_neg_index = i\n last_neg_index = i\n\n if num_of_neg % 2 == 0:\n sub_max = sub_nums[0]\n for num in sub_nums[1:]:\n sub_max *= num\n else:\n sub_max1 = sub_nums[0]\n for num in sub_nums[1:last_neg_index]:\n sub_max1 *= num\n\n # only the last num is negative\n if first_neg_index+1 == len(sub_nums):\n sub_max2 = sub_nums[first_neg_index]\n else:\n sub_max2 = 1\n for num in sub_nums[first_neg_index+1:]:\n sub_max2 *= num\n\n sub_max = max(sub_max1, sub_max2)\n\n current_max = max(sub_max, current_max)\n\n return current_max\n\nprint(Solution().maxProduct([2,-5,-2,-4,3]))\nprint(Solution().maxProduct([2,3,-2,4]))\nprint(Solution().maxProduct([-2,0,-1]))\nprint(Solution().maxProduct([0]))\nprint(Solution().maxProduct([0, 2]))\n"} {"blob_id": "57c27259ecb108ea26e23acacf45ecefcb31b41d", "repo_name": "prerna2055/investment-analysis", "path": "/Module.py", "length_bytes": 9121, "score": 3.703125, "int_score": 4, "content": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[3]:\n\n\nimport pandas as pd\n\ndef drawdown(return_series: pd.Series):\n \"\"\"\n Takes a time series of asset returns and Computes and returns a DataFrame that contains:\n Wealth Index\n Previous peaks\n % Drawdowns\n \"\"\"\n wealth_index=1000*(1+return_series).cumprod()\n previous_peaks = wealth_index.cummax()\n drawdowns = (wealth_index - previous_peaks)/previous_peaks\n return pd.DataFrame({\n \"Wealth\": wealth_index,\n \"Peaks\": previous_peaks,\n \"Drawdown\": drawdowns\n })\n\n \ndef semideviation(r):\n \"\"\"\n Returns the semi deviation or negative semideviation of r must be a series or a DataFrame\n \"\"\"\n \n is_negative = r < 0\n return r[is_negative].std(ddof=0)\n\ndef skewness(r):\n \"\"\"\n An alternative to the scipy.stats.skew()\n Computes skewness of the supplied series of DF\n Returns a float or a Series\n \"\"\"\n demeaned_r = r-r.mean()\n sigma_r=r.std(ddof=0) #use population Std. , so, set dof=0, i.e. no (n-1) correction\n exp = (demeaned_r**3).mean()\n return exp/sigma_r**3\n\ndef kurtosis(r):\n \"\"\"\n An alternative to the scipy.stats.kurtosis()\n Computes kurtosis of the supplied series of DF\n Returns a float or a Series\n \"\"\"\n demeaned_r = r-r.mean()\n sigma_r=r.std(ddof=0) #use population Std. , so, set dof=0, i.e. no (n-1) correction\n exp = (demeaned_r**4).mean()\n return exp/sigma_r**4\n\n\nimport scipy.stats\ndef is_normal(r, level = 0.01):\n \"\"\"\n Applies Jarque-Bera test to determine if series is normal or not\n Test is applied at the 1% level by default\n Returns True if hypothesis of normailty is accepted, False otherwise\n \"\"\"\n statistic, p_value = scipy.stats.jarque_bera(r)\n return p_value>level\n\ndef annualize_return(r,periods_per_year):\n \"\"\"\n Annualizes the set of returns\n \"\"\"\n compounded_growth = (1+r).prod()\n n_periods = len(r)\n return compounded_growth**(periods_per_year/n_periods)-1\n \ndef annualize_vol(r, periods_per_year):\n \"\"\"\n Annualizes the volume of a set of returns\"\"\"\n return r.std()*(periods_per_year**0.5)\n\ndef sharpe_ratio(r, riskfree_rate, periods_per_year):\n \"\"\"\n Computes the annualized sharpe ratio of a set of returns\n \"\"\"\n#convert the annual riskfree rate to per period\n\n rf_per_period = (1+riskfree_rate)**(1/periods_per_year)-1\n excess_ret = r-rf_per_period\n ann_ex_ret = annualize_return(excess_ret, periods_per_year)\n ann_vol = annualize_vol(r, periods_per_year)\n return ann_ex_ret/ann_vol\nimport numpy as np\ndef var_hist(r, level=5):\n \"\"\"\n Returns the historic VaR at a specified level, i.e. returns the number such that \"level\" percent of the returns fall below that number, and the (100-level) percent are above\n \"\"\"\n if isinstance(r, pd.DataFrame):\n return r.aggregate(var_hist, level=level)\n elif isinstance(r, pd.Series):\n return -np.percentile(r, level)\n else:\n raise TypeError(\"Expected r to be series or DataFrame\")\n \n\nfrom scipy.stats import norm\ndef var_gaussian(r, level=5):\n \"\"\"\n Returns the Parametric Gaussian(Variance Covariance approach) VaR of Seris or DataFrame\n \"\"\"\n #assuming Z score to be Gaussian\n z= norm.ppf(level/100)\n return -(r.mean() + z*r.std(ddof = 0))\n \n \ndef var_modified(r, level = 5):\n \"\"\"\n Returns Parametric Gausian VaR of a Series or DataFrame \n If \"modified\" is TRUE, then the modified VaR is returned,\n using the Cornish-Fisher modification\n \"\"\"\n #compute the Z score assuming it was Gausian\n z= norm.ppf(level/100)\n #if modified:\n # modify the Z score based on observed skewness and kurtosis\n s=skewness(r)\n k=kurtosis(r)\n z=(z +\n (z**2-1)*s/6 + \n (z**3 -3*z)*(k-3)/24 -\n (2*z**3 - 5*z)*(s**2)/36\n )\n return -(r.mean() + z*r.std(ddof = 0))\n\n#CVaR\ndef cvar_hist(r, level=5):\n \"\"\"\n Returns the historic VaR at a specified level, i.e. returns the number such that \"level\" percent of the returns fall below that number, and the (100-level) percent are above\n \"\"\"\n if isinstance(r, pd.DataFrame):\n return r.aggregate(cvar_hist, level=level)\n elif isinstance(r, pd.Series):\n is_beyond = r <= -var_hist(r, level=level)\n return -r[is_beyond].mean()\n else:\n raise TypeError(\"Expected r to be series or DataFrame\")\n\n \n #Computing Portfolio Risk and Returns\ndef portfolio_return(weights, returns):\n \"\"\"\n Computes the return on a portfolio from constituent returns and weights\n weights are a numpy array or Nx1 matrix and returns are a numpy array or Nx1 matrix\n \"\"\"\n return weights.T @ returns\n\ndef portfolio_vol(weights, covmat):\n \"\"\"\n Computes the vol of a portfolio from a covariance matrix and constituent weights\n weights are a numpy array or N x 1 maxtrix and covmat is an N x N matrix\n \"\"\"\n return (weights.T @ covmat @ weights)**0.5\n\ndef plot_EF2(n_points, er, cov, style = \".-\", title= 'Two Asset Efficient Frontier'):\n \"\"\"\n Plots the 2-Asset Efficient Frontier\n \"\"\"\n if er.shape[0] != 2 or er.shape[0] != 2:\n raise ValueError(\"plot_EF can plot only two asset frontiers\")\n weights = [np.array([w, 1-w]) for w in np.linspace(0, 1, n_points)]\n Rets = [portfolio_return(w,er) for w in weights]\n Vols = [portfolio_vol(w, cov) for w in weights]\n ef = pd.DataFrame({\"Returns\": Rets, \"Volatility\": Vols})\n \n return ef.plot.line(x = \"Volatility\", y = \"Returns\", style = style)\n\n\"\"\"\n Plots the Multi-Asset Efficient Frontier\n \"\"\"\nfrom scipy.optimize import minimize\ndef minimize_vol(target_return, er, cov):\n \"\"\"\n Returns the optimal weights that achieve the target return\n given a set of expected returns and a covariance matrix\n \"\"\"\n n = er.shape[0]\n init_guess = np.repeat(1/n, n)\n bounds = ((0.0, 1.0),) * n # an N-tuple of 2-tuples!\n # construct the constraints\n weights_sum_to_1 = {'type': 'eq',\n 'fun': lambda weights: np.sum(weights) - 1\n }\n return_is_target = {'type': 'eq',\n 'args': (er,),\n 'fun': lambda weights, er: target_return - portfolio_return(weights,er)\n }\n weights = minimize(portfolio_vol, init_guess,\n args=(cov,), method='SLSQP',\n options={'disp': False},\n constraints=(weights_sum_to_1,return_is_target),\n bounds=bounds)\n return weights.x\n\ndef optimal_weights(n_points, er, cov):\n \"\"\"\n \"\"\"\n target_rs = np.linspace(er.min(), er.max(), n_points)\n weights = [minimize_vol(target_return, er, cov) for target_return in target_rs]\n return weights\n\ndef plot_ef_multi(n_points, er, cov, style = \".-\", title= 'Multi-Asset Efficient Frontier'):\n \"\"\"\n Plots the multi-asset efficient frontier\n \"\"\"\n weights = optimal_weights(n_points, er, cov) # not yet implemented!\n rets = [portfolio_return(w, er) for w in weights]\n vols = [portfolio_vol(w, cov) for w in weights]\n ef = pd.DataFrame({\n \"Returns\": rets, \n \"Volatility\": vols\n })\n return ef.plot.line(x=\"Volatility\", y=\"Returns\", style='.-')\n\n'''\nFinding the MSR portfolio\n'''\ndef msr(riskfree_rate, er, cov):\n \"\"\"\n Returns the weights of the portfolio that gives you the maximum sharpe ratio\n given the riskfree rate and expected returns and a covariance matrix\n \"\"\"\n n = er.shape[0]\n init_guess = np.repeat(1/n, n)\n bounds = ((0.0, 1.0),) * n # an N-tuple of 2-tuples!\n # construct the constraints\n weights_sum_to_1 = {'type': 'eq',\n 'fun': lambda weights: np.sum(weights) - 1\n }\n def neg_sharpe(weights, riskfree_rate, er, cov):\n \"\"\"\n Returns the negative of the sharpe ratio\n of the given portfolio\n \"\"\"\n r = portfolio_return(weights, er)\n vol = portfolio_vol(weights, cov)\n return -(r - riskfree_rate)/vol\n\n weights = minimize(neg_sharpe, init_guess,\n args=(riskfree_rate, er, cov), method='SLSQP',\n options={'disp': False},\n constraints=(weights_sum_to_1,),\n bounds=bounds)\n return weights.x\n \ndef plot_ef(n_points,er,cov, show_cml = False, style ='.-', riskfree_rate=0):\n '''\n plots the multiasset frontier\n '''\n weights = optimal_weights(n_points,er,cov)\n rets = [portfolio_return(w,er) for w in weights]\n vols = [portfolio_vol(w,cov) for w in weights]\n ef = pd.DataFrame({\n \"Returns\": rets,\n \"Volatility\": vols\n })\n ax = ef.plot.line(x=\"Volatility\", y = \"Returns\", style=style)\n if show_cml:\n ax.set_xlim(left = 0)\n # get MSR\n w_msr = msr(riskfree_rate, er, cov)\n r_msr = portfolio_return(w_msr, er)\n vol_msr = portfolio_vol(w_msr, cov)\n # add CML\n cml_x = [0, vol_msr]\n cml_y = [riskfree_rate, r_msr]\n ax.plot(cml_x, cml_y, color='green', marker='o', linestyle='dashed', linewidth=2, markersize=12)\n \n"} {"blob_id": "7765d51fd059b85e4d4c45f0b5b3aeee3f7675cc", "repo_name": "HongguJeong/Digital_Video_Processing", "path": "/3. Motion Estimation/Assignment_3_ME.py", "length_bytes": 10719, "score": 3.515625, "int_score": 4, "content": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Nov 4 00:32:16 2019\n\n@author: Ibrahim El-Shal\nAssignment 3:\n- Develop a Motion Estimation algorithm using Window Search to encode two images in YUV format. \n- Use 8x8 block.\n- Reconstruct the images using Motion Compensation. \n- Compute PSNR between the Source Image and the Reconstructed Images.\n- Compare between the two Algorithms\n- Bonus : you may choose more than one matching criteria\n- Bonus : you may choose more than these two algorithms \n\"\"\"\n# In[1]: Import Packages\n\nimport os\nimport sys\nimport cv2\nimport math\nimport time\nimport numpy as np\n\n# In[1-2]:\n \nGRID_SIZE = 8\nOVERLAPPED_WIDTH = 10\nOVERLAPPED_HEIGHT = 10\n\n# In[2]: Functions of Image\n\ndef ReadFrames(FrameNumber):\n return(cv2.imread(\"frames/frame%d.jpg\"%FrameNumber))\n \ndef RGB2YUV(RGBImage):\n return(cv2.cvtColor(RGBImage, cv2.COLOR_BGR2YUV)) \n \ndef YUV2RGB(YUVImage):\n return(cv2.cvtColor(YUVImage,cv2.COLOR_YUV2BGR)) \n \ndef Split_Channels(img):\n return (cv2.split((img))) \n \ndef Create_Dir(directory):\n if not os.path.exists(directory):\n os.makedirs(directory)\n\ndef Save_Image(Name,Image):\n return(cv2.imwrite(Image, Name))\n \ndef Get_PSNR(arr):\n mse = (arr ** 2).mean()\n psnr = 10 * math.log10((255 ** 2) / mse)\n return psnr\n\ndef psnr(orignal_picture,compressed_picture):\n# peak signal-to-noise ratio\n mse =0\n #mean squared error\n for i in range(len(orignal_picture)):\n for j in range(len(orignal_picture[i])):\n mse=mse+(orignal_picture[i][j]-compressed_picture[i][j])*(orignal_picture[i][j]-compressed_picture[i][j])\n mse=mse/(len(orignal_picture)*len(orignal_picture[i]))\n mx_value=0\n for lst in orignal_picture:\n value=max(lst)\n if value > mx_value:\n mx_value=value\n psnr_=10*math.log( mx_value*mx_value/ mse, 10)\n return psnr_\n \n# In[3]: Convert Video Into frames\n \ndef Video2Frames(VideoName):\n \n cap = cv2.VideoCapture(VideoName)\n Create_Dir('./frames/') \n frame_counter = 0\n \n if not cap.isOpened():\n print('{} not opened'.format(VideoName))\n sys.exit(1)\n\n while(1):\n return_flag, frame = cap.read()\n if not return_flag:\n print('Video Reach End')\n break\n #Start\n cv2.imwrite('./frames/' + 'frame%d.jpg' % frame_counter, frame)\n frame_counter += 1\n #End\n cap.release()\n return(1)\n\n# In[4]: Get the needed search area \n \ndef Search_Range(w_min, h_min, w_max, h_max, curr_w, curr_h, w_size, h_size):\n \n start_w = curr_w - w_size if curr_w - w_size > w_min else w_min\n end_w = curr_w + w_size if curr_w + w_size < w_max else curr_w\n start_h = curr_h - h_size if curr_h - h_size > h_min else h_min\n end_h = curr_h + h_size if curr_h + h_size < h_max else curr_h\n return (start_w, start_h, end_w, end_h)\n\n# In[5]: Get Needed blocked 8x8\n \ndef Needed_Blocks(Frame):\n \n img_blocks = []\n img_blocks_idx = [] \n\n # shape of image\n height, width = Frame.shape\n\n for h_idx in range(0, height, GRID_SIZE):\n micro_block_per_row = []\n micro_block_idx_per_row = []\n for w_idx in range(0, width, GRID_SIZE):\n micro_block_per_row.append(Frame[h_idx: h_idx + GRID_SIZE, w_idx: w_idx + GRID_SIZE])\n micro_block_idx_per_row.append((w_idx, h_idx))\n img_blocks_idx.append(micro_block_idx_per_row)\n img_blocks.append(micro_block_per_row)\n\n return(img_blocks_idx, img_blocks)\n \n# In[6]:Get the Movtion Vector of each picked Block to comparison with others \n \ndef MotionVector(Current_Block, Next_Frame, x_micro, y_micro, search_area):\n \n mv = (0, 0)\n min_value = np.inf\n \n start_w, start_h, end_w, end_h = search_area\n \n for y in range(start_h, end_h + 1):\n for x in range(start_w, end_w + 1):\n # search range \n window_block = Next_Frame[y:y + GRID_SIZE, x:x + GRID_SIZE]\n value = np.sum(np.abs(Current_Block - window_block))\n\n if value < min_value:\n mv = (x - x_micro, y - y_micro)\n min_value = value \n return(mv)\n \n# In[7]: \n\ndef Block_Matching(curr_frame, next_frame):\n\n height, width = curr_frame.shape\n block_idx_list, block_list = Needed_Blocks(curr_frame)\n\n frame_motion_vector = [[0 for j in range(len(block_idx_list[0]))] for i in range(len(block_list))]\n \n for h in range(len(block_idx_list)):\n for w in range(len(block_list[0])):\n # search range \n micro_x, micro_y = block_idx_list[h][w]\n Grid_Block = block_list[h][w]\n\n search_range = Search_Range(0, 0, width, height, micro_x, micro_y, GRID_SIZE, GRID_SIZE)\n \n frame_motion_vector[h][w] = MotionVector(Grid_Block,next_frame,\n micro_x, micro_y, search_range)\n\n return frame_motion_vector\n\n# In[8]: \n \ndef TSS_Block_Matching(curr_frame, next_frame):\n\n TSS_GRID_SIZE = GRID_SIZE\n height, width = curr_frame.shape\n block_idx_list, block_list = Needed_Blocks(curr_frame)\n\n frame_motion_vector = [[(0,0) for j in range(len(block_idx_list[0]))] for i in range(len(block_list))]\n \n for h in range(len(block_idx_list)-1): \n for w in range(len(block_list[0])-1): \n # search range \n micro_x, micro_y = block_idx_list[h][w]\n Grid_Block = block_list[h][w] \n TSS_GRID_SIZE = GRID_SIZE\n \n for i in range(3):\n TSS_GRID_SIZE = TSS_GRID_SIZE // 2\n search_range = Search_Range(0, 0, width, height, micro_x, micro_y,\n TSS_GRID_SIZE, TSS_GRID_SIZE)\n \n frame_motion_vector[h][w] = MotionVector(Grid_Block,next_frame,\n micro_x, micro_y, search_range)\n \n micro_x, micro_y = frame_motion_vector[h][w]\n \n return frame_motion_vector\n\n# In[8]:\n\ndef Overlapped_Motion_Vector(Current_frame, motion_vector):\n \n height, width = Current_frame.shape\n Current_frame = Current_frame.astype(np.uint32)\n \n overlapped_range = [[[] for j in range(len(motion_vector[i]))] for i in range(len(motion_vector))]\n overlapped_width = int((OVERLAPPED_WIDTH - GRID_SIZE) / 2)\n overlapped_height = int((OVERLAPPED_HEIGHT - GRID_SIZE) / 2)\n\n overlapped_motion_vector = [[[] for j in range(width)] for i in range(height)]\n\n for h in range(0, int(height / GRID_SIZE)):\n for w in range(0, int(width / GRID_SIZE)):\n temp_w = w * GRID_SIZE\n temp_h = h * GRID_SIZE\n s_x = temp_w - overlapped_width if temp_w - overlapped_width >= 0 else temp_w\n s_y = temp_h - overlapped_height if temp_h - overlapped_height >= 0 else temp_h\n e_x = (w + 1) * GRID_SIZE\n e_x = e_x + overlapped_width if e_x + overlapped_width < width else e_x\n e_y = (h + 1) * GRID_SIZE\n e_y = e_y + overlapped_height if e_y + overlapped_height < height else e_y\n overlapped_range[h][w] = (motion_vector[h][w], [[s_x, s_y], [e_x, e_y]])\n for y in range(s_y, e_y):\n for x in range(s_x, e_x):\n overlapped_motion_vector[y][x].append(motion_vector[h][w])\n \n return(overlapped_motion_vector)\n \n# In[9]:\n \n#Function to reconstruct a frame from a reference frame given the motion vectors in a macroblock \n#Inputs: Reference Frame, Macroblocks containing motion vectors\n#Outputs:reconstructed_frame \n\ndef Create_Compressed_Image(Curr_frame, Post_frame, overlapped_MV):\n \n height, width = Curr_frame.shape\n Post_frame = Post_frame.astype(np.uint32)\n interpolated_frame = [[0 for j in range(width)] for i in range(height)]\n\n for y in range(height):\n for x in range(width):\n sum = 0\n for mv in overlapped_MV[y][x]:\n \n prev_y = y + mv[1]\n if prev_y >= height or prev_y < 0:\n prev_y = 0 if prev_y < 0 else height - 1\n\n prev_x = x + mv[0]\n if prev_x >= width or prev_x < 0:\n prev_x = 0 if prev_x < 0 else width - 1\n\n next_y = y - mv[1]\n if next_y >= height or next_y < 0:\n next_y = 0 if next_y < 0 else height - 1\n\n next_x = x - mv[0]\n if next_x >= width or next_x < 0:\n next_x = 0 if next_x < 0 else width - 1\n\n sum += Curr_frame[prev_y][prev_x] + Post_frame[next_y, next_x]\n\n l = len(overlapped_MV[y][x]) * 2\n res = sum / l\n res = np.array(res).T\n \n interpolated_frame[y][x] = res.astype(np.uint8)\n\n Final_Image = np.array(interpolated_frame)\n return(Final_Image)\n\n# In[10]:\n\ndef Window_Full_Search(): \n\n current_frame = ReadFrames(0)\n next_frame = ReadFrames(1)\n\n #Convert to YUV Image\n current_yuv = RGB2YUV(current_frame)\n next_yuv = RGB2YUV(next_frame)\n\n ###Get Channels\n curr_Y, curr_U, curr_V = Split_Channels(current_yuv)\n next_Y, next_U, next_V = Split_Channels(next_yuv)\n\n Mv = Block_Matching(curr_Y,next_Y)\n Overlapped_Mv = Overlapped_Motion_Vector(curr_Y, Mv)\n Img = Create_Compressed_Image(curr_Y, next_Y, Overlapped_Mv) \n \n return(Img)\n\n\ndef TSS_Search(): \n\n current_frame = ReadFrames(0)\n next_frame = ReadFrames(1)\n\n #Convert to YUV Image\n current_yuv = RGB2YUV(current_frame)\n next_yuv = RGB2YUV(next_frame)\n\n ###Get Channels\n curr_Y, curr_U, curr_V = Split_Channels(current_yuv)\n next_Y, next_U, next_V = Split_Channels(next_yuv)\n\n Save_Image(curr_Y,\"Original Img.jpg\")\n Mv = TSS_Block_Matching(curr_Y,next_Y)\n Overlapped_Mv = Overlapped_Motion_Vector(curr_Y, Mv)\n Img = Create_Compressed_Image(curr_Y, next_Y, Overlapped_Mv) \n \n return(Img)\n\n# In[11]:\n \ndef main():\n \n #Video2Frames('./video.mp4')\n \n start = time.time()\n WinImg = Window_Full_Search()\n end = time.time()\n res_psnr = Get_PSNR(WinImg)\n print('PSNR at Window Matching:',res_psnr)\n print('Window Matching Running Time:',(end - start)) \n\n start = time.time()\n TssImg = TSS_Search()\n end = time.time()\n res_psnr = Get_PSNR(WinImg)\n print('\\nPSNR at TSS:',res_psnr)\n print('TSS Running Time:',(end - start)) \n \n return(WinImg,TssImg)\n\n# In[11]:\n\n## call the main function\nif __name__ == '__main__':\n WinImg,TssImg = main()\n\nSave_Image(WinImg,\"Img of Window.jpg\")\nSave_Image(TssImg,\"Img of Thee Step.jpg\")"} {"blob_id": "3b17da4171b2d00877200cfacf72d48b68d2c2cd", "repo_name": "godscreator/GeneticAlgorithms", "path": "/Genetic/MultiObjectiveAlgorithms.py", "length_bytes": 9223, "score": 3.90625, "int_score": 4, "content": "import math\nimport random\nfrom abc import ABC, abstractmethod\nfrom typing import List\n\n\nclass Gene(ABC):\n \"\"\"\n Gene is template to make a genotype of the solution.\n \"\"\"\n\n @classmethod\n @abstractmethod\n def create_random(cls) -> 'Gene':\n \"\"\"\n Create a gene with random data.\n\n :return: a gene with random data.\n \"\"\"\n pass\n\n @abstractmethod\n def mutate(self) -> None:\n \"\"\"\n Mutate the gene.\n\n :return: None\n \"\"\"\n pass\n\n @staticmethod\n @abstractmethod\n def crossover(parent_a: 'Gene', parent_b: 'Gene') -> ('Gene', 'Gene'):\n \"\"\"\n Crossover between parent genes.\n\n :param parent_a: First Parent gene\n :param parent_b: Second Parent gene\n :return: Two children gene of parent genes\n \"\"\"\n pass\n\n @abstractmethod\n def calculate_fitness(self) -> List[float]:\n \"\"\"\n calculate fitness of gene.\n\n :return: fitness\n \"\"\"\n pass\n\n\nclass GeneWrapper:\n \"\"\" Wrapper for gene in a population.\"\"\"\n\n def __init__(self, gene: Gene):\n self.gene = gene\n self.fitness = gene.calculate_fitness()\n self.rank = 0\n self.cDist = 0\n\n def __eq__(self, other):\n return self.rank == other.rank and self.cDist == other.cDist\n\n def __lt__(self, other):\n return self.rank > other.rank or (self.rank == other.rank and self.cDist < self.cDist)\n\n def __gt__(self, other):\n return self.rank < other.rank or (self.rank == other.rank and self.cDist > self.cDist)\n\n @staticmethod\n def dominates(p: 'GeneWrapper', q: 'GeneWrapper') -> bool:\n \"\"\"\n Returns if p dominates q.\n\n :param p: List of fitness of solution p.\n :param q: List of fitness of solution q (in same order as of p).\n :return: if p dominates q.\n \"\"\"\n length = min(len(p.fitness), len(q.fitness))\n for i in range(length):\n if p.fitness[i] < q.fitness[i]:\n return False\n for i in range(length):\n if p.fitness[i] > q.fitness[i]:\n return True\n return False\n\n\ndef fast_non_dominated_sort(genes: List[GeneWrapper]) -> List[List[GeneWrapper]]:\n \"\"\"\n Returns non dominated sorted front(list of index of solutions that are non dominating to each other) of solutions in increasing order of ranks.\n\n :param genes: List of gene wrappers.\n :return: list of fronts.\n \"\"\"\n pop_len = len(genes)\n S = [set() for _ in range(pop_len)] # solutions dominated by gene(solution) at that index.\n N = [0 for _ in range(pop_len)] # number of solutions dominating gene(solution) at that index.\n F = [] # solution fronts\n F_0 = [] # zeroth front\n r = 1\n for i in range(pop_len):\n for j in range(pop_len):\n if GeneWrapper.dominates(genes[i], genes[j]):\n S[i].add(j)\n elif GeneWrapper.dominates(genes[j], genes[i]):\n N[i] += 1\n if N[i] == 0:\n genes[i].rank = r\n F_0.append(i)\n F.append(F_0)\n F_i = F_0\n while F_i:\n H = []\n r += 1\n for i in F_i:\n for j in S[i]:\n N[j] -= 1\n if N[j] == 0:\n H.append(j)\n genes[j].rank = r\n F_i = H\n if F_i:\n F.append(F_i)\n fronts = []\n for i in F:\n t = []\n for j in i:\n t.append(genes[j])\n fronts.append(t)\n\n return fronts\n\n\ndef crowding_distance_assignment(front: List[GeneWrapper]) -> None:\n \"\"\"\n crowding distance for the front.\n\n :param front: front.\n :return: None.\n \"\"\"\n for i in range(len(front[0].fitness)):\n front.sort(key=lambda x: x.fitness[i])\n front[0].cDist = math.inf\n front[-1].cDist = math.inf\n for j in range(1, len(front) - 1):\n front[j].cDist += abs(front[j + 1].fitness[i] - front[j - 1].fitness[i])\n\n\nclass NonDominatedGenePool:\n def __init__(self, gene_type, population_size: int, tournament_fraction: float = 0.1,\n mutation_rate: float = 0.1, crossover_rate: float = 1):\n \"\"\"\n Create a gene pool.\n\n :param gene_type: type of gene.\n :param population_size: size of population.\n :param tournament_fraction: faction of population as size of tournament.\n :param mutation_rate: rate of mutation.\n :param crossover_rate: rate of crossover.\n \"\"\"\n self.tournament_fraction = tournament_fraction\n self.population_size = population_size\n self.population = []\n self.fronts = []\n self.wrappers = []\n self.gene_type = gene_type\n self.mutation_rate = mutation_rate\n self.crossover_rate = crossover_rate\n\n def initialize_population(self) -> None:\n \"\"\"\n Initialize population with random genes.\n\n :return: None\n \"\"\"\n self.population = []\n for i in range(self.population_size):\n self.population.append(self.gene_type.create_random())\n # evaluate\n self.wrappers = NonDominatedGenePool.evaluate(self.population)\n\n def generate(self) -> None:\n \"\"\"\n generate next population.\n 1. selection\n 2. crossover\n 3. mutate\n 4. evaluate\n\n :return: None\n \"\"\"\n # selection\n selected = self.select(self.wrappers, self.population_size)\n\n # crossover\n new_population = self.crossover(selected)\n\n # mutation\n self.mutate(new_population)\n new_population = self.population + new_population\n\n # evaluate\n wrappers = NonDominatedGenePool.evaluate(new_population)\n wrappers.sort(reverse=True)\n\n self.population = []\n for i in wrappers[:self.population_size]:\n self.population.append(i.gene)\n self.wrappers = wrappers[:self.population_size]\n\n def select(self, wrappers: List[GeneWrapper], selection_size: int) -> List[Gene]:\n \"\"\"\n select a population of selection_size with tournament on basis of fitness.\n\n :param wrappers: list of gene wrappers.\n :param selection_size: size of population to be selected.\n :return: selected list of genes.\n \"\"\"\n selected = []\n for i in range(selection_size):\n tournament_list = random.choices(wrappers,\n k=int(len(wrappers) * self.tournament_fraction))\n winner = max(tournament_list)\n selected.append(winner.gene)\n return selected\n\n def crossover(self, selected_population: List[Gene]) -> List[Gene]:\n \"\"\"\n Crossover the selected population.\n\n :param selected_population: selected population\n :return: crossed population\n \"\"\"\n new_population = []\n for i in range(0, len(selected_population), 2):\n if i + 1 < len(selected_population):\n if random.random() <= self.crossover_rate:\n child_a, child_b = self.gene_type.crossover(selected_population[i], selected_population[i + 1])\n new_population.append(child_a)\n new_population.append(child_b)\n else:\n new_population.append(selected_population[i])\n new_population.append(selected_population[i + 1])\n else:\n new_population.append(selected_population[i])\n return new_population\n\n def mutate(self, crossed_population: List[Gene]) -> None:\n \"\"\"\n Mutate the population.\n\n :param crossed_population: list of genes to mutate.\n :return:\n \"\"\"\n for i in crossed_population:\n if random.random() <= self.mutation_rate:\n i.mutate()\n\n @staticmethod\n def evaluate(population: List[Gene]) -> List[GeneWrapper]:\n \"\"\"\n Evaluate the rank and crowding distance of population.\n\n :param population: population to evaluate.\n :return: list of rank and crowding distance.\n \"\"\"\n wrappers = []\n for i in population:\n wrappers.append(GeneWrapper(i))\n fronts = fast_non_dominated_sort(wrappers)\n for i in fronts:\n crowding_distance_assignment(i)\n return wrappers\n\n def get_population(self) -> List[Gene]:\n \"\"\"\n get population of current generation.\n\n :return: population\n \"\"\"\n return self.population\n\n def get_fitness(self) -> List[List[float]]:\n \"\"\"\n get fitness of current generation.\n\n :return: fitness\n \"\"\"\n return [i.fitness for i in self.wrappers]\n\n def get_best_genes(self) -> List[Gene]:\n \"\"\"\n get best genes of the generation.\n\n :return: best genes\n \"\"\"\n front = [i.gene for i in self.wrappers if i.rank == 1]\n return front\n\n def get_best_fitness(self) -> List[List[float]]:\n \"\"\"\n get fitness of best gene of the generation.\n\n :return: fitness of best gene of the generation.\n \"\"\"\n front = [i.fitness for i in self.wrappers if i.rank == 1]\n return front\n"} {"blob_id": "2ef19d4886644d077c1f53c97f7de400c7019540", "repo_name": "vidyasagarr7/DataStructures-Algos", "path": "/GeeksForGeeks/Arrays/Rearrange.py", "length_bytes": 1096, "score": 4.1875, "int_score": 4, "content": "\n\n\"\"\"\nRearrange an array so that arr[i] becomes arr[arr[i]] with O(1) extra space\nGiven an array arr[] of size n where every element is in range from 0 to n-1. Rearrange the given array so that\n arr[i] becomes arr[arr[i]]. This should be done with O(1) extra space.\n\nExamples:\n\nInput: arr[] = {3, 2, 0, 1}\nOutput: arr[] = {1, 0, 3, 2}\n\nInput: arr[] = {4, 0, 2, 1, 3}\nOutput: arr[] = {3, 4, 2, 0, 1}\n\nInput: arr[] = {0, 1, 2, 3}\nOutput: arr[] = {0, 1, 2, 3}\nIf the extra space condition is removed, the question becomes very easy. The main part of the question is to do it\nwithout extra space.\n\n\"\"\"\n\ndef rearrange(input_list):\n if not input_list :\n return\n else :\n n = len(input_list)\n for i in range(len(input_list)) :\n input_list[i] += (input_list[input_list[i]]%n)*n\n for i in range(len(input_list)):\n input_list[i] = input_list[i]//n\n return input_list\n\nif __name__=='__main__':\n test = [3, 2, 0, 1]\n print(rearrange(test))\n\n test = [4,0,2,1,3]\n print(rearrange(test))\n\n test = [0,1,2,3]\n print(rearrange(test))"} {"blob_id": "57cc28aff06e12ba071e2e41040bbae3da8e8d59", "repo_name": "tnagasaivijayram/lab", "path": "/Daa/10.py", "length_bytes": 663, "score": 3.65625, "int_score": 4, "content": "# method 2\nimport numpy as np\ndef floyd(graph ,v):\n for k in range(v):\n for i in range(v):\n for j in range(v):\n graph[i][j] = min(graph[i][j],graph[i][k]+graph[k][j])\n print(\"After Step\",k+1,\"Matrix A: \")\n printsol(graph,v)\n \ndef printsol(graph,v):\n for i in range(v):\n for j in range(v):\n if(graph[i][j]==INF):\n print(\" %7s \" %(\"INF\"),end=\" \")\n else :\n print(\" %7d \" %(graph[i][j]),end=\" \")\n print()\nV = 4\nINF = np.inf\ngraph = [[0, 3, INF, 7],\n [3, 0, 2, INF],\n [3, INF, 0, 1],\n [2, INF, INF, 0]]\nfloyd(graph,V)\n"} {"blob_id": "63114c7c063d18756984c9c24d2d20debc915ebe", "repo_name": "ChangYuTeng/ai108b", "path": "/homework/HWSV_pbm/HWSV_pbm.py", "length_bytes": 3389, "score": 3.78125, "int_score": 4, "content": "# initial data\nobj = [\"Human\", \"Wolf\", \"Sheep\", \"Kale\"] # Obviously, these are objects. (Kale : \u7518\u85cd\u83dc\nstatus = [False, False, False, False] # This is all initial status of the former objects.\nhtySta = [status] # This variable could help recording which step we've gone to.\nsltCnt = 0 # And this is ..., no offense, just number of solutions. (not a discrimination\n\n\n# successful condition : all members are alive\ndef alive(sta):\n if(sta[1] == sta[2]) & (sta[1] != sta[0]): # Sheep's dead.\n return False\n if(sta[2] == sta[3]) & (sta[2] != sta[0]): # Kale's eaten.\n return False\n return True # They're all alive.\n\n# generate the next status\ndef generate(sta):\n nextStaList = [] # returning variable \n \n for i in range(0, 4):\n if(sta[0] != sta[i]): # If there's anyone who's at the opposite of Human,\n continue # keep generating the next status.\n\n nextSta = sta[:] # copy of current status\n nextSta[0] = not nextSta[0] # Human goes across the river.\n nextSta[i] = nextSta[0] # Appointed animal goes accompany with Human.\n\n if(alive(nextSta)): # If next status we about to move in fits successful condition, \n nextStaList.append(nextSta) # upgrade returning status.\n \n return nextStaList # end of \"generate()\"\n\n# Find the solution of this question while distiguish if we've gone to the current step.\ndef solution(htySta):\n global sltCnt\n curSta = htySta[len(htySta) - 1]\n nextStaList = generate(curSta) # \"nextStaList\" stores all possible status groups of current status.\n\n for nextSta in nextStaList:\n if nextSta in htySta: # Check current group of status. If it has been searched,\n continue # we'll pass this group.\n\n htySta.append(nextSta) # And if this ststus group hasn't been searched,\n # we add it to \"htySta\" variable for recording.\n\n if(isDone(nextSta)): # If we fing one set of solutions, print it.\n sltCnt += 1\n print(\"Solution\" + str(sltCnt) + \":\")\n prtHtySta(htySta)\n else:\n solution(htySta) # If we haven't found a solution, keep searching.\n\n htySta.pop()\n\n# To see if we have a solution\ndef isDone(sta):\n return sta[0] and sta[1] and sta[2] and sta[3] # Because when an object reaches the opposite shore, \n # we set its value to true. \n # Therefore, if we want to know whether the search is over, \n # just use AND gate to connect statuses of all objects.\n# Beautify the performance of the output.\ndef prtHtySta(htySta):\n prtStr = \"\"\n for sta in htySta:\n prtStr += \"\\t\"\n for i in range(0, 4):\n prtStr += str(obj[i]) + \" \" + str(sta[i]) + \" \"\n prtStr += \"\\n\"\n print(prtStr + \"\\n\")\n\n# main\nsolution(htySta)\nprint(\"Success!!! Find \" + str(sltCnt) + \" solutions.\")"} {"blob_id": "cc9cf015699a1a295f847c7a2c848f6d1c23360b", "repo_name": "jdogg6ms/project_euler", "path": "/p030/p30.py", "length_bytes": 1127, "score": 3.96875, "int_score": 4, "content": "#!/usr/bin/env python\n# Project Euler Problem #30\n\n'''\nSurprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:\n\n1634 = 1^4 + 6^4 + 3^4 + 4^4\n8208 = 8^4 + 2^4 + 0^4 + 8^4\n9474 = 9^4 + 4^4 + 7^4 + 4^4\nAs 1 = 1^4 is not a sum it is not included.\n\nThe sum of these numbers is 1634 + 8208 + 9474 = 19316.\n\nFind the sum of all the numbers that can be written as the sum of fifth powers of their digits.\n'''\nfrom math import pow\n \ndef isSumOfPowers(num,power):\n g = lambda x: int(pow(x,power))\n if num == sum(map(g,[int(char) for char in str(num)])):\n return True\n else:\n return False\n\ndef find_range():\n i = 1\n while len(str(i*pow(9,5))) >= i:\n i+=1\n return 10**(i-2)\n\n \nif __name__ == \"__main__\":\n #test\n if isSumOfPowers(1634,4) and isSumOfPowers(8208,4) and \\\n isSumOfPowers(9474,4) and not isSumOfPowers(8208,5):\n print \"test passed.\"\n else:\n print \"test failed!\" \n\n result = sum([x for x in xrange(2,find_range()) if isSumOfPowers(x,5)]) \n \n print \"The answer to #30 is: %s\" %result \n"} {"blob_id": "f9291987ec98543712ec5d5c88ebe052c808db5b", "repo_name": "sbraun27/AdventofCode", "path": "/Python/20201222.py", "length_bytes": 3998, "score": 3.53125, "int_score": 4, "content": "import time\n\n\nclass Deck():\n def __init__(self, starting_cards, name):\n self.deck = starting_cards\n self.no_cards = len(starting_cards)\n self.card_history = []\n self.name = name\n\n def play_card(self):\n self.no_cards -= 1\n return self.deck.pop(0)\n\n def add_to_deck(self, card1, card2):\n self.deck.append(card1)\n self.deck.append(card2)\n self.no_cards += 2\n\n def calculate_score(self):\n self.score = 0\n for i, card in enumerate(reversed(self.deck)):\n self.score += card * (i+1)\n\n return self.score\n\n def check_history(self):\n if self.deck in self.card_history:\n return True\n else:\n self.card_history.append(self.deck.copy())\n return False\n\n\ndef load(file_path):\n with open(file_path) as f:\n file_input = f.read().split(\"\\n\\n\")\n\n player1_cards = file_input[0].split(\"\\n\")\n player2_cards = file_input[1].split(\"\\n\")\n player1 = Deck([int(i) for i in player1_cards if i.isdigit()], \"player1\")\n player2 = Deck([int(i) for i in player2_cards if i.isdigit()], \"player2\")\n\n return player1, player2\n\n\ndef play_combat(player1, player2):\n while player1.no_cards > 0 and player2.no_cards > 0:\n player1_deals = player1.play_card()\n player2_deals = player2.play_card()\n if player1_deals > player2_deals:\n player1.add_to_deck(player1_deals, player2_deals)\n else:\n player2.add_to_deck(player2_deals, player1_deals)\n\n return player1 if player1.no_cards > 0 else player2\n\n\ndef play_recursive_combat(player1, player2):\n # If there was a previous round that had the same cards in the same order, in the same players deck, player 1 wins\n # If the current deck wasn't used before, play as normal\n # If both players have at least as many cards remaining in their deck as the value of the card they just drew, the winner is determined by playing another round of recursive combat\n # Else the player doesn't have enough cards to recurse, the winner is the player with the highest card value dealt\n\n while player1.no_cards > 0 and player2.no_cards > 0:\n player1_repeat = player1.check_history()\n player2_repeat = player2.check_history()\n if player1_repeat and player2_repeat:\n # Player 1 wins automatically\n return player1\n else:\n player1_deals = player1.play_card()\n player2_deals = player2.play_card()\n if player1_deals <= player1.no_cards and player2_deals <= player2.no_cards:\n sub_player1 = Deck(player1.deck[:player1_deals], \"player1\")\n sub_player2 = Deck(player2.deck[:player2_deals], \"player2\")\n sub_winner = play_recursive_combat(sub_player1, sub_player2)\n if \"1\" in sub_winner.name:\n player1.add_to_deck(player1_deals, player2_deals)\n else:\n player2.add_to_deck(player2_deals, player1_deals)\n else:\n if player1_deals > player2_deals:\n player1.add_to_deck(player1_deals, player2_deals)\n else:\n player2.add_to_deck(player2_deals, player1_deals)\n\n return player1 if player1.no_cards > 0 else player2\n\n\nif __name__ == \"__main__\":\n player1, player2 = load(\"../input/day22.txt\")\n start = time.time()\n winner = play_combat(player1, player2)\n part1 = winner.calculate_score()\n elapsed = round(time.time() - start, 3)\n print(\n f\"Part 1: The winner was: {winner.name} with a score of: {part1}. Took: {elapsed} seconds.\")\n\n player1, player2 = load(\"../input/day22.txt\") # Create a new set of decks\n start = time.time()\n winner = play_recursive_combat(player1, player2)\n part2 = winner.calculate_score()\n elapsed = round(time.time() - start, 3)\n print(\n f\"Part 2: the winner was: {winner.name} with a score of {part2}. Took: {elapsed} seconds.\")\n"} {"blob_id": "46b464a07b98bd5724b0c919a0405d1c8ff80a1f", "repo_name": "oscarhscc/algorithm-with-python", "path": "/LeetCode/39. \u7ec4\u5408\u603b\u548c.py", "length_bytes": 1325, "score": 3.734375, "int_score": 4, "content": "'''\r\n\u7ed9\u5b9a\u4e00\u4e2a\u65e0\u91cd\u590d\u5143\u7d20\u7684\u6570\u7ec4\u00a0candidates\u00a0\u548c\u4e00\u4e2a\u76ee\u6807\u6570\u00a0target\u00a0\uff0c\u627e\u51fa\u00a0candidates\u00a0\u4e2d\u6240\u6709\u53ef\u4ee5\u4f7f\u6570\u5b57\u548c\u4e3a\u00a0target\u00a0\u7684\u7ec4\u5408\u3002\r\n\r\ncandidates\u00a0\u4e2d\u7684\u6570\u5b57\u53ef\u4ee5\u65e0\u9650\u5236\u91cd\u590d\u88ab\u9009\u53d6\u3002\r\n\r\n\u8bf4\u660e\uff1a\r\n\r\n\u6240\u6709\u6570\u5b57\uff08\u5305\u62ec\u00a0target\uff09\u90fd\u662f\u6b63\u6574\u6570\u3002\r\n\u89e3\u96c6\u4e0d\u80fd\u5305\u542b\u91cd\u590d\u7684\u7ec4\u5408\u3002\u00a0\r\n\u793a\u4f8b\u00a01\uff1a\r\n\r\n\u8f93\u5165\uff1acandidates = [2,3,6,7], target = 7,\r\n\u6240\u6c42\u89e3\u96c6\u4e3a\uff1a\r\n[\r\n [7],\r\n [2,2,3]\r\n]\r\n\u793a\u4f8b\u00a02\uff1a\r\n\r\n\u8f93\u5165\uff1acandidates = [2,3,5], target = 8,\r\n\u6240\u6c42\u89e3\u96c6\u4e3a\uff1a\r\n[\r\n\u00a0 [2,2,2,2],\r\n\u00a0 [2,3,3],\r\n\u00a0 [3,5]\r\n]\r\n'''\r\n\r\nclass Solution(object):\r\n def combinationSum(self, candidates, target):\r\n \"\"\"\r\n :type candidates: List[int]\r\n :type target: int\r\n :rtype: List[List[int]]\r\n \"\"\"\r\n result = []\r\n def dfs(temp, res):\r\n if temp > target:#\u526a\u679d\u4e00:\u5f53\u524d\u7684\u603b\u503c\u5927\u4e8e\u76ee\u6807\u503c\r\n return\r\n if temp == target:#\u5f53\u524d\u503c\u548c\u76ee\u6807\u503c\u76f8\u7b49\u7684\u65f6\u5019,\u4fdd\u5b58\u5f53\u524d\u7ed3\u679c,\u5e76\u8fd4\u56de\r\n result.append(res)\r\n return\r\n for i in candidates:\r\n if res and res[-1] > i:#\u9632\u6b62\u91cd\u590d\u7684\u65b9\u6cd5\u662f,\u4e0d\u8ba9\u5176\u627e\u5728\u5f53\u524d\u5143\u7d20\u4ee5\u524d\u7684\u5143\u7d20\r\n continue\r\n dfs(temp + i, res + [i])\r\n dfs(0, [])\r\n return result"} {"blob_id": "2fe56474d4dfa1672180cc776e05e8d3dd46f90e", "repo_name": "btrif/Python_dev_repo", "path": "/Algorithms/Recursion/N Queens Problem.py", "length_bytes": 9898, "score": 3.5625, "int_score": 4, "content": "# Created by Bogdan Trif on 10-09-2017 , 6:57 PM.\n'''\nGiven nxn board place n queen on this board so that they dont attack each other. One solution is to find\n * any placement of queens which do not attack each other. Other solution is to find all placements of queen\n * on the board.\n Given an integer n, return all distinct solutions to the n-queens puzzle.\n\nEach solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' '\n both indicate a queen and an empty space respectively.\n\nFor example,\nThere exist two distinct solutions to the 4-queens puzzle:\n[ [\".Q..\", // Solution 1\n \"...Q\",\n \"Q...\",\n \"..Q.\"],\n\n [\"..Q.\", // Solution 2\n \"Q...\",\n \"...Q\",\n \".Q..\"]]\n\n * Time complexity O(n*n)\n * Space complexity O(n*n)\n\n https://github.com/mission-peace/interview/blob/master/src/com/interview/recursion/NQueenProblem.java\n\nBacktracking Algorithm\nThe idea is to place queens one by one in different columns, starting from the leftmost column.\nWhen we place a queen in a column, we check for clashes with already placed queens.\nIn the current column, if we find a row for which there is no clash,\nwe mark this row and column as part of the solution.\nIf we do not find such a row due to clashes then we backtrack and return false.\n\n1) Start in the leftmost column\n2) If all queens are placed\n return true\n3) Try all rows in the current column. Do following for every tried row.\n a) If the queen can be placed safely in this row then mark this [row,\n column] as part of the solution and recursively check if placing\n queen here leads to a solution.\n b) If placing queen in [row, column] leads to a solution then return\n true.\n c) If placing queen doesn't lead to a solution then umark this [row,\n column] (Backtrack) and go to step (a) to try other rows.\n3) If all rows have been tried and nothing worked, return false to trigger\n backtracking.\n\n'''\n\n\nimport numpy as np\nimport time\n\nM= np.zeros( ( 5 , 5 ), dtype=int)\n# Here we place two queens\nM[1][1] = 1\nM[3][4] = 1\nprint(M)\n\ndef get_free_squares(M ) :\n ''' \u00a9 Made by Bogdan Trif @ 2017-09-12\n :Description: In the N Queens problem get all the occupied squares as 1 ones\n and AVAILABLE squares as zeros.\n\n :param M: Matrix to analyze\n :return: grid 2D, all the unoccupied squares as zeros, occupied squares as ones '''\n l = len(M)\n N = np.zeros( (l, l) , dtype=int )\n # print('N :',N)\n # O = np.where(M ==1)\n for i in range(len(N)):\n for j in range(len(N[i])):\n if M[i][j] == 1 :\n # print(i,j)\n I = ( i, j )\n # row , col = i, j\n\n # Insert corresponding row\n N = np.delete(N, I[0], 0)\n # print('N2 : \\n',N)\n # print( np.ones(( N.shape[0] , 1 ), dtype=int ) )\n N = np.insert(N, I[0], values=np.ones((1, l)) , axis=0 )\n # print ('N3 ROW insertion : \\n', N )\n\n # Insert corresponding column\n N = np.delete(N, I[1], axis=1)\n # print('N4 : \\n',N)\n # print( np.ones((1, N.shape[1] ), dtype=int ) )\n N = np.insert(N, I[1], values=np.ones(( 1, l)) , axis=1 )\n # print ('N5 COLUMN insertion : \\n', N )\n\n row , col = I\n # print(' Chosen position : row, col = ', row, col)\n # Diagonal I\n d1 = row - col\n if d1 < 0 :\n row1 = 0\n col1 = abs(d1) + row1\n if d1 > 0 :\n col1 = 0\n row1 = col1 + d1\n if d1 == 0 :\n row1 = 0\n col1 = 0\n\n # print('\\nrow1, col1 = ', row1, col1 , ' d1 = ', d1)\n while col1 < l and row1 < l :\n # print( N[row1][col1] , ' row1, col1 = ',row1, col1 )\n N[row1][col1] = 1\n col1+=1\n row1+=1\n # print('N6 : after diagonal 1 : \\n', N )\n\n # Diagonal II\n d2 = (row + col)\n if row + col >= l :\n col2 = l-1\n row2 = d2 - col2\n if row + col < l :\n row2 = 0\n col2 = d2 - row2\n if row + col == l-1 :\n row2 = 0\n col2 = l-1\n\n # print('\\nrow2, col2 = ', row2, col2 , ' d2 = ', d2)\n while col2 >= 0 and row2 < l :\n # print( N[row2][col2] , ' row2, col2 = ',row2, col2 )\n N[row2][col2] = 1\n col2-=1\n row2+=1\n # print('N6 : after diagonal 2 : \\n', N )\n\n return N\n\ndef is_row_free(M, row) :\n '''Uses the function get_free_squares(M) to find available spots\n\n :param M: matrix, grid 2D\n :param row: the row we are investigating\n :return: boolean, True or False '''\n\n N = get_free_squares(M)\n if sum(N[row]) == len(N[row]) :\n return False\n return True\n\n# def next_free_pos(M, pos) :\n# ''' :Description: returns the next available position in the same row\n#\n# :param M:\n# :param row:\n# :param pos:\n# :return:\n# '''\n# row = pos[0]\n# if is_row_free(M, row) :\n# for i in range(len(M[row])):\n\n\n\nprint(' get_free_squares : \\n' , get_free_squares(M) )\n\n\n# print('is_row_free : \\t', is_row_free(M, 4) )\n\n\n# def solveQueens(M):\n# pos = (0 , 0)\n\n\n################################ BACKTRACKING ALGORITHM #################\nprint('\\n-------------------BACKTRACKING ALGORITHM ----------------------- ')\nt1 = time.time()\n\n\ndim = 18\nM= np.zeros( ( dim , dim ), dtype=int)\n\ndef print_board(board):\n for i in range(len(M)):\n print(M[i])\n\nprint_board(M)\n\n# An utility function to check if a queen can be placed on board[row][col]. Note that this\n# function is called when \"col\" queens are already placed in columns from 0 to col -1.\n# So we need to check only left side for attacking queens\n\ndef is_location_safe(board, row, col):\n # Check row\n if sum(board[row]) > 0 :\n return False\n\n # Check column\n if sum(M[ : , col ] ) > 0 :\n return False\n\n # Check diagonal 1\n if sum( M.diagonal(col-row)) > 0 :\n return False\n\n # Check diagonal 2 -> M[::-1] is the transpose matrix\n if sum( M[::-1].diagonal(row+col-len(board)+1)) > 0 :\n return False\n\n return True\n\ndef find_empty_row(board, pos ):\n\n for row in range(len(board)):\n if sum(board[row]) == 0:\n pos[0], pos[1] = row, 0\n return True\n return False\n\n\ndef solve_Queens( M ):\n pos = [0,0]\n # If all queens are placed return true\n if not find_empty_row(M, pos):\n return True\n\n # this takes the row, col=0 from the find_empty_row function, col remains unchanged !\n row, col = pos\n\n # this search in row a free column\n for col in range(len(M[row])) :\n if is_location_safe(M, row, col):\n M[row][col] = 1\n\n if solve_Queens(M):\n return True\n\n # Backtracking\n M[row][col] = 0\n\n return False\n\n\nN = solve_Queens(M) # VICTORY . IT works !!!!! I made it @ 2017-10-27, 16:51\nprint('\\n')\nprint_board(M)\n\n\nt2 = time.time()\nprint('\\nCompleted in :', round((t2-t1),6), 's\\n\\n')\n\n\n\nprint('\\n---------------------- BACKTRACKING - METHOD 2, 5x faster ------------------------------- ')\nt1 = time.time()\n\n# Python program to solve N Queen\n# Problem using backtracking\n\n\nN = 18\n\ndef printSolution(board):\n for i in range(len(board)):\n print( board[i])\n\n\n\n# A utility function to check if a queen can\n# be placed on board[row][col]. Note that this\n# function is called when \"col\" queens are\n# already placed in columns from 0 to col -1.\n# So we need to check only left side for\n# attacking queens\ndef isSafe(board, row, col):\n\n # Check this row on left side\n for i in range(col):\n if board[row][i] == 1:\n return False\n\n # Check upper diagonal on left side\n for i,j in zip(range(row,-1,-1), range(col,-1,-1)):\n if board[i][j] == 1:\n return False\n\n # Check lower diagonal on left side\n for i,j in zip(range(row,N,1), range(col,-1,-1)):\n if board[i][j] == 1:\n return False\n\n return True\n\ndef solveNQUtil(board, col):\n # base case: If all queens are placed\n # then return true\n if col >= N:\n return True\n\n # Consider this column and try placing\n # this queen in all rows one by one\n for i in range(N):\n\n if isSafe(board, i, col):\n # Place this queen in board[i][col]\n board[i][col] = 1\n\n # recur to place rest of the queens\n if solveNQUtil(board, col+1) == True:\n return True\n\n # If placing queen in board[i][col\n # doesn't lead to a solution, then\n # queen from board[i][col]\n board[i][col] = 0\n\n # if queen can not be place in any row in\n # this colum col then return false\n return False\n\n# This function solves the N Queen problem using\n# Backtracking. It mainly uses solveNQUtil() to\n# solve the problem. It returns false if queens\n# cannot be placed, otherwise return true and\n# placement of queens in the form of 1s.\n# note that there may be more than one\n# solutions, this function prints one of the\n# feasible solutions.\ndef solveNQ():\n board = [[0]*N for i in range(N) ]\n\n if solveNQUtil(board, 0) == False:\n print (\"Solution does not exist\")\n return False\n\n printSolution(board)\n return True\n\n# driver program to test above function\nsolveNQ()\n\n\nt2 = time.time()\nprint('\\nCompleted in :', round((t2-t1),6), 's\\n\\n')"} {"blob_id": "78c5ddb44b3aac0d56622ba951ee9234a2051db5", "repo_name": "savourylie/coding_tests", "path": "/microsoft/num_island_in_matrix.py", "length_bytes": 2846, "score": 3.71875, "int_score": 4, "content": "# Consider a matrix of 0s and 1s.\n# If two 1s are adjacent to each other, they are considered connected.\n# Find out the number of connected components there are in the matrix\n\ndef num_island_in_matrix(m):\n\t\"\"\"\n\t(2D-list) -> int\n\t\"\"\"\n\tnum_row = len(m)\n\tnum_col = len(m[0])\n\n\tisland_list = []\n\n\t# Identify islands and put in a list\n\tfor x in range(num_row):\n\t\tfor y in range(num_col):\n\t\t\tif m[x][y] == 1:\n\t\t\t\tisland_list.append([(x, y), None])\n\n\t# Assign parent index to each island, defaulting their own index\n\t# Create a matrix_to_list_map\n\tmatrix_to_list_map = {}\n\n\tfor i, x in enumerate(island_list):\n\t\tx[1] = i\n\t\tmatrix_to_list_map[x[0]] = x[1]\n\n\t# Sanity check\n\tcounter = 0\n\tfor x in range(num_row):\n\t\tfor y in range(num_col):\n\t\t\tif m[x][y] == 1:\n\t\t\t\tcounter += 1\n\n\tassert counter == len(island_list)\n\tprint(\"Sanity check passed.\")\n\n\tvisited_matrix = [[False] * num_col for _ in range(num_row)]\n\n\tfor x in range(num_row):\n\t\tfor y in range(num_col):\n\t\t\tvisited_matrix[x][y] = True\n\n\t\t\tx_coords = [x, x - 1, x + 1]\n\t\t\ty_coords = [y, y - 1, y + 1]\n\n\t\t\tx_coords = [x for x in x_coords if num_row > x >= 0]\n\t\t\ty_coords = [y for y in y_coords if num_col > y >= 0]\n\n\t\t\tvicinity_coords = [(x, y) for x in x_coords for y in y_coords]\n\t\t\tvicinity_coords.remove((x, y))\n\t\t\t\n\t\t\tif m[x][y] == 1:\n\t\t\t\tfor coord in vicinity_coords:\n\t\t\t\t\tif coord in matrix_to_list_map:\n\t\t\t\t\t\town_index = matrix_to_list_map[(x, y)]\n\t\t\t\t\t\tnear_index = matrix_to_list_map[coord]\n\t\t\t\t\t\t# print(island_list[matrix_to_list_map[(x, y)]])\n\t\t\t\t\t\tif m[coord[0]][coord[1]] and m[coord[0]][coord[1]] == 1:\n\t\t\t\t\t\t\tif visited_matrix[coord[0]][coord[1]] == False:\n\t\t\t\t\t\t\t\tisland_list[near_index][1] = island_list[own_index][1]\n\t\t\t\t\t\t\t\tvisited_matrix[coord[0]][coord[1]] = True\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tisland_list[own_index][1] = island_list[near_index][1]\n\t\t\t\t\t\t\t\tvisited_matrix[coord[0]][coord[1]] = True\n\n\tprint(island_list)\n\t\n\tfor i, x in enumerate(island_list):\n\t\twhile island_list[x[1]][1] != island_list.index(island_list[x[1]]):\n\t\t\tx[1] = island_list[x[1]][1]\n\n\tprint(island_list)\n\n\tindex_set = set([x[1] for x in island_list])\n\n\treturn len(index_set)\n\n\ndef test_num_island_in_matrix():\n\tm1 = [[0, 0, 1, 1, 1], [0, 1, 1, 0, 0], [1, 0, 0, 0, 1]]\n\tm2 = [[1, 0, 1, 0, 1], [0, 0, 0, 1, 1], [1, 0, 0, 0, 0]]\n\tm3 = [[1, 1, 0, 0, 1, 1], [1, 0, 1, 0, 1, 0], [0, 0, 0, 0, 0, 1], [1, 1, 1, 0, 1, 0], [0, 1, 0, 0, 0, 1]]\n\tm4 = [[1, 1, 0, 1, 0], [0, 0, 0, 1, 0], [1, 1, 0, 0, 0], [0, 0, 0, 0, 1], [1, 0, 1, 0, 0]]\n\tm5 = [[1, 0, 1, 0, 0, 0], [0, 1, 0, 1, 1, 0], [0, 0, 0, 0, 0, 1], [1, 0, 0, 1, 1, 0], [1, 1, 1, 0, 0, 0]]\n\n\tassert num_island_in_matrix(m1) == 2\n\tassert num_island_in_matrix(m2) == 3\n\tassert num_island_in_matrix(m3) == 3\n\tassert num_island_in_matrix(m4) == 6\n\tassert num_island_in_matrix(m5) == 1\n\n\tprint(\"All tests passed.\")\n\nif __name__ == '__main__':\n\ttest_num_island_in_matrix()"} {"blob_id": "4b052c08f9372d64e99ea6d07a50d9135f7a50f5", "repo_name": "nail82/final_exam", "path": "/batch_perceptron.py", "length_bytes": 3634, "score": 3.8125, "int_score": 4, "content": "\"\"\"\nTed Satcher\nCS 640\nFall 2012\n\nFinal Exam\n\nFile: batch_perceptron.py\n\nThis modulue implements the batch perceptron algorithm.\n\"\"\"\nfrom __future__ import print_function\nimport numpy as np\nimport itertools as it\nimport make_data as md\nimport matplotlib.pyplot as plt\n\ndef separate(data):\n \"\"\"Use the batch perceptron algorithm to calculate\n the decision function weight vector for a two class problem.\n\n Args:\n data: A list of labeled sample vectors. The zeroth element\n of each sample must identify the category this sample\n belongs to.\n\n Returns:\n A tuple. The first element is the number of\n iterations to find the separating weight vector\n and the second element is the weight vector\n itself.\n \"\"\"\n ldata = data.copy()\n aug_data = np.matrix(map(augment_sample, ldata))\n n = aug_data.shape[0]\n wt_dimensions = aug_data.shape[1]\n\n # Intial weigth vector\n w = np.matrix(np.zeros(wt_dimensions)).T\n total_count = 0\n # Learning rate\n eta = 1\n # Main loop for the batch perceptron\n while True:\n total_count += 1\n w_delta = np.matrix(np.zeros(wt_dimensions)).T\n # Check the classification of each sample\n mis_class_count = 0\n for i in range(0,len(aug_data)):\n yk = aug_data[i].T\n v = (w.T*yk)[0,0]\n if v <= 0:\n # This sample is mis-classified, so add it to\n # the weight update vector.\n mis_class_count += 1\n w_delta += yk\n # Update the weight vector\n w = w + (eta*w_delta)\n if mis_class_count == 0:\n break\n return (total_count, w)\n\n\ndef augment_sample(y):\n \"\"\"Augment a pattern vector and negate if the\n pattern is a member of omega2\"\"\"\n rtn = np.asarray(y).squeeze()\n if rtn[0] > 1:\n rtn[0] = 1\n rtn = -rtn\n return rtn\n\ndef plot_solution(w, data, mytitle, catlabel):\n \"\"\"\n Scatter plot data and the separation line described\n by the weight vector w.\n\n Args:\n w: The weight vector describing a solution line.\n data: A three dimensional data matrix. The first\n element of each row is assumed to be the category\n assignment of the sample.\n mytitle: Plot title\n catlabel: A dictionary with category names.\n\n Note: This function assumes two category data.\n \"\"\"\n f = get_solution_func(np.array(w))\n adata = np.array(data)\n\n minx = min(adata[0:,1])\n maxx = max(adata[0:,1])\n rng = maxx-minx\n x = np.array((minx-rng, maxx+rng))\n y = np.array(list(it.imap(f, x)))\n mincat = min(adata[0:,0])\n maxcat = max(adata[0:,0])\n colors = dict(mincat=\"blue\", maxcat=\"red\")\n # Find the data for each category\n i = (adata[0:,0] == mincat)\n j = (adata[0:,0] == maxcat)\n mincat_x = adata[i,1]\n mincat_y = adata[i,2]\n maxcat_x = adata[j,1]\n maxcat_y = adata[j,2]\n\n # Plot the solution line\n plt.plot(x,y, color=\"black\", label=\"Decision Boundary\")\n plt.scatter(mincat_x, mincat_y, color=colors['mincat'],\n label=catlabel['mincat'])\n plt.scatter(maxcat_x, maxcat_y, color=colors['maxcat'],\n label=catlabel['maxcat'])\n plt.legend()\n plt.title(mytitle, fontsize=18)\n plt.xlabel(\"X1\", fontsize=16)\n plt.ylabel(\"X2\", fontsize=16)\n plt.show()\n\ndef get_solution_func(w):\n \"\"\"\n Resolve a 2d weight vector into a plottable\n function in the form of y = mx + b\n \"\"\"\n if w[2] == 0:\n raise Exception('Error: slope is infinte')\n return (lambda x1: (-w[0]/w[2]) + (-w[1]/w[2])*x1)\n"} {"blob_id": "deb1a80c8b8cb1224b377b25a2d6169b4aaa68d4", "repo_name": "TotesReptilian/CelestialShell", "path": "/globe.py", "length_bytes": 2762, "score": 3.6875, "int_score": 4, "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport re\nimport math\n\nfrom util.angle import Angle, Degree, Latlon, HourAngle\nfrom util.location import StarLocation, SphereLocation\nfrom util.vector3 import Vector3\n\nclass Star(StarLocation):\n def __init__(self, ra, dec):\n \"\"\"\n :param ra: Latlon Right Ascension\n :param dec: HourAngle Declination\n \"\"\"\n StarLocation.__init__(self, ra, dec)\n\n def azimuth(self, location, gmst):\n \"\"\"\n Calculates azimuth angle of this star from given location\n\n :param location: Location\n :param gmst: HourAngle greenwich sidereal time\n\n :return: azimuth Angle\n \"\"\"\n lha = self.local_hour_angle(location, gmst)\n\n den = math.sin(location.lat) * math.cos(lha) - math.tan(self.dec)*math.cos(location.lat)\n sin_lha = math.sin(lha)\n\n # prevent divide-by-zero error\n if den == 0:\n if sin_lha == 0:\n return Angle(0)\n elif sin_lha > 0:\n return Angle(math.pi*1.5)\n else:\n return Angle(math.pi*0.5)\n\n atan = math.atan(sin_lha / den)\n\n # atan range is from -90 to 90. Must manually detect other quandrants from sign of denomenator\n if den > 0:\n atan += math.pi\n\n # enforce 0 - 360 range.\n if atan < 0:\n atan += math.pi*2.0\n\n return Angle(atan)\n\n def altitude(self, location, gmst):\n \"\"\"\n Calculates altitude angle of this star from given location\n\n :param location: Location\n :param gmst: greenwich sidereal time\n\n :return: altitude Angle\n \"\"\"\n lha = self.local_hour_angle(location, gmst)\n return Angle(math.asin(math.sin(location.lat)*math.sin(self.dec) + math.cos(location.lat)*math.cos(self.dec)*math.cos(lha)))\n\n def local_hour_angle(self, location, gmst):\n \"\"\"\n Calculates local hour angle of this star from given location\n\n :param location: Location\n :param gmst: greenwich sidereal time\n\n :return: local hour angle\n \"\"\"\n\n return Angle(gmst.rad() + location.lon.rad() - self.ra.rad())\n\n def greenwich_hour_angle(self, location, gmst):\n \"\"\"\n Calculates greenwich hour angle of this star from given location\n\n :param location: Location\n :param gmst: greenwich sidereal time\n\n :return: local hour angle\n \"\"\"\n return Angle(gmst.rad() - self.ra)\n\n def local_sidereal_time(self, location, gmst):\n return Angle(gmst.rad() + location.lon.rad())\n\n\n def print_azi_alt(self, loc, gmst):\n print(\"Azi: \"+self.azimuth(loc, gmst).deg_min_sec())\n print(\"Alt: \"+self.altitude(loc, gmst).deg_min_sec())\n\n\n"} {"blob_id": "f9491a59f8e091a0eb4cd8ce546d92df8b99830a", "repo_name": "yalcinkilic/Euler_Project", "path": "/Problem0003.py", "length_bytes": 337, "score": 3.515625, "int_score": 4, "content": "import math_library\n\"\"\"\nThis program solves 3rd question of Euler Project\n\"\"\"\n\ndivisor_list = math_library.factorize_integer(600851475143)\nfor i in range(len(divisor_list) - 1 , -1 , -1):\n if math_library.is_prime(divisor_list[i]) == True:\n print(\"The largest prime divisor of 600851475143 is\" , divisor_list[i])\n break\n"} {"blob_id": "e0c5fc3a55327871f16b450def694a6dd97a8e5f", "repo_name": "JKinsler/Sorting_Algorithms_Test", "path": "/merge_sort2.py", "length_bytes": 1353, "score": 4.15625, "int_score": 4, "content": "\"\"\"\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\nMerge sort\nSorting array practice\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\nSort an unsorted array in O(nlogn) time complexity\n\n\"\"\"\n\ndef merge_sort(arr):\n \"\"\"\n decompose the array into arrays of length 1\n recombine the arrays in a sorted manner, using the helper function\n \n Developer notes: \n This solution is not ideal because it uses 'pop(0)' in the helper function, \n which adds O(n) run time.\n \"\"\"\n\n if len(arr) < 2:\n print(f'returning arr: {arr}')\n return arr\n\n mid = len(arr)//2\n \n lst1 = merge_sort(arr[:mid])\n lst2 = merge_sort(arr[mid:])\n\n return merge(lst1, lst2)\n\n\ndef merge(lst1, lst2):\n \"\"\"combine two sorted arrays into a single sorted array\"\"\"\n\n res = []\n\n # add the lowest value to res\n while len(lst1) > 0 or len(lst2) > 0:\n \n # add the value of the remaining list if one list is empty\n if lst1 == []:\n res.append(lst2.pop(0))\n\n elif lst2 == []:\n res.append(lst1.pop(0))\n\n # append the lesser value to res\n elif lst1[0] < lst2[0]:\n res.append(lst1.pop(0))\n \n else:\n res.append(lst2.pop(0))\n \n return res\n\n\nif __name__ == '__main__':\n\n print(merge_sort([3, 1, 4]))"} {"blob_id": "da890184d2f668dd80efa0119a68f13163e80425", "repo_name": "Wang-Yann/LeetCodeMe", "path": "/python/_0001_0500/0280_wiggle-sort.py", "length_bytes": 1776, "score": 3.75, "int_score": 4, "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Author : Rock Wayne \n# @Created : 2020-07-27 11:14:37\n# @Last Modified : 2020-07-27 11:14:37\n# @Mail : lostlorder@gmail.com\n# @Version : alpha-1.0\n\n\"\"\"\n# \u7ed9\u4f60\u4e00\u4e2a\u65e0\u5e8f\u7684\u6570\u7ec4 nums, \u5c06\u8be5\u6570\u5b57 \u539f\u5730 \u91cd\u6392\u540e\u4f7f\u5f97 nums[0] <= nums[1] >= nums[2] <= nums[3]...\u3002 \n# \n# \u793a\u4f8b: \n# \n# \u8f93\u5165: nums = [3,5,2,1,6,4]\n# \u8f93\u51fa: \u4e00\u4e2a\u53ef\u80fd\u7684\u89e3\u7b54\u662f [3,5,1,6,2,4] \n# Related Topics \u6392\u5e8f \u6570\u7ec4 \n# \ud83d\udc4d 23 \ud83d\udc4e 0\n\n\"\"\"\n\nfrom typing import List\n\nimport pytest\n\n\n# leetcode submit region begin(Prohibit modification and deletion)\nclass Solution:\n def wiggleSort(self, nums: List[int]) -> None:\n \"\"\"\n Do not return anything, modify nums in-place instead.\n \"\"\"\n\n for i in range(len(nums) - 1):\n if (i % 2 == 0 and nums[i] > nums[i + 1]) or (\n i % 2 == 1 and nums[i] < nums[i + 1]\n ):\n nums[i], nums[i + 1] = nums[i + 1], nums[i]\n\n\n# leetcode submit region end(Prohibit modification and deletion)\nclass Solution1:\n def wiggleSort(self, nums: List[int]) -> None:\n \"\"\"\n Do not return anything, modify nums in-place instead.\n \"\"\"\n nums.sort()\n med = (len(nums) - 1) // 2\n nums[::2], nums[1::2] = nums[med::-1], nums[:med:-1]\n\n\n@pytest.mark.parametrize(\"nums,expected\", [\n ([3, 5, 2, 1, 6, 4], [3, 5, 1, 6, 2, 4]),\n])\ndef test_solutions(nums, expected):\n Solution().wiggleSort(nums)\n i = 1\n while i < len(nums) - 1:\n if i % 2 == 0:\n assert nums[i - 1] > nums[i] < nums[i + 1]\n else:\n assert nums[i - 1] < nums[i] > nums[i + 1]\n i += 1\n\n\nif __name__ == '__main__':\n pytest.main([\"-q\", \"--color=yes\", \"--capture=no\", __file__])\n"} {"blob_id": "d504c26783f51d7ebd7e179fda8b58d9ae25e090", "repo_name": "skydragonceo/Game-of-Life", "path": "/GameOfLife.py", "length_bytes": 43010, "score": 3.59375, "int_score": 4, "content": "from Tkinter import *\nimport os\nimport urllib\nimport random\n\n#Images of Game of Life owned by Hasbro\n#Images retrieved from http://blog.nicoledelsenno.com/?p=212\n#http://recruiterpoet.files.wordpress.com/2011/07/life2.gif\n#Images of Mario and Koopa ownership of Nintendo\n#Images retrieved from http://www.spriters-resource.com\n\n##From 15-112\n#We use both to store the points created in GameOfLifePoints in the function\n#points.txt\ndef readFile(filename, mode=\"rt\"):\n # rt stands for \"read text\"\n fin = contents = None\n try:\n fin = open(filename, mode)\n contents = fin.read()\n finally:\n if (fin != None): fin.close()\n return contents\n\ndef writeFile(filename, contents, mode=\"wt\"):\n # wt stands for \"write text\"\n fout = None\n try:\n fout = open(filename, mode)\n fout.write(contents)\n finally:\n if (fout != None): fout.close()\n return True\n\ndef sizeChanged(event):\n canvas = event.widget.canvas\n canvas.width = event.width - 4\n canvas.height = event.height - 4\n redrawAll(canvas)\n#From 15 112 ^\n \nclass GameOfLifePoints(object): #purpose is to refer to every space on the\n #game of life board to be represented by a point\n\n def mousePressed(self, event): \n canvas = self.canvas\n canvas.pressedAt.append((event.x, event.y)) # append the (x,y) tuple\n print \"Our locations:\", canvas.pressedAt\n canvas.storedPoints = writeFile( \"\\\\GameOfLife\\\\points.txt\", repr(\n canvas.pressedAt)) #every space on the board is from the coordinates\n #represented in canvas.PressedAt\n canvas.newLocations = eval(readFile( \"\\\\GameOfLife\\\\points.txt\"))\n print canvas.newLocations\n\n def keyPressed(self, event):\n canvas = self.canvas\n if (event.char == \"d\"): #deleting the last point in the board(undo)\n if len(canvas.pressedAt) > 0:\n canvas.pressedAt = canvas.pressedAt[0:-1]\n## class Cells:\n## def init(self):\n## for i in canvas.data.newLocations:\n## print \"this location\", i \n \n def timerFired(self):\n canvas = self.canvas\n delay = 250 # milliseconds\n\n def redrawAll(self):\n canvas = self.canvas\n thirdImage = canvas.thirdImage\n canvas.delete(ALL)\n r = canvas.r\n canvas.create_image(canvas.width/2, canvas.height/2,\n image = thirdImage) #displays the board\n for (x,y) in canvas.pressedAt: #each point represented by a black point\n canvas.create_oval(x-r, y-r, x+r, y+r, fill=\"black\")\n\n def init(self):\n canvas = self.canvas\n canvas.pressedAt = []\n canvas.index = 0\n # from 112 notes\n image = PhotoImage(file=\"GameOfLifeBoardFinal.gif\")\n canvas.image = image #printing the board out to play\n canvas.width = canvas.winfo_reqwidth()-4\n canvas.height = canvas.winfo_reqheight()-4\n thirdImage = image.subsample(3,3) #resizing image to fit screen\n canvas.thirdImage = thirdImage\n # from 112 notes ^\n canvas.r = 3 # 3 pixel radius\n\n # Call app.run(width,height) to get your app started\n def run(self, width=1200, height=850):\n # create the root and the canvas\n root = Tk()\n self.width = width\n self.height = height\n self.canvas = Canvas(root, width=width, height=height)\n self.canvas.pack(fill=BOTH, expand=YES)#from 112 \n # set up events\n def redrawAllWrapper():\n self.canvas.delete(ALL)\n self.redrawAll()\n def mousePressedWrapper(event):\n self.mousePressed(event)\n redrawAllWrapper()\n def keyPressedWrapper(event):\n self.keyPressed(event)\n redrawAllWrapper()\n root.bind(\"\", mousePressedWrapper)\n root.bind(\"\", keyPressedWrapper)\n # set up timerFired events\n self.timerFiredDelay = 250 # milliseconds\n def timerFiredWrapper():\n self.timerFired()\n redrawAllWrapper()\n # pause, then call timerFired again\n self.canvas.after(self.timerFiredDelay, timerFiredWrapper)\n # init and get timerFired running\n self.init()\n timerFiredWrapper()\n # and launch the app\n root.mainloop() # This call BLOCKS (so your program waits until\n #you close the window!)\n\nclass Player(object): #all the info needed for the players\n def __init__(self):\n self.font = (\"Helvetica\", 24, \"bold\")\n (self.positionX,self.positionY) = (200,200) #for stats\n self.lifeMsg = \"Hi! Welcome to the Game of Life!\"\n self.displayStatus = False #you can control if or not to display status\n self.indexStatus = False #of player\n self.newLocations = eval(readFile( \"\\\\GameOfLife\\\\points.txt\"))\n self.cells = Cell() #everything that happens when you pass/land on a\n #point on the board is caused by the list caused in the cells (sub)class\n (self.Money, self.Babies, self.LifeCard, self.LifeEvent) = (Money(),\n Babies(),LifeCard(),LifeEvent()) #specific cells have their own class\n (self.DoSomething, self.OtherPoint) = (DoSomething(), OtherPoint())\n self.otherPos = self.cells.otherPos\n self.playerMoney = self.cells.playerMoney #money\n self.marriedStatus = self.LifeEvent.marriedStatus\n self.homeStatus = self.LifeEvent.homeStatus\n self.salary = self.Money.salary #salary\n self.playerBabyCount = self.Babies.playerBabyCount #children\n self.occupation = self.LifeEvent.occupation\n self.occupations = self.LifeEvent.occupations\n self.degreeStatus = self.LifeEvent.degreeStatus\n self.message = \"Moving 0 Places\"\n\nclass GameOfLifeData(GameOfLifePoints):\n #What creates the players on the board and allows you to move around\n def init(self): #holds all the stats of the player, the marriageStatus,\n #whether the player has a home, how many babies does the player have\n #the amount money the player has\n super(GameOfLifeData, self).init()\n canvas = self.canvas\n self.font = (\"Helvetica\", 24, \"bold\")\n (self.positionX,self.positionY) = (200,200)\n self.lifeMsg = \"Welcome to the Game of Life!\"\n self.displayStatus = False\n self.indexStatus = False\n self.cells = Cell() #everything that happens when you pass/land on a\n #point on the board is caused by the list caused in the cells class\n #and it's subclasses\n (self.Money, self.Babies, self.LifeCard, self.LifeEvent) = (Money(),\n Babies(),LifeCard(),LifeEvent())\n (self.DoSomething, self.OtherPoint) = (DoSomething(), OtherPoint())\n self.players()\n\n def players(self):#deals with how many players in the game\n self.playerOne = Player() #we have two players right now\n self.playerTwo = Player()\n self.players = [self.playerOne, self.playerTwo] # a list of players\n self.currentPlayer = 0 #and the index for whose turn and the other...\n self.otherPlayer = 1 #player\n self.playerTwo.positionX = self.width - self.playerOne.positionX\n self.player = self.players[self.currentPlayer]\n self.isGameOver = False\n self.startScreen = True\n self.instruction = False\n \n def keyPressed(self, event):\n if event.char == \"h\": self.instruction = True\n if event.char == \"j\": self.instruction = False\n if self.startScreen == False:\n if event.char == \"d\":#press d to make your move!\n self.makeMove()#make Move evaluates the functions stored in the\n #list made by cells for when you land/pass a space\n if event.char == \"a\": #show status of player\n self.displayStatus = True\n if event.char == \"s\": #turn ofus stat\n self.displayStatus = False\n if event.char == \"i\": #show index of player\n self.indexStatus = True\n if event.char == \"o\": #turn of index\n self.indexStatus = False\n if event.char == \"x\": #call automatic game over\n self.gameOver(self.players[self.currentPlayer],\n self.players[self.otherPlayer])\n else:\n if event.char == \"s\":\n self.startScreen = False\n \n def redrawAll(self):\n (canvas,cells) = (self.canvas,self.cells)\n if self.startScreen == True:self.startPage()\n elif self.instruction == True: self.instructions()\n else:\n super(GameOfLifeData, self).redrawAll()\n self.viewPlayer(self.playerOne,imagePlayer = PhotoImage(\n file = \"MarioStill.gif\")) #player one's avatar\n self.viewPlayer(self.playerTwo,imagePlayer = PhotoImage(\n file = \"koopaTest.gif\")) #player two's avatar\n if self.displayStatus == True: #displays status of player\n self.status(self.playerOne)\n self.status(self.playerTwo)\n if self.indexStatus == True: #displays index of player\n self.index(self.playerOne)\n self.index(self.playerTwo)\n self.displayLifeStatus(self.lifeMsg) #for misc. spots, this is what\n #the text on that cell says\n self.playerTurn() #display who's turn it is\n if self.isGameOver == True:\n self.winner() #displays who won\n\n def startPage(self):\n self.startImage()\n self.canvas.create_text(self.width/2, self.height/2,\n text = \"Welcome to the Game of Life! Press s to start!\", font =\n self.font, fill = \"black\")\n self.canvas.create_text(self.width/2, self.height/2 + 50,\n text = \"Press h during game to see instructions\", font =\n self.font, fill = \"black\")\n\n def startImage(self):\n canvas = self.canvas\n image = canvas.image\n canvas.gameOfLifeImage = PhotoImage(file = \"GameOflife2.gif\")\n self.canvas.create_image(self.width/2,self.height/2, image =\n canvas.gameOfLifeImage)\n \n \n def instructions(self): #how to play!\n self.instructionImage() #image for instructions\n self.instructionSet() #text for instructions\n \n\n def instructionSet(self):\n self.canvas.create_text(self.width/2, self.height/2 - 150,\n text = \"Hello!\" , font = self.font, fill = \"black\")\n self.canvas.create_text(self.width/2, self.height/2 - 100,\n text = \"press d to make your move!\",\n font = self.font, fill = \"black\") \n self.canvas.create_text(self.width/2, self.height/2 - 50,\n text = \"Press i to show index, o to turn off!\",\n font = self.font, fill = \"black\")\n self.canvas.create_text(self.width/2, self.height/2,\n text = \"Press a to show status of player, s to turn off!\" ,\n font = self.font, fill = \"black\")\n self.canvas.create_text(self.width/2, self.height/2 + 50,\n text = \"Get to the end of board with the most money!\",\n font = self.font, fill = \"black\")\n self.canvas.create_text(self.width/2, self.height/2 + 100,\n text = \"Check shell to see when you need to make a decision!\",\n font = self.font, fill = \"black\")\n self.canvas.create_text(self.width/2, self.height/2 + 150,\n text = \"Good Luck! press j to resume\",\n font = self.font, fill = \"black\")\n\n def instructionImage(self):\n self.startImage()\n \n def viewPlayer(self,currentPlayer, imagePlayer): #display player X avatar\n #at their index\n canvas = self.canvas\n image = canvas.image\n cells = currentPlayer.cells\n currentPlayer.imagePlayer = imagePlayer\n #takes the initial position from points.txt to print out player's piece\n (currentPlayer.playerPositionX, currentPlayer.playerPositionY\n ) = currentPlayer.newLocations[cells.index]\n self.canvas.create_image(currentPlayer.playerPositionX,\n currentPlayer.playerPositionY, image = currentPlayer.imagePlayer)\n\n def status(self, player): #displaying status of the player(s)\n self.canvas.create_text(player.positionX, player.positionY,\n text = player.message , font = self.font, fill = \"white\")\n self.canvas.create_text(player.positionX, player.positionY + 50,\n text = \"Player Money = %s\" %(str(player.Money.playerMoney)) ,\n font = self.font, fill = \"white\") \n self.canvas.create_text(player.positionX, player.positionY + 100,\n text = \"Marriage Status = %s\" %(str(player.LifeEvent.marriedStatus)),\n font = self.font, fill = \"white\")\n self.canvas.create_text(player.positionX, player.positionY + 150,\n text = \"Home = %s\" %(str(player.LifeEvent.houseChoice)) ,\n font = self.font, fill = \"white\")\n self.canvas.create_text(player.positionX, player.positionY + 200,\n text = \"Career = %s\" %(str(player.LifeEvent.occupation)),\n font = self.font, fill = \"white\")\n self.canvas.create_text(player.positionX, player.positionY + 250,\n text = \"Children = %s\" %(str(player.Babies.playerBabyCount)),\n font = self.font, fill = \"white\")\n self.canvas.create_text(player.positionX, player.positionY + 300,\n text = \"Salary = %s\" %(str(player.LifeEvent.salary)),\n font = self.font, fill = \"white\")\n \n #rework of 112 boardGame\n def switchCurrentPlayer(self): #switches whose turn it is\n if self.currentPlayer < (len(self.players) - 1):\n self.currentPlayer += 1\n self.otherPlayer -= 1\n else: (self.currentPlayer,self.otherPlayer) = (0,1)\n #rework of 112 boardGame ^\n\n def playerTurn(self):\n self.canvas.create_text(self.width/2, self.positionY,\n text = \"Player %s turn\" %(str(self.currentPlayer + 1)),\n font = self.font, fill = \"white\")\n\n def index(self, player):\n self.canvas.create_text(player.positionX, player.positionY - 50,\n text = \"player position = %s\" %(str(player.cells.index)),\n font = self.font, fill = \"white\")\n \n def mousePressed(self, event):\n pass\n\n def makeMove(self): #function that deals what happens when it's your turn\n currentPlayer = self.players[self.currentPlayer]\n otherPlayer = self.players[self.otherPlayer]\n currentPlayer.cells.makeList() #makes the list that holds the data\n #of what happens at each point in a string (which is why we eval)\n (cells,othercells) = (currentPlayer.cells,otherPlayer.cells)\n # ^ index of the currentPlayer and other player\n self.randomCounter = random.randint(1, 10) #spin to see how far you\n #move!\n #cells.index += self.randomCounter\n #print currentPlayer.cells.Spaces\n print \"player one money\", self.playerOne.Money.playerMoney\n print \"player two money\", self.playerTwo.Money.playerMoney\n currentPlayer.counter = self.randomCounter\n #randomCounter determines how far player moves\n currentPlayer.message = \"Moving %s Places\" % str(self.randomCounter)\n if self.isGameOver == False:\n self.makeMoveGame(currentPlayer,otherPlayer)\n self.switchCurrentPlayer()\n \n def makeMoveGame(self, currentPlayer,otherPlayer):#while the game isn't over\n (cells,othercells) = (currentPlayer.cells,otherPlayer.cells)\n if currentPlayer.cells.index + self.randomCounter <= (len(\n cells.newLocations) - 1): #no one has hit end of board\n while (currentPlayer.counter > 0):\n self.makeMoveTurn(currentPlayer,otherPlayer)\n #what happens while it's player x's turn\n self.landPoint(currentPlayer) #eval what happens at point you\n #land at\n currentPlayer.Money.playerMoney -= (\n currentPlayer.Babies.playerBabyCount * 5000) #cost for\n #children...\n elif currentPlayer.cells.index + self.randomCounter > (len(\n cells.newLocations) - 1): #one player hit end of board but game\n #goes on\n (cells.index,currentPlayer.counter) = ((len(cells.newLocations)\n - 1),0)\n if otherPlayer.cells.index == (len(cells.newLocations) - 1):\n self.gameOver(currentPlayer,otherPlayer) # both\n #hit end of board so game over\n \n def makeMoveTurn(self, currentPlayer,otherPlayer): #what happens\n #at player x's turn\n (cells,othercells) = (currentPlayer.cells,otherPlayer.cells)\n if len(cells.Spaces[currentPlayer.cells.index][3]) < 2: \n cells.index = cells.Spaces[currentPlayer.cells.index][3][0]\n currentPlayer.counter -= 1 #evaluate at each point\n else: #you've hit a fork in the road! choose your direction!\n self.Options(currentPlayer)\n if currentPlayer.cells.index == 1:\n currentPlayer.LifeEvent.career()\n self.passedPoint(currentPlayer)\n #what happens when you pass a point \n \n def passedPoint(self,currentPlayer):#3 points, when married,job,get a house\n cells = currentPlayer.cells \n #some things happen when you pass a point! Not just\n #when you land ((ex, paydays and stopping points)\n # they either call fn for new home, job, or marriage\n #or function for payday (green spots)\n if cells.index == currentPlayer.LifeEvent.marriedPos: #stop!Married!\n eval(self.LifeEvent.Spaces[currentPlayer.LifeEvent.marriedPos][2])\n cells.index = currentPlayer.LifeEvent.index\n currentPlayer.counter = 0 #you stop at this point\n elif cells.index == currentPlayer.LifeEvent.homePos:#stop!new house!\n self.passedPointHome(currentPlayer)\n elif cells.index == self.LifeEvent.jobPos:\n self.passedPointJob(currentPlayer) #you get a job!\n self.payDay(currentPlayer)\n\n def passedPointHome(self,currentPlayer): #you buy a home!\n cells = currentPlayer.cells \n currentPlayer.LifeEvent.playerMoney = (\n currentPlayer.Money.playerMoney) #set money in lifeEvent\n #where home function is to your money, and then back when evaluating\n #ie calling the function\n eval(self.LifeEvent.Spaces[currentPlayer.LifeEvent.homePos][2])\n currentPlayer.Money.playerMoney = (\n currentPlayer.LifeEvent.playerMoney)\n cells.index = currentPlayer.LifeEvent.index\n currentPlayer.counter = 0 #the player must stop at this spot\n \n def passedPointJob(self, currentPlayer): #new job!\n cells = currentPlayer.cells \n currentPlayer.LifeEvent.playerMoney = currentPlayer.Money.playerMoney\n eval(self.LifeEvent.Spaces[self.LifeEvent.jobPos][2])\n currentPlayer.Money.playerMoney = (\n currentPlayer.LifeEvent.playerMoney)\n cells.index = currentPlayer.LifeEvent.index \n currentPlayer.counter = 0 #the player must stop at this spot\n\n def payDay(self,currentPlayer): #payday spots are in a list for each player\n #so when you land at that point, add to your money your salary (the fn\n #that's being eval, and take that index out of th list \n cells = currentPlayer.cells\n #print currentPlayer.Money.payDaySpots\n if len(currentPlayer.Money.payDaySpots) >= 1:\n if cells.index == min(currentPlayer.Money.payDaySpots):\n eval(cells.Spaces[min(currentPlayer.Money.payDaySpots)][2])\n currentPlayer.Money.payDaySpots = (\n currentPlayer.Money.payDaySpots[1:len(cells.payDaySpots)])\n if (cells.index in [55,88]):\n currentPlayer.Money.payDaySpots = (\n currentPlayer.Money.payDaySpots[1:len(cells.payDaySpots)])\n \n def landPoint(self,currentPlayer): #only happens when you land on this space\n cells = currentPlayer.cells\n #newBaby, lifeCard, taxes, or miscellaneous (otherPos)\n if cells.index in cells.babyPos: eval(cells.Spaces[cells.index][2])\n elif cells.index in cells.lifePos: eval(cells.Spaces[cells.index][2])\n elif cells.index in cells.salTradePos:\n eval(cells.Spaces[cells.index][2])\n elif cells.index in cells.taxPos: eval(cells.Spaces[cells.index][2])\n elif cells.index in cells.newCareerPos:\n eval(cells.Spaces[cells.index][2])\n elif cells.index in cells.otherPos:\n currentPlayer.OtherPoint.index = cells.index\n currentPlayer.OtherPoint.playerMoney = (\n currentPlayer.Money.playerMoney)\n #keeping playerMoney all the same ^\n eval(cells.Spaces[cells.index][2])\n currentPlayer.Money.playerMoney = (\n currentPlayer.OtherPoint.playerMoney)\n if cells.index in cells.gameOfLifeSpaces:\n self.lifeEventStatuses(currentPlayer)\n else: self.lifeMsg = \"Game of Life!\" #default message\n\n def lifeEventStatuses(self,currentPlayer):\n self.lifeEventStatus(currentPlayer) #the text at spot player lands at\n self.moreEventStatus(currentPlayer) #at the said index player lands on\n self.evenMoreEventStatus(currentPlayer)\n self.lastEventStatus(currentPlayer)\n #else: eval(cells.Spaces[cells.index][2])\n\n def lifeEventStatus(self,currentPlayer): #text at space x\n cells = currentPlayer.cells\n if (cells.index == 2): self.lifeMsg = \"Rent, Pay $5k\"\n elif (cells.index == 3): self.lifeMsg = \"Raffle prize! Collect $10k!\"\n elif (cells.index == 4): self.lifeMsg = \"Scholarship, collect $20k!\"\n elif (cells.index == 5): self.lifeMsg = \"Buy books, pay $5k\"\n elif (cells.index == 7): self.lifeMsg = \"Part-time Job, collect $5k\"\n elif (cells.index == 10): self.lifeMsg = \"Spring break!, pay $5k\"\n elif (cells.index == 20): self.lifeMsg = \"Marathon! collect $20k\"\n elif (cells.index == 26): self.lifeMsg = \"Honeymoon! pay $10k\"\n elif (cells.index == 28): self.lifeMsg = \"Buy furniture! pay $10k\"\n elif (cells.index == 29): self.lifeMsg = \"Car insurance, pay $10k\"\n elif (cells.index == 30): self.lifeMsg = \"Moving! pay $10k\"\n elif (cells.index == 31): self.lifeMsg = \"Night School, pay $20k\"\n elif (cells.index in cells.taxPos): self.lifeMsg = \"Taxes!\"\n elif (cells.index == 38): self.lifeMsg = \"Fired! New Career\"\n elif (cells.index == 40): self.lifeMsg = \"Buy baby crib! pay $5k\"\n elif (cells.index == 42): self.lifeMsg = \"Win talent show collect $20k\"\n elif (cells.index == 45): self.lifeMsg = \"At World Series! pay $20k\"\n elif (cells.index == 47): self.lifeMsg = \"Hollywood premeir! pay $5k\"\n elif (cells.index == 48): self.lifeMsg = \"House flood! pay $40k\"\n \n def moreEventStatus(self,currentPlayer): #text at space x\n cells = currentPlayer.cells\n if (cells.index in cells.salTradePos): self.lifeMsg = \"Trade Salaries!\"\n elif (cells.index == 49): self.lifeMsg = \"Family checkup! pay $5k\"\n elif (cells.index == 54): self.lifeMsg = \"Tree falls on house, pay $15k\"\n elif (cells.index == 56): self.lifeMsg = \"Buy big screen TV, pay $5k\"\n elif (cells.index == 61): self.lifeMsg = \"Car stolen!!! pay $15k\"\n elif (cells.index == 67): self.lifeMsg = \"Vacation!, pay $25k\"\n elif (cells.index == 68): self.lifeMsg = \"Night School, pay $20k\"\n elif (cells.index == 68): self.lifeMsg = \"Night School, pay $20k\"\n elif (cells.index == 70): self.lifeMsg = \"Art auction, pay $20k\"\n elif (cells.index == 73): self.lifeMsg = \"Beauty Pageant! collect $20k\"\n elif (cells.index == 77): self.lifeMsg = \"Tennis camp! Pay $25k\"\n elif (cells.index == 78): self.lifeMsg = \"African Safari! Pay $25k\"\n elif (cells.index == 82): self.lifeMsg = \"Day Care! Pay $5k\"\n elif (cells.index == 83): self.lifeMsg = \"Write bestseller! Collect 80k\"\n elif (cells.index == 85): self.lifeMsg = \"Fund Police Ball! Pay $15k\"\n elif (cells.index == 87): self.lifeMsg = \"Find treasure! Collect $80k\"\n elif (cells.index == 89): self.lifeMsg = \"Invest in Broadway! Pay $15k\"\n elif (cells.index == 92): self.lifeMsg = \"Build a barn! Pay $70k\"\n elif (cells.index == 94): self.lifeMsg = \"Buy a sports car! Pay $25k\"\n\n def evenMoreEventStatus(self,currentPlayer): #text at space x\n cells = currentPlayer.cells\n if (cells.index == 95): self.lifeMsg = \"Tax Break! Collect $75k\"\n elif (cells.index == 97): self.lifeMsg = \"Give to art inst.! Pay $25k!\"\n elif (cells.index == 99): self.lifeMsg = \"Game Show! Collect $95k\"\n elif (cells.index == 100): self.lifeMsg = \"Summer School. Pay $5k!\"\n elif (cells.index == 103): self.lifeMsg = \"Buy cabin on lake! Pay $90k\"\n elif (cells.index == 105): self.lifeMsg = \"Burglary! Pay $50k\"\n elif (cells.index == 106): self.lifeMsg = \"Nobel Prize! Win $100k!!!\"\n elif (cells.index == 108): self.lifeMsg = \"Buy gym equipment! Pay $30k!\"\n elif (cells.index == 110): self.lifeMsg = \"Tornado! Pay $125k!\"\n elif (cells.index == 112): self.lifeMsg = \"Mooshoo flu attk! Pay $25k!\"\n elif (cells.index == 114): self.lifeMsg = \"Buy sailboat! Pay $30k\"\n elif (cells.index == 115): self.lifeMsg = \"Golf Tourney! Pay $35k\"\n elif (cells.index == 119): self.lifeMsg = \"Produce rock vid! Pay $100k\"\n elif (cells.index == 123): self.lifeMsg = \"Remove tattoes! Pay $100k\"\n elif (cells.index == 124): self.lifeMsg = \"Kids to college! Pay $50k\"\n elif (cells.index == 129): self.lifeMsg = \"Sponsor an exhibit.Pay $125k\"\n elif (cells.index == 135): self.lifeMsg = \"Race horse! Pay $65k\"\n elif (cells.index == 141): self.lifeMsg = \"Tour Europe! Pay $45k\"\n \n def lastEventStatus(self,currentPlayer): #text at space x\n cells = currentPlayer.cells\n if (cells.index == 144): self.lifeMsg = \"Party for grammy winners!-$35k\"\n elif (cells.index == 145): self.lifeMsg = \"Luxury Cruise! Pay $5k\"\n elif (cells.index == 146): self.lifeMsg = \"Pension, Collect $100k\"\n\n def displayLifeStatus(self,lifeMsg): #displays message at point x\n self.canvas.create_text(self.width/2, self.positionY + 350,\n text = lifeMsg, font = self.font, fill = \"white\")\n \n#(19,-5000) doctor, (28,-10000)salesman, (31, -20000) teacher, (45, -20000)\n#Athlete (49, -5000) doctor (56, 5000) salesman (68, -20000) teacher \n#(77, -25000) Athlete Teacher (82, -5000) Police (85,-15000)\n#is insured (optional)\n# 38 newCareer 116\n\n def Options(self,currentPlayer): #choose which direction you're going!\n cells = currentPlayer.cells\n self.value = int(raw_input(\"Choose next spot %d or %d\" % (1,2)))\n if self.value not in [1,2] : print \"Try again! Must be one or two!\"\n #elif type(self.value) != int: print \"Needs to be an integer!\"\n else:\n if self.value == 1:\n cells.index = cells.Spaces[cells.index][3][0]\n if self.value == 2:\n cells.index = cells.Spaces[cells.index][3][1]\n currentPlayer.Money.payDaySpots = (\n currentPlayer.Money.payDaySpots[1:len(cells.payDaySpots)])\n \n def gameOver(self, currentPlayer,otherPlayer): #add to the player's money\n #all their life cards(which is just numbers with money) the one who\n #has the most money at the end wins!\n currentLifeCards = currentPlayer.LifeCard.playerLifeCards\n otherLifeCards = otherPlayer.LifeCard.playerLifeCards\n for i in xrange(len(currentPlayer.LifeCard.playerLifeCards)):\n currentPlayer.Money.playerMoney += currentLifeCards[i]\n for i in xrange(len(otherPlayer.LifeCard.playerLifeCards)):\n otherPlayer.Money.playerMoney += otherLifeCards[i]\n self.playersMoney = [self.playerOne.Money.playerMoney,\n self.playerTwo.Money.playerMoney]\n self.isGameOver = True\n\n def winner(self): #who won!\n winningPlayer = self.playersMoney.index(max(self.playersMoney))\n self.canvas.create_text(self.width/2, self.height/2,\n text = \"Player %s Wins!!!\" %(str(winningPlayer + 1)),\n font = self.font, fill = \"black\")\n \nclass Cell(object): #class that determines what happens when you land/pass\n #a position\n def __init__(self): #holds the indexes of the points that either\n #add money, give a life card, add a baby, etc.\n self.Spaces = []\n self.salary = 0 \n self.newLocations = eval(readFile( \"\\\\GameOfLife\\\\points.txt\"))\n #gets all the points from the file we created in gameOfLifePoints\n self.playerLifeCards = []\n self.playerMoney = 0\n self.listPos()\n self.gameOfLifePos()\n self.playerBabyCount = 0\n self.playerLifeCards = []\n self.index = 0 #start at point 0\n self.occupation = \"Nothing\"\n self.degreeStatus = False\n self.houseChoice = \"Nothing\"\n #if the player went to college, it subtracts 150k then you have\n #to select jobs but if you hit work, you pick a job\n\n def listPos(self): #lists positions of payday spots, lifecard positions,\n #places where one would have a baby, and stopping spots (lifePosition)\n self.payDaySpots = [1,15,23,32,37,43,52,60,66,71,79,86,90,96,104,111,\n 118,125,132,137,143] \n self.lifePos = [6,9,11,13,16,18,21,22,27,35,55,58,59,63,64,69,72,81,\n 91,92,98,101,102,121,128,130,133,136,138,140,142]\n self.babyPos = [39,41,44,46,51,53,65,84]\n self.otherPos = [2,3,4,5,7,10,20,26,28,29,30,31,34,40,47,48,49,\n 54,56,61,67,68,70,73,77,78,82,83,85,87,89,92,94,95,\n 97,99,100,103,105,106,108,110,112,114,115,119,123,\n 124,129,135,141,144,145,146]\n self.salTradePos = [50, 62, 75, 93, 107, 120, 131]\n self.newCareerPos = [38,116]\n self.taxPos = [33,76,88,113,126]\n self.lifePosition = [(14, False), (25, False), (36, False)]\n (self.jobStatus, self.jobPos) = (self.lifePosition[0][1],\n self.lifePosition[0][0])\n (self.marriedStatus, self.marriedPos) = (self.lifePosition[1][1],\n self.lifePosition[1][0])\n (self.homeStatus, self.homePos) = (self.lifePosition[2][1],\n self.lifePosition[2][0])\n def gameOfLifePos(self):\n self.listPos()\n self.gameOfLifeSpaces = []\n for i in (self.payDaySpots): self.gameOfLifeSpaces.append(i)\n for i in (self.lifePos): self.gameOfLifeSpaces.append(i)\n for i in (self.babyPos): self.gameOfLifeSpaces.append(i)\n for i in (self.otherPos): self.gameOfLifeSpaces.append(i)\n for i in (self.salTradePos): self.gameOfLifeSpaces.append(i)\n for i in (self.newCareerPos): self.gameOfLifeSpaces.append(i)\n for i in (self.taxPos): self.gameOfLifeSpaces.append(i)\n for i in ([14,25,36]): self.gameOfLifeSpaces.append(i)\n return self.gameOfLifeSpaces\n \n def makeList(self):\n for self.i in xrange(len(self.newLocations)): #like said in init,\n #this stores in the list indexes, a string that will be\n #evaluated of what happens when you land at/pass a point,\n #and split decisions on the board\n i = self.i #indexes\n self.functions() #the functions\n self.splitDecisions() #which index you go to for split index\n self.Spaces.append([i, self.newLocations[i], self.function,\n self.nextCell]) #so self.spaces 0 = index\n #1 = coordinates of index #2 is function of what happens\n #when you land/pass point #nextcell, where player goes next\n return self.Spaces\n #to add to the tuple of coordinates\n # do you have two choices?\n # what happens at that point (a function)\n \n def functions(self): #stores all the functions in a string\n #format based on index to be evaluate in GameOfLifeData\n i = self.i #index (again)\n if (i in (self.payDaySpots) or i in [14,25,36] or i in self.lifePos or\n i in self.taxPos or i in self.babyPos or i in self.salTradePos or\n i in self.otherPos or i in self.newCareerPos):\n #these indexes do something\n self.listOfFunctions() #split for style reasons\n self.moreListOfFunctions()\n else: #indexes do nothing\n self.function = \"currentPlayer.DoSomething.doSomething()\"\n \n def listOfFunctions(self):\n i = self.i #index (again)\n if i in self.payDaySpots: #getting paid!\n self.function = (\n \"currentPlayer.Money.money(currentPlayer.LifeEvent.salary)\")\n elif i in [14,25,36]: #marriage,career,or a new house\n if i == 14: self.function = (\n \"currentPlayer.LifeEvent.stoppingPoint('career')\" )\n elif i == 25: self.function = (\n \"currentPlayer.LifeEvent.stoppingPoint('marriage')\")\n else: self.function = (\n \"currentPlayer.LifeEvent.stoppingPoint('newHouse')\")\n elif i in self.lifePos: #draw lifecard\n self.function = \"currentPlayer.LifeCard.lifeCard()\"\n elif i in self.newCareerPos:\n self.function = \"currentPlayer.LifeEvent.newCareer()\"\n \n def moreListOfFunctions(self):\n i = self.i #index (again)\n if i in self.taxPos: #pay taxes\n self.function = (\n \"currentPlayer.Money.taxes(currentPlayer.LifeEvent.salary)\")\n elif i in self.babyPos:\n if (i == 44 or i == 84): #points where you get a twin instead of\n #one baby\n self.function = \"currentPlayer.Babies.babyCount(2)\"\n else:\n self.function = \"currentPlayer.Babies.babyCount(1)\"\n elif i in self.salTradePos: #trade salaries\n self.function =\"currentPlayer.LifeEvent.salTrade(self.playerOne.LifeEvent, self.playerTwo.LifeEvent)\"\n elif i in self.otherPos: #misc\n self.function = \"currentPlayer.OtherPoint.otherPoints(cells.index)\"\n \n\n def splitDecisions(self):\n #split decisions in the game, example at point 0, whether to\n #go to college or job\n i = self.i\n if (i == 0 or i == 48 or i== 84): #the three split decisions\n if i == 0 : self.nextCell = [1,4]#where you'll land based off\n #of choice made in Options()\n elif i == 48: self.nextCell = [49,56]\n elif i == 84: self.nextCell = [85,89]\n elif (i == 3 or i == 55 or i == 88): #go back to regular list if\n #you chose the alternative route\n if i==3: self.nextCell = [15]\n elif i == 55: self.nextCell = [62]\n elif i == 88: self.nextCell = [96]\n else: self.nextCell = [i+1]\n\nclass Money(Cell): #called when you pass a payday spot, you get money!\n #or when land on a tax spot, paying taxes :(\n \n def __init__(self):\n super(Money, self).__init__()\n #self.playerOne = player()\n #self.playerTwo = player()\n \n def money(self, value): #get paid\n self.playerMoney += value\n\n def taxes(self,salary): #pay taxes\n self.playerMoney -= int(round(salary/4))\n\n \n\nclass LifeCard(Cell): #draw a life card that adds/subtracts money at the end\n #of the game. Life Cards stored in list self.playerLifeCards\n\n def __init__(self):\n super(LifeCard, self).__init__()\n \n def lifeCardValues(self):\n self.lifeCards = []\n for i in xrange(-50000,51000,1000):\n self.lifeCards += [i]\n return self.lifeCards\n\n def lifeCard(self):\n self.lifeCardValues()\n self.playerLifeCards += [self.lifeCards[random.randint(\n 0,(len(self.lifeCards)-1))]]\n\nclass Babies(Cell): #add a newborn! Babies take 5K from player's money per turn\n \n def __init__(self):\n super(Babies, self).__init__()\n \n def babyCount(self, babies):\n self.playerBabyCount += babies\n\nclass LifeEvent(Cell): #stopping points in the game, marriage, new home, or\n #when you chose the college route, a new job\n \n def __init__(self):\n super(LifeEvent, self).__init__()\n super(LifeEvent, self).makeList()\n self.occupations = [(0,\"Police Officer\", 40000),(1,\"Firefighter\",60000),\n (2,\"Artist\", 30000), (3,\"Entertainer\", 50000),\n (4,\"Teacher\", 55000), (5,\"Athlete\", 100000),\n (6,\"Architect\",50000), (7,\"Psychologist\", 60000),\n (8,\"Doctor\", 100000),(9,\"Accountant\", 40000),\n (10,\"Engineer\", 100000),\n (11,\"Computer Scientist\",100000)]\n # Above ^ index of occupation, occupation, salary of occupation\n self.houses = [(0, \"Victorian\", 150000),(1, \"Condo\", 80000),\n (2, \"Town House\", 120000), (3, \"Mansion\", 400000),\n (4, \"New School Home\", 300000)]\n #above ^ choices of homes\n \n def stoppingPoint(self, lifeEvent):\n if lifeEvent == 'marriage': #married!\n self.marriedStatus = True\n self.index = self.marriedPos\n print \"Hi\"\n elif lifeEvent =='newHouse': #new house so pick home!\n self.homeStatus = True\n self.newHouse()\n self.index = self.homePos\n print \"Hi\"\n elif lifeEvent == 'career':\n self.jobStatus = True\n self.degreeStatus = True\n self.playerMoney -= 150000 #only happens when person goes to college\n #college fees!\n self.career()\n print \"Hi\"\n print self.playerMoney\n print \"Salary\", self.salary\n self.index = self.jobPos\n \n def career(self): #choose a career\n print self.occupations\n while self.occupation == \"Nothing\":\n self.careerChoice = int(raw_input(\n \"Choose your career by #(indexes 6+ for those with degrees!)\"))\n if 11 >= self.careerChoice > 5 and self.degreeStatus == False:\n print \"Try again! Need a degree for this career!\"\n elif self.careerChoice > 11 or self.careerChoice < 0:\n print \"Try again! Out of bounds!\"\n #elif type(self.careerChoice) != int:\n #print \"Not an integer!\"\n else:\n self.salary = self.occupations[self.careerChoice][2]\n self.occupation = self.occupations[self.careerChoice][1]\n \n def newHouse(self):#choose a home!\n print self.houses\n while self.houseChoice == \"Nothing\":\n self.homeChoice = int(raw_input(\"Choose your home!\"))\n if 4 < self.homeChoice or 0 > self.homeChoice:\n print \"Try Again! Out of Bounds!\"\n else:\n self.playerMoney -= self.houses[self.homeChoice][2]\n self.houseChoice = self.houses[self.homeChoice][1]\n\n def salTrade(self,playerOne,playerTwo): #trade salaries\n (playerOne.salary,playerTwo.salary) = (playerTwo.salary,\n playerOne.salary)\n print \"hello\"\n #51, 62, 75, 93, 107, 120, 131\n\n def newCareer(self):\n self.occupation = \"Nothing\"\n self.salary = \"Nothing\"\n self.career()\n\nclass OtherPoint(Cell):\n \n def __init__(self):\n super(OtherPoint, self).__init__()\n self.otherPos = [(2, -5000),(3,10000),(4,20000),(5,-5000),(7,5000),\n (10,-5000),(20,20000),(26, -10000),(28,-10000),\n (29, -10000),(30, -10000), (31, -20000),\n (34,50000), (40, -5000),(42,20000), (45, -20000),\n (47,-5000), (48,-40000), (49, -5000),(54, -15000),\n (56, -5000),(61, -15000), (67,-25000), (68, -10000),\n (70,-20000), (73,20000), (77,-25000), (78,-25000),\n (82, -5000),(83,80000),(85,-15000),(87,80000),\n (89,-15000),(92,-70000),(94,-25000),(95,75000),\n (97,-25000),(99,95000), (100,-5000),(103,-90000),\n (105,-50000),(106,100000),(108,-30000),(110, -125000),\n (112,-25000),(114,-30000),(115,-35000),(119,-100000),\n (123,-100000),(124,-50000),(129,-125000),(135,-60000),\n (141,-45000),(144,-35000), (145,-5000),(146,100000)]\n (self.cashPos,self.cashValue) = ([],[])\n for i in xrange(len(self.otherPos)):\n self.cashPos += [self.otherPos[i][0]]\n for i in xrange(len(self.otherPos)):\n self.cashValue += [self.otherPos[i][1]]\n \n def otherPoints(self, index):\n #other points add money to player's money\n #otherPos holds index of point and how much you must pay/get\n #cashPos is just the index\n #cash value is his how much you pay/get\n cells = Cell()\n self.playerMoney += self.cashValue[self.cashPos.index(self.index)]\n print \"index\", self.index\n #self.cashValue[self.cashPos.index(self.index)]\n \nclass DoSomething(Cell): #other spots on the board\n\n def __init__(self):\n super(DoSomething, self).__init__()\n\n def doSomething(self):\n print \"Merry Christmas!\"\n\napp = GameOfLifeData()\napp.run()\n \n##app = GameOfLifeData()\n##app.run()\n\n#check to see if the player has hit the end point,\n#switch player until end game\n\n#Thing's to do this week\n#RESIZABLE IMAGE\n#Ability to deal with split places\n#storage of character info\n#things that happen at point X\n\n#Make move in Game of Life\n#GameOfLifeData = boardGame\n#Subclasses of Cell (money, lifeCard) all inherit from cell.\n\n#Have a function that is called passed at that is called every time\n#with payday it will have to check if passed at AND \n#Have a function that is called for split decisions\n\n"} {"blob_id": "15e68bba93bd5794e440a0bf5e4532f4b76030dd", "repo_name": "peasant98/NBA-Stats-Clustering", "path": "/clustering/Cluster.py", "length_bytes": 7430, "score": 3.625, "int_score": 4, "content": "# NBA Stats Clustering\n# Copyright Matthew Strong, 2019\n\n# main cluster file\nimport numpy as np\n# reads the csv into dataframe before clustering\nimport clustering.CreateClusterData\nimport clustering.DimReduce\n\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\nfrom nba_api.stats.static import players\n\nclass NBACluster():\n def __init__(self, num_clusters):\n self.num_clusters = num_clusters\n # get number of clusters, this is called in all other child classes\n\n def init_data_from_df(self, year, dim_vals, normalize=True):\n # normalize can be set to false, but you should not do it \n self.year = year\n self.dim_vals = dim_vals\n self.cols = dim_vals\n self.reduced = False\n # create clustered data and get ids, numpy matrix for clustering,\n # dataframe, and dimensions to display in plot function\n self.names, self.x, self.df, self.ordered_dims = clustering.CreateClusterData.create_cluster_data(year, dim_vals, normalize)\n # initializes the data from the dataframe\n # pca dimension reduction if there are 4 or more dimensions on which we want to cluster\n if len(self.dim_vals) > 3:\n # perform pca if many dimensions to get 3-d visualization\n self.x, self.df, self.ordered_dims = clustering.DimReduce.pca(self.x, 3)\n self.dim_vals = self.ordered_dims\n # it is reduced!\n self.reduced = True\n print(f'{self.names.shape[0]} unique points, each with dimension {self.x.shape[-1]}')\n\n def fit(self, eps):\n '''\n fit function.\n '''\n # fit the data\n # is officially implemented in the other classes that inherit from this one.\n pass\n def get_labels(self):\n '''\n gets the labels from the fitting of the classification.\n '''\n # show labels\n # return labels from engine.\n return self.labels\n def text_display_cluster(self):\n '''\n displays all of the groups that every player is in after `fit()` is run, as well\n their corresponding centroid.\n '''\n for i,p in enumerate(self.x):\n name_obj = players.find_player_by_id(self.names[i])\n if name_obj != None:\n name = name_obj['full_name']\n print(f'{name}: Group {self.labels[i]} with centroid {self.centroids[self.labels[i]]}')\n\n def plot(self, disp_names=False, thresh=0.8, single_name='', interactive=False):\n '''\n plots the cluster points.\n\n `disp_names`: `bool`: selects whether to display some players' names or not.\n\n `thresh`: `float`, between `0` and `1`: given each dimensions max value, take `thresh * 100%` of that to show names.\n\n `single_name`: `str`: If the user wants to see where a specific player is classified, they can do so here.\n\n `interactive`: `bool`: If the user wants to be able to interact with the plot after each clustering `fit` is run.\n \n '''\n self.priority_name_index = -1\n player = players.find_players_by_full_name(single_name)\n if len(player) == 1:\n # there is a valid player with the name\n self.p_id = player[0]['id']\n index = np.where(np.array(self.names)==self.p_id)\n if len(index) == 1:\n # player does in fact exist\n self.priority_name_index = index[0][0]\n # groups\n self.color_labels = [f'Group {i+1}' for i in range(self.num_clusters)]\n groups = [[] for i in range(self.num_clusters)]\n group_labels = [[] for i in range(self.num_clusters)]\n for i,p in enumerate(self.x):\n groups[self.labels[i]].append(p)\n group_labels[self.labels[i]].append(self.labels[i])\n groups = np.array(groups)\n if len(self.dim_vals) == 1:\n pass\n elif len(self.dim_vals) == 2:\n # 2-d visualization\n fig, ax = plt.subplots()\n # for i,group in enumerate(groups):\n # g = np.array(group)\n # plt.scatter(g[::,0], g[::,1], c=self.labels, label=self.color_labels)\n ax.scatter(self.x[::,0], self.x[::,1], c=self.labels)\n # plt.xlabel('f')\n ax.set_xlabel(self.ordered_dims[0])\n ax.set_ylabel(self.ordered_dims[1])\n dim1_thresh = np.max(self.x[::,0]) * thresh\n dim2_thresh = np.max(self.x[::,1]) * thresh\n # if we want to display themes, find players with high values, and show the name on the plot\n if disp_names:\n for i,p in enumerate(self.x):\n if p[0] > dim1_thresh or p[1] > dim2_thresh:\n name_obj = players.find_player_by_id(self.names[i])\n if name_obj != None:\n name = name_obj['full_name']\n ax.text(p[0],p[1], name)\n # look for player with priority name index, which is when a user wants a player's name to be\n # shown in the graph itself\n for i,p in enumerate(self.x):\n if i==self.priority_name_index:\n name_obj = players.find_player_by_id(self.names[i])\n if name_obj != None:\n name = name_obj['full_name']\n ax.text(p[0],p[1], name)\n elif len(self.dim_vals) == 3:\n # 3d visualization\n # kudos to matplotlib with good example of showing how this works\n fig = plt.figure()\n ax = Axes3D(fig)\n ax.scatter(xs=self.x[::,0], ys=self.x[::,1], zs=self.x[::,2], c=self.labels)\n ax.set_xlabel(self.ordered_dims[0])\n ax.set_ylabel(self.ordered_dims[1])\n ax.set_zlabel(self.ordered_dims[2])\n dim1_thresh = np.max(self.x[::,0]) * thresh\n dim2_thresh = np.max(self.x[::,1]) * thresh\n dim3_thresh = np.max(self.x[::,2]) * thresh\n # similar to 2d plot, display names that are high on one or more axes\n\n if disp_names:\n for i,p in enumerate(self.x):\n if p[0] > dim1_thresh or p[1] > dim2_thresh or p[2] > dim3_thresh:\n name_obj = players.find_player_by_id(self.names[i])\n if name_obj != None:\n name = name_obj['full_name']\n ax.text(p[0],p[1],p[2], name)\n # display name if important\n for i,p in enumerate(self.x):\n if i==self.priority_name_index:\n name_obj = players.find_player_by_id(self.names[i])\n if name_obj != None:\n name = name_obj['full_name']\n ax.text(p[0],p[1],p[2], name)\n # save all of the graphs to a png file\n # if pca was performed\n # method type\n # year\n # k value\n # along with fields/dimensions clustering was performed.\n is_dr = '' if not self.reduced else '-with-PCA'\n rounded_ssd = np.round(self.ssd, 4)\n title = f'{self.method}-k={self.num_clusters}-{self.cols}-{self.year}{is_dr}'\n plt.title(f'{title}-ssd={rounded_ssd}')\n plt.savefig(f'img/{title}')\n # also can be toggled in 3-d, fun stuff\n if interactive:\n plt.show()\n # close plot.\n plt.close()"} {"blob_id": "f4f131f11cb1905e2d484b8b504dfe9944b7c000", "repo_name": "fatedglory14/Computational-Physics", "path": "/hooking_rule.py", "length_bytes": 908, "score": 3.6875, "int_score": 4, "content": "#Homework 7 Problem 5 Dimension of Symmetric Partition\n#Andrew Turner\n\nfrom numpy import *\nfrom math import *\n\nn = 4\nsym_partition = [[1,1],[1,1]]\nhooking_factor = 1\n\nfor i in range(len(sym_partition)):\n for j in sym_partition[i]:\n hook = sum(sym_partition[i][j:]) + sum(sym_partition[i:][j]) -1\n hooking_factor *= hook\n\ndimension = factorial(n) / hooking_factor\n\nprint 'The dimension of the symmetric partition of %d is %d.' % (n, dimension)\n\n\n'''If this code worked the algorithm would be as follows:\n1: Assign a symmetric partition to an array of n by n filled with 1's.\n2: Calculate the number of 1's below and to the right each index ij within the array.\n3: Multiply each value for (2) to get the hooking factor.\n4: For an integer n, calculate n! and divide by the hooking factor to get the dimension.\n\nFor this particular example, hooking factor should be (3*2*2*1), giving dimension = 2\n'''\n"} {"blob_id": "af14268d01cc722b8c5a622d7cb6874860fd8fb6", "repo_name": "tanya9779/lab24", "path": "/4_vigenere.py", "length_bytes": 5716, "score": 3.640625, "int_score": 4, "content": "\ufeff# -*- coding: utf-8 -*-\n\nclass Vigenere:\n alphabet = \"\u0430\u0431\u0432\u0433\u0434\u0435\u0451\u0436\u0437\u0438\u0439\u043a\u043b\u043c\u043d\u043e\u043f\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044a\u044b\u044c\u044d\u044e\u044f\"\n\n def __init__(self, keyword):\n # \u0441\u043b\u043e\u0432\u0430\u0440\u044c \u0434\u043b\u044f \u043d\u0430\u0445\u043e\u0436\u0434\u0435\u043d\u0438\u044f \u043d\u043e\u043c\u0435\u0440\u0430 \u0431\u0443\u043a\u0432\u044b \u0432 \u0430\u043b\u0444\u0430\u0432\u0438\u0442\u0435\n self.alphaindex = {self.alphabet[index]: index for index in range(len(self.alphabet))}\n # \u0432\u043c\u0435\u0441\u0442\u043e \u0441\u0438\u043c\u0432\u043e\u043b\u043e\u0432 \u0441\u043f\u0438\u0441\u043e\u043a \u043d\u043e\u043c\u0435\u0440\u043e\u0432 \u0441\u0438\u043c\u0432\u043e\u043b\u043e\u0432 \u0438\u0437 \u043a\u043b\u044e\u0447\u0435\u0432\u043e\u0433\u043e \u0441\u043b\u043e\u0432\u0430\n self.key = [self.alphaindex[letter] for letter in keyword.lower()]\n\n # \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u0426\u0435\u0437\u0430\u0440\u044f \u0441\u043e \u0441\u0434\u0432\u0438\u0433\u043e\u043c shift\n def caesar(self, letter, shift):\n if letter in self.alphaindex: # \u0441\u0442\u0440\u043e\u0447\u043d\u0430\u044f \u0431\u0443\u043a\u0432\u0430\n index = (self.alphaindex[letter] + shift)%len(self.alphabet)\n cipherletter = self.alphabet[index]\n elif letter.lower() in self.alphaindex: # \u0437\u0430\u0433\u043b\u0430\u0432\u043d\u0430\u044f \u0431\u0443\u043a\u0432\u0430\n cipherletter = self.caesar(letter.lower(), shift).upper()\n else:\n cipherletter = letter\n return cipherletter\n\n def encode(self, line, key = None):\n if not key:\n key = self.key\n ciphertext = []\n i = 0\n for letter in line:\n shift = key[i]\n cipherletter = self.caesar(letter, shift)\n ciphertext.append(cipherletter)\n i = (i + 1)%len(key)\n\n return ''.join(ciphertext)\n\n def decode(self, line): # \u043f\u0440\u043e\u0446\u0435\u0434\u0443\u0440\u0430 \u0434\u0435\u0448\u0438\u0444\u0440\u043e\u0432\u0430\u043d\u0438\u044f\n # \u043f\u043e\u0447\u0442\u0438 \u043d\u0438\u0447\u0435\u043c \u043d\u0435 \u043e\u0442\u043b\u0438\u0447\u0430\u0435\u0442\u0441\u044f \u043e\u0442 \u0448\u0438\u0444\u0440\u043e\u0432\u0430\u043d\u0438\u044f\n ciphertext = []\n i = 0\n for letter in line:\n shift = self.key[i]\n cipherletter = self.caesar(letter, -shift)\n ciphertext.append(cipherletter)\n i = (i + 1)%len(self.key)\n\n return ''.join(ciphertext)\n\n\n\n\n# \u043f\u043e \u043e\u0442\u043a\u0440\u044b\u0442\u043e\u043c\u0443 \u0442\u0435\u043a\u0441\u0442\u0443 line \u0438 \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0443\u044e\u0449\u0435\u043c\u0443 \u0448\u0438\u0444\u0440\u043e\u0432\u0430\u043d\u043d\u043e\u043c\u0443 code \n# \u0438 \u0434\u043b\u0438\u043d\u0435 \u043a\u043b\u044e\u0447\u0430 keyword_len \u0432\u044b\u0447\u0438\u0441\u043b\u044f\u0435\u0442 \u043a\u043b\u044e\u0447\ndef find_keyword(line,code, keyword_len):\n alphabet = \"\u0430\u0431\u0432\u0433\u0434\u0435\u0451\u0436\u0437\u0438\u0439\u043a\u043b\u043c\u043d\u043e\u043f\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044a\u044b\u044c\u044d\u044e\u044f\"\n alphaindex = {alphabet[index]: index for index in range(len(alphabet))}\n\n keyword = [0]*len(line) # \u043f\u043e\u043b\u0435\u0437\u043d\u044b \u0431\u0443\u0434\u0443\u0442 \u0442\u043e\u043b\u044c\u043a\u043e \u043f\u043e\u0437\u0438\u0446\u0438\u0438 \u0433\u0434\u0435 \u0435\u0441\u0442\u044c \u0440\u0443\u0441\u0441\u043a\u0438\u0435 \u0431\u0443\u043a\u0432\u044b\n final_keyword = [0]*keyword_len # \u0438\u0442\u043e\u0433\u043e\u0432\u044b\u0439 \u043a\u043b\u044e\u0447\n # \u0434\u0440\u0443\u0433\u0438\u0435 \u0431\u0443\u043a\u0432\u044b, \u043f\u0440\u043e\u0431\u0435\u043b\u044b \u0438 \u0441\u0438\u043c\u0432\u043e\u043b\u044b \u043d\u0435 \u0448\u0438\u0444\u0440\u0443\u044e\u0442\u0441\u044f \u0438 \u043a\u043b\u044e\u0447 \u043d\u0435 \u0432\u044b\u0447\u0438\u0441\u043b\u044f\u044e\u0442\n # \u0432\u044b\u0447\u0438\u0441\u043b\u0438\u043c \u0434\u043b\u044f \u043a\u0430\u0436\u0434\u043e\u0439 \u043f\u043e\u0437\u0438\u0446\u0438\u0438, \u0430 \u043f\u0435\u0440\u0432\u044b\u0435 keyword_len \u043f\u043e\u0437\u0438\u0446\u0438\u0439 \u0431\u0443\u0434\u0435\u043c \u0443\u0442\u043e\u0447\u043d\u044f\u0442\u044c \u043a\u0430\u0436\u0434\u044b\u0439 \u0440\u0430\u0437\n\n for i in range(len(line)):\n letter=line[i]\n cod_letter = code[i]\n if letter in alphaindex: # \u0441\u0442\u0440\u043e\u0447\u043d\u0430\u044f \u0431\u0443\u043a\u0432\u0430\n index = (alphaindex[cod_letter] - alphaindex[letter] )%len(alphabet)\n if final_keyword[i%keyword_len] == 0:\n final_keyword[i%keyword_len] = index\n keyword[i] = index # \u044d\u0442\u043e \u0442\u043e\u043b\u044c\u043a\u043e \u0434\u043b\u044f \u0438\u043b\u043b\u044e\u0441\u0442\u0440\u0430\u0446\u0438\u0438\n elif letter.lower() in alphaindex: # \u0437\u0430\u0433\u043b\u0430\u0432\u043d\u0430\u044f \u0431\u0443\u043a\u0432\u0430\n index = (alphaindex[cod_letter.lower()] - alphaindex[letter.lower()] )%len(alphabet)\n if final_keyword[i%keyword_len] == 0:\n final_keyword[i%keyword_len] = index\n keyword[i] = index\n return final_keyword, keyword\n\n# --- main ------------------\n\n# \u0428\u0442\u0438\u0440\u043b\u0438\u0446 \u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u043b\u0441\u044f \u0441\u0430\u043c\u043e\u0439 \u0441\u0442\u043e\u0439\u043a\u043e\u0439 \u043a\u0440\u0438\u043f\u0442\u043e\u0433\u0440\u0430\u0444\u0438\u0435\u0439 - \u0434\u043e\u0441\u0442\u0430\u0432\u0430\u043b \u0438\u0437 \u0448\u043a\u0430\u0444\u0430 \u043a\u043d\u0438\u0433\u0443 \n# \u0438 \u043e\u0442\u043a\u0440\u044b\u0432\u0430\u043b \u043a\u0430\u0436\u0434\u044b\u0439 \u0440\u0430\u0437 \u043d\u0430 \u0434\u0440\u0443\u0433\u043e\u0439 \u0441\u0442\u0440\u0430\u043d\u0438\u0446\u0435 (\u041e\u043d \u0438 \u043a\u043d\u0438\u0433\u0438 \u043c\u043e\u0433 \u0431\u0440\u0430\u0442\u044c \u0440\u0430\u0437\u043d\u044b\u0435)\n# \u041d\u0430\u0448\u0430 \u0432\u0435\u0440\u0441\u0438\u044f - \u0442\u0435\u043a\u0441\u0442 \u043d\u0430\u0447\u0438\u043d\u0430\u0435\u0442\u0441\u044f \u0441\u043e \u0441\u043b\u043e\u0432 \"\u0428\u0438\u0444\u0440 \u0412\u0435\u0440\u043d\u0430\u043c\u0430 (\u043e\u0434\u043d\u043e\u0440\u0430\u0437\u043e\u0432\u044b\u0439 \u0431\u043b\u043e\u043a\u043d\u043e\u0442)\"\n\nline = \"\u0428\u0438\u0444\u0440 \u0412\u0435\u0440\u043d\u0430\u043c\u0430 (\u043e\u0434\u043d\u043e\u0440\u0430\u0437\u043e\u0432\u044b\u0439 \u0431\u043b\u043e\u043a\u043d\u043e\u0442)\"\ncode = \"\u0419\u044b\u0433\u044c \u041e\u0435\u044e\u044f\u0442\u044b\u043b (\u043e\u0441\u044f\u0431\u044f\u043b\u0443\u044b\u0432\u0438\u044b \u043f\u0447\u044a\u0447\u043d\u044c\u0434)\"\n# \u2116 1234567812345678123456781234567812\n# \u0415\u0441\u0442\u044c \u0431\u0443\u043a\u0432\u0430 \"\u043d\" 2 \u0440\u0430\u0437\u0430 \u0432 \u043f\u043e\u0437\u0438\u0446\u0438\u0438 1 \n# \u0438 \u0431\u0443\u043a\u0432\u0430 \"\u0430\" 2 \u0440\u0430\u0437\u0430 \u0432 \u043f\u043e\u0437\u0438\u0446\u0438\u0438 4\n# \u043f\u0440\u0438 \u0434\u043b\u0438\u043d\u0435 \u043a\u043b\u044e\u0447\u0430 8 \u0448\u0438\u0444\u0440\u043e\u043a\u043e\u0434\u044b \u043e\u0434\u0438\u043d\u0430\u043a\u043e\u0432\u044b\u0435 -\n# \u0437\u043d\u0430\u0447\u0438\u0442 \u0434\u043b\u0438\u043d\u0430 \u043a\u043b\u044e\u0447\u0430 \u043d\u0430 \u0441\u0430\u043c\u043e\u043c \u0434\u0435\u043b\u0435 8\n# \u0432 \u043a\u0430\u0436\u0434\u043e\u0439 \u043f\u043e\u0437\u0438\u0446\u0438\u0438 \u043a\u043e\u0433\u0434\u0430-\u043d\u0438\u0431\u0443\u0434\u044c \u043d\u0430\u0439\u0434\u0435\u0442\u0441\u044f \u0440\u0443\u0441\u0441\u043a\u0430\u044f \u0431\u0443\u043a\u0432\u0430 - \u0437\u043d\u0430\u0447\u0438\u0442 \u0432\u0441\u0435 \u043f\u043e\u0437\u0438\u0446\u0438\u0438 \u043a\u043b\u044e\u0447\u0430 \u0432\u044b\u0447\u0438\u0441\u043b\u0438\u043c\u044b\n\nkeyword_len = 8\n# \u043d\u0430\u0439\u0434\u0435\u043c \u043a\u043b\u044e\u0447\nprint(\"------------- \u041f\u041e\u0418\u0421\u041a \u041a\u041b\u042e\u0427\u0410 ------------------------\")\n(final_keycode, keycode) = find_keyword(line, code, keyword_len)\nfor i in range(int(len(keycode)/keyword_len+1)):\n print(keycode[i*keyword_len:(i+1)*keyword_len])\nprint(final_keycode) # \u043a\u043b\u044e\u0447 \u043a\u043e\u0442\u043e\u0440\u044b\u0439 \u0441\u043e\u0431\u0440\u0430\u043b\u0441\u044f \u0437\u0430 \u043d\u0435\u0441\u043a\u043e\u043b\u044c\u043a\u043e \u0440\u0430\u0441\u0448\u0438\u0444\u0440\u043e\u0432\u0430\u043d\u0438\u0439\n# \u0430 \u043f\u043e\u043f\u0440\u043e\u0431\u0443\u0435\u043c \u0441\u043e\u0431\u0440\u0430\u0442\u044c \u0441\u043b\u043e\u0432\u043e \u0438\u0437 \u044d\u0442\u0438\u0445 \u043a\u043e\u0434\u043e\u0432\nkeyword=''\nfor i in range(keyword_len):\n keyword+=Vigenere.alphabet[final_keycode[i]]\nprint(keyword)\n\n# \u043f\u043e\u043b\u0443\u0447\u0438\u043b\u0441\u044f \u0442\u0430\u043a\u043e\u0439 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\n#[18, 19, 15, 12, 0, 13, 0, 14]\n#[18, 19, 15, 12, 0, 0, 0, 14]\n#[18, 19, 15, 12, 12, 13, 0, 14]\n#[18, 0, 15, 12, 12, 13, 0, 14]\n#[18, 0]\n#[18, 19, 15, 12, 12, 13, 0, 14]\n#\u0441\u0442\u043e\u043b\u043b\u043c\u0430\u043d\n\nprint(\"------------- \u0420\u0410\u0421\u0428\u0418\u0424\u0420\u041e\u0412\u041a\u0410 \u0422\u0415\u041a\u0421\u0422\u0410 ------------------------\")\n# \u0442\u0435\u043f\u0435\u0440\u044c \u043c\u043e\u0436\u0435\u043c \u0440\u0430\u0441\u0448\u0438\u0444\u0440\u043e\u0432\u0430\u0442\u044c \u0442\u0435\u043a\u0441\u0442 (\u0435\u0433\u043e \u043c\u043e\u0436\u043d\u043e \u043f\u043e\u0434\u0430\u0442\u044c \u043d\u0430 \u0432\u0445\u043e\u0434 \u0447\u0435\u0440\u0435\u0437 \u043e\u043f\u0435\u0440\u0430\u0442\u043e\u0440 <\u0438\u043c\u044f_\u0444\u0430\u0439\u043b\u0430.txt)\ncipher = Vigenere(keyword)\n\nline = input()\nwhile not line or line != '.': # \u0435\u0441\u043b\u0438 \u0432\u0441\u0442\u0440\u0435\u0442\u0438\u043c \".\" \u0432 \u043d\u0430\u0447\u0430\u043b\u0435 \u0441\u0442\u0440\u043e\u043a\u0438 - \u043e\u0441\u0442\u0430\u043d\u043e\u0432\u0438\u043c\u0441\u044f\n print(cipher.decode(line))\n line = input()\n\n\n\n\n"} {"blob_id": "3d491bf5193d974410fffb775238eb9e19cb6023", "repo_name": "KarinShimel/Hopfield-Reconstruction", "path": "/main.py", "length_bytes": 7529, "score": 3.625, "int_score": 4, "content": "import random\nfrom typing import List\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef get_digits_from_txt(filename, num_of_letters):\n with open(filename) as f:\n content = f.readlines()\n\n number = \"\"\n all_numbers = []\n i = 0\n for line in content:\n line = line.rstrip(\"\\n\")\n number = number + line\n if line == '':\n if i < num_of_letters:\n all_numbers.append(number)\n line_size = len(number)\n number = \"\"\n i += 1\n\n if number != \"\":\n if i < num_of_letters:\n line_size = len(number)\n all_numbers.append(number)\n\n column_size = len(all_numbers)\n arr = np.zeros(shape=(column_size, line_size), dtype=int)\n for i in range(len(all_numbers)):\n for j in range(len(all_numbers[0])):\n arr[i][j] = all_numbers[i][j]\n return arr\n\n\ndef change_0_to_1(arr):\n indices_zero = arr == 0\n arr[indices_zero] = -1 # replacing 0s with -1\n return arr\n\n\ndef get_weight_matrix(digits_line_by_line):\n col_size = digits_line_by_line.shape[1]\n weight_matrix = np.zeros(shape=(col_size, col_size))\n for i in range(col_size):\n weight_matrix[i][i] = col_size + 1\n col = digits_line_by_line[:, i]\n for j in range(col_size):\n # means it's same cell ([i][i]), so we already did it above\n if i == j:\n continue\n second_col = digits_line_by_line[:, j]\n sum_of_similar = 0\n for k in range(len(col)):\n if col[k] == second_col[k]:\n sum_of_similar += 1\n sum_of_different = len(col) - sum_of_similar\n weight = sum_of_similar - sum_of_different\n weight_matrix[i][j] = weight\n return weight_matrix\n\n\n# returns list of numbers in increasing order\ndef get_list_of_increasing_numbers(start: int, end: int):\n list_of_numbers: List[int] = []\n for i in range(start, end):\n list_of_numbers.append(i)\n return list_of_numbers\n\n\ndef update(weight_matrix, example):\n sum1 = 0\n list_of_numbers = get_list_of_increasing_numbers(0, len(example))\n copy_example = example.copy()\n while len(list_of_numbers) > 0:\n place: int = random.choice(list_of_numbers)\n list_of_numbers.remove(place)\n weight_column = weight_matrix[:, place]\n for i in range(len(weight_column)):\n if i != place:\n sum1 += weight_column[i] * copy_example[i]\n if sum1 >= 0:\n grade = 1\n else:\n grade = 0\n copy_example[place] = grade\n sum1 = 0\n\n return copy_example\n\n\n# change n percent of the array\ndef get_after_change_n_percent(arr, n=10):\n arr_copy = arr.copy()\n list_of_numbers = get_list_of_increasing_numbers(0, len(arr_copy))\n for _ in range(n):\n rand: int = random.choice(list_of_numbers)\n list_of_numbers.remove(rand)\n if arr_copy[rand] == 0:\n arr_copy[rand] = 1\n else:\n arr_copy[rand] = 0\n return arr_copy\n\n\ndef run_simulation(txt_filename, txt_prefect_digit, num_of_digits, number_of_runs, percent_to_pass_for_success, plot,\n mix_up_percent):\n digits_line_by_line = get_digits_from_txt(txt_filename, num_of_digits)\n\n perfect_digit = get_digits_from_txt(txt_prefect_digit, 1)[0]\n\n weight_matrix = get_weight_matrix(digits_line_by_line)\n\n digit_model = digits_line_by_line[0]\n digit_model = perfect_digit\n if plot:\n plt.imshow(digit_model.reshape(10, 10), aspect=\"auto\")\n plt.title(\"digit model\")\n plt.show()\n\n number_of_success = 0\n for _ in range(number_of_runs):\n digit_given = get_after_change_n_percent(digit_model, mix_up_percent)\n if plot:\n plt.imshow(digit_given.reshape(10, 10), aspect=\"auto\")\n plt.title(\"digit after mix up\")\n plt.show()\n digit_updated = update(weight_matrix, digit_given)\n # while not convergence\n while not (digit_updated == digit_given).all():\n digit_given = digit_updated\n digit_updated = update(weight_matrix, digit_given)\n if plot:\n plt.imshow(digit_updated.reshape(10, 10), aspect=\"auto\")\n plt.title(\"digit after update\")\n plt.show()\n total_matches = np.sum(digit_updated == digit_model)\n percent = (total_matches / len(digit_model)) * 100\n if percent >= percent_to_pass_for_success:\n number_of_success += 1\n\n success_rate = number_of_success / number_of_runs\n return success_rate * 100\n\n\ndef plot_3d_for_report(x, y, z):\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n # ax.scatter(x, y, z)\n ax.plot(x, y, z)\n plt.xlabel('number of letters', fontsize=10)\n plt.ylabel('mix upd percent', fontsize=10)\n ax.set_zlabel('success rate', fontsize=10)\n plt.show()\n\n\ndef get_txt_dig_name(method_index: int):\n return {\n 0: f'zero_perfect.txt',\n 1: f'one_perfect.txt',\n 2: f'two_perfect.txt',\n 3: f'three_perfect.txt',\n 4: f'four_perfect.txt',\n 5: f'five_perfect.txt',\n 6: f'six_perfect.txt',\n 7: f'seven_perfect.txt',\n 8: f'eight_perfect.txt',\n 9: f'nine_perfect.txt',\n }.get(method_index, 0)\n\n\ndef get_digit_to_find_from_user_input():\n while True:\n print('please choose digit you wish to play with')\n user_input = input()\n try:\n user_input = int(user_input)\n if user_input > 9 or user_input < 0:\n print('not valid digit')\n else:\n break\n except:\n print('please enter valid input 0-9')\n digit = get_txt_dig_name(user_input)\n return digit\n\n\ndef get_num_of_dig_from_user_input():\n while True:\n print('please how much different digits would you like to insert?')\n user_input = input()\n try:\n user_input = int(user_input)\n if user_input > 10 or user_input < 1:\n print('not valid number')\n else:\n break\n except:\n print('please enter valid input 1-10')\n amount = int(user_input)\n return amount\n\n\ndef get_plot_from_user_input():\n while True:\n print('would you like to view the digits output? 1-> yes, 0->no')\n user_input = input()\n try:\n user_input = int(user_input)\n if user_input > 1 or user_input < 0:\n print('not valid number')\n else:\n break\n except:\n print('please enter valid input 0/1')\n retval = False\n if user_input == 1:\n retval = True\n return retval\n\n\ndef main():\n txt_filename = '1_perfect_digit_of_each.txt'\n txt_prefect_digit = get_digit_to_find_from_user_input()\n # hyper parameters\n num_of_different_digits = get_num_of_dig_from_user_input()\n num_of_digits = num_of_different_digits\n number_of_runs = 100\n percent_to_pass_for_success = 90\n mix_up_percent = 10\n plot_digits = get_plot_from_user_input()\n\n success_rate = run_simulation(txt_filename, txt_prefect_digit, num_of_digits, number_of_runs,\n percent_to_pass_for_success, plot_digits,\n mix_up_percent)\n print('for %d letters, success rate: %d%%' % (num_of_different_digits, success_rate))\n\n print('press somethong to exit')\n input()\n\nif __name__ == '__main__':\n main()\n"} {"blob_id": "66ac7292e98626dfd4722b1644e8b5cb7e4ec8f9", "repo_name": "Mostafa-At-GitHub/Design_of_Computer_Programs", "path": "/Week3/decorated_tools.py", "length_bytes": 2061, "score": 3.625, "int_score": 4, "content": "from functools import update_wrapper\n\ndef decorator(d):\n \"\"\"Make function d a decorator: d wraps a function fn.\"\"\"\n def _d(fn):\n return update_wrapper(d(fn), fn)\n update_wrapper(_d, d)\n return _d\n\n# def decorator(d): # alternative definition\n# return lambda fn: update_wrapper(d(fn), fn)\n# decorator = decorator(decorator)\n\n@decorator\ndef memo(f):\n \"\"\"Decorator that caches the return value for each call to f(args).\n Then when called again with the same args, we can just look it up.\"\"\"\n cache = {}\n\n def _f(*args):\n try:\n return cache[args]\n except KeyError:\n cache[args] = result = f(*args)\n return result\n except TypeError:\n # some elements of args can't be a dict key\n return f(args)\n return _f\n\n\n@decorator\ndef count_calls(f):\n \"\"\"Decorator that makes the function count calls to it, in callcounts[f].\"\"\"\n def _f(*args):\n calls_count_map[_f] += 1\n return f(*args)\n calls_count_map[_f] = 0\n return _f\n\ncalls_count_map = {}\n\n\n@decorator\ndef trace(f):\n indent = ' '\n def _f(*args):\n signature = '%s(%s)' % (f.__name__, ', '.join(map(repr, args)))\n print('%s--> %s' % (trace.level*indent, signature))\n trace.level += 1\n try:\n result = f(*args)\n print('%s<-- %s == %s' % ((trace.level-1)*indent,\n signature, result))\n finally:\n trace.level -= 1\n return result\n trace.level = 0\n return _f\n\n\n\ndef disabled(f):\n \"\"\"Function to disable any decorator function\"\"\"\n return f\n# trace = disabled\n\n\n@count_calls\n@trace\n@memo\ndef fib(n):\n return 1 if n <= 1 else fib(n - 1) + fib(n - 2)\n\n\n# --------------------------------------------------- Testing ----------------------------------------------------------\n# print(\"n \\t fib(n) \\t calls\")\n# for n in range(31):\n# print(\"{} \\t {} \\t\\t {}\".format(n, fib(n), calls_count_map[fib]))\n# calls_count_map[fib] = 0\n\n\nprint(fib(30))\n"} {"blob_id": "97d543a5289db82c175e0dbcd2f6e07d6d556d80", "repo_name": "Nigirimeshi/leetcode", "path": "/0179_largest-number.py", "length_bytes": 1459, "score": 4.09375, "int_score": 4, "content": "\"\"\"\n\u6700\u5927\u6570\n\n\u94fe\u63a5\uff1ahttps://leetcode-cn.com/problems/largest-number\n\n\u7ed9\u5b9a\u4e00\u7ec4\u975e\u8d1f\u6574\u6570 nums\uff0c\u91cd\u65b0\u6392\u5217\u5b83\u4eec\u6bcf\u4e2a\u6570\u5b57\u7684\u987a\u5e8f\uff08\u6bcf\u4e2a\u6570\u5b57\u4e0d\u53ef\u62c6\u5206\uff09\u4f7f\u4e4b\u7ec4\u6210\u4e00\u4e2a\u6700\u5927\u7684\u6574\u6570\u3002\n\n\u6ce8\u610f\uff1a\u8f93\u51fa\u7ed3\u679c\u53ef\u80fd\u975e\u5e38\u5927\uff0c\u6240\u4ee5\u4f60\u9700\u8981\u8fd4\u56de\u4e00\u4e2a\u5b57\u7b26\u4e32\u800c\u4e0d\u662f\u6574\u6570\u3002\n\n\u793a\u4f8b 1\uff1a\n\n\u8f93\u5165\uff1anums = [10,2]\n\u8f93\u51fa\uff1a\"210\"\n\n\u793a\u4f8b 2\uff1a\n\u8f93\u5165\uff1anums = [3,30,34,5,9]\n\u8f93\u51fa\uff1a\"9534330\"\n\n\u793a\u4f8b 3\uff1a\n\u8f93\u5165\uff1anums = [1]\n\u8f93\u51fa\uff1a\"1\"\n\n\u793a\u4f8b 4\uff1a\n\u8f93\u5165\uff1anums = [10]\n\u8f93\u51fa\uff1a\"10\"\n\n\u63d0\u793a\uff1a\n1 <= nums.length <= 100\n0 <= nums[i] <= 109\n\n\n\u5b98\u65b9\u89e3\u6cd5\uff1a\n1. \u81ea\u5b9a\u4e49\u6392\u5e8f\u3002\n\u5148\u5c06\u6bcf\u4e2a\u6570\u5b57\u53d8\u6210\u5b57\u7b26\u4e32\uff0c\u7136\u540e\u6bd4\u8f83\u5b57\u7b26\u4e32\u6392\u5e8f\u3002\n\u6bd4\u8f83\u7684\u5173\u952e\u5728\u4e8e x + y \u548c y + x\u3002\n\n\u65f6\u95f4\u590d\u6742\u5ea6\uff1aO(NlogN)\n\u7a7a\u95f4\u590d\u6742\u5ea6\uff1aO(N)\n\n\"\"\"\nfrom typing import List\nimport unittest\n\n\nclass LargestNumKey(str):\n def __lt__(x, y):\n return x + y > y + x\n\n\nclass Solution:\n def largest_number(self, nums: List[int]) -> str:\n largest_num = ''.join(\n sorted(\n map(str, nums),\n key=LargestNumKey,\n )\n )\n return '0' if largest_num[0] == 0 else largest_num\n\n\nclass TestSolution(unittest.TestCase):\n def setUp(self) -> None:\n self.s = Solution()\n \n def test_largest_number(self) -> None:\n self.assertEqual(\n self.s.largest_number([10, 2]),\n '210',\n )\n\n\nif __name__ == '__main__':\n unittest.main()\n"} {"blob_id": "28fdb41bd93baec491f2ac920fa2c7a3c0160085", "repo_name": "PETAR-BOT/crossword", "path": "/crossword.py", "length_bytes": 17785, "score": 3.609375, "int_score": 4, "content": "# crossword class\n# crossword object creates an empty board with word bank and clues\n\n# nee to find a file w words and their definition -> (word: [definitions])\n# how to open all the json files in a folder and read all of them?\nimport re\nfrom pathlib import Path\nimport random\nimport string\nfrom collections import defaultdict\nimport pickle\n\nBLOCKCHAR = '#'\nOPENCHAR = '-'\nPROTECTEDCHAR = '~'\n\n\nclass Crossword:\n def __init__(self, vocab_file=r'vocab.pkl', width=5, height=5):\n \"\"\"\n :param vocab_file: string\n pickle file with words and meanings\n :param width: int\n width of board\n :param height: int\n height of board\n \"\"\"\n self.width = width\n self.height = height\n self.board = '-' * (width * height)\n self.blockct = int(width * height / 6)\n self.vocab = defaultdict(list)\n self.load_vocab(vocab_file)\n\n # make board\n empty_pos = [i for i in range(len(self.board))]\n self.board, num = self.place_blocks(self.board, 0, empty_pos)\n self.clean_protected()\n\n # solve puzzle\n self.patterns = dict()\n self.letter_count = {letter: 0 for letter in string.ascii_uppercase}\n self.make_patterns()\n self.down, self.across = self.find_word_pos(self.board)\n self.solved_board = self.solve_board(self.board, set(), self.down, self.across)\n\n # show puzzle\n self.get_game()\n self.get_answers()\n\n def load_vocab(self, path):\n path = Path(path)\n with open(path, mode='rb') as openedfile:\n self.vocab = pickle.load(openedfile)\n\n def save_vocab(self, path):\n path = Path(path)\n with open(path, mode='wb') as openedfile:\n self.vocab = pickle.dump(self.vocab, openedfile)\n\n def place_blocks(self, board, curr_blockct, empty_pos):\n \"\"\"\n places blockct of blocks on the board such that the board is symmetrical and no word is too short\n \"\"\"\n if curr_blockct == self.blockct: # if you have enough blocks, stop\n return board, curr_blockct\n if len(empty_pos) == 0: # if there are no more empty spaces, stop\n return board, curr_blockct\n # empty_pos.sort(key=lambda pos: self.pick_pos_heuristic(pos), reverse=True)\n empty_pos.sort(key=lambda pos: self.pick_pos_heuristic(pos, board), reverse=True)\n picked_pos = empty_pos[0]\n empty_pos.remove(picked_pos)\n board = board[0:picked_pos] + BLOCKCHAR + board[picked_pos + 1:]\n new_board, curr_blockct = self.block_helper(board) # get string with no border\n if curr_blockct > self.blockct:\n board = board[0:picked_pos] + OPENCHAR + board[picked_pos + 1:] # if too many blocks, remove prev block\n curr_blockct = board.count(BLOCKCHAR)\n else:\n new_board, curr_blockct = self.make_palindrome(new_board)\n # pass string with no border, new_board is a string with no border\n if curr_blockct > self.blockct:\n board = board[0:picked_pos] + OPENCHAR + board[picked_pos + 1:]\n curr_blockct = board.count(BLOCKCHAR)\n else:\n bordered = self.add_border(new_board)\n c = self.check_connected(bordered, self.width + 2, bordered.find(OPENCHAR), set())\n if c != len(new_board) - new_board.count(BLOCKCHAR):\n board = board[0:picked_pos] + OPENCHAR + board[picked_pos + 1:]\n curr_blockct = board.count(BLOCKCHAR)\n else:\n temp_pos = [z for z in empty_pos if new_board[z] == OPENCHAR]\n final_board, curr_blockct = self.place_blocks(new_board, curr_blockct, temp_pos)\n if curr_blockct == self.blockct:\n bordered = self.add_border(final_board)\n connected = self.check_connected(bordered, self.width + 2, bordered.find(OPENCHAR), set())\n if connected == len(final_board) - final_board.count(BLOCKCHAR):\n return final_board, curr_blockct\n else:\n board = board[0:picked_pos] + OPENCHAR + board[picked_pos + 1:]\n curr_blockct = board.count(BLOCKCHAR)\n else:\n board = board[0:picked_pos] + OPENCHAR + board[picked_pos + 1:]\n curr_blockct = board.count(BLOCKCHAR)\n empty_pos = [z for z in empty_pos if board[z] == OPENCHAR]\n return self.place_blocks(board, curr_blockct, empty_pos)\n\n def block_helper(self, board):\n xw = self.add_border(board)\n illegalRE = \"[#](.?[A-Z~]|[A-Z~].?)[#]\"\n newH = self.height + 2\n for c in range(2):\n if re.search(illegalRE, xw):\n return board, len(board)\n xw = self.transpose(xw, len(xw) // newH)\n newH = len(xw) // newH\n subRE = \"[{}]{}(?=[{}])\".format(BLOCKCHAR, OPENCHAR, BLOCKCHAR)\n subRE2 = \"[{}]{}{}(?=[{}])\".format(BLOCKCHAR, OPENCHAR, OPENCHAR, BLOCKCHAR)\n subRE3 = \"[#]-([A-Z~])-(?=[#])\"\n subRE4 = \"[#]--([A-Z~])(?=[#])\"\n subRE5 = \"[#]([A-Z~])--(?=[#])\"\n subRE6 = \"[#]([A-Z~][A-Z~])-(?=[#])\"\n subRE7 = \"[#]-([A-Z~][A-Z~])(?=[#])\"\n subRE8 = \"[#]([A-Z~])-([A-Z~])(?=[#])\"\n newH = len(xw) // (self.width + 2)\n for counter in range(2):\n xw = re.sub(subRE, BLOCKCHAR * 2, xw)\n xw = re.sub(subRE2, BLOCKCHAR * 3, xw)\n xw = re.sub(subRE3, r\"#~\\1~\", xw)\n xw = re.sub(subRE4, r\"#~~\\1\", xw)\n xw = re.sub(subRE5, r\"#\\1~~\", xw)\n xw = re.sub(subRE6, r\"#\\1~\", xw)\n xw = re.sub(subRE7, r\"#~\\1\", xw)\n xw = re.sub(subRE8, r\"#\\1~\\2\", xw)\n xw = self.transpose(xw, len(xw) // newH)\n newH = len(xw) // newH\n newboard = self.remove_border(xw)\n return newboard, newboard.count(BLOCKCHAR)\n\n def make_palindrome(self, board): # make board rotationally symmetrical\n new_board = board[::-1]\n new_board = re.sub(\"[A-Z]\", \"~\", new_board)\n return self.combine(board, new_board)\n\n def check_connected(self, board, width, index, visited):\n if index < 0 or index >= len(board):\n return 0\n if index in visited or board[index] == BLOCKCHAR:\n return 0\n visited.add(index)\n return 1 + self.check_connected(board, width, index - 1, visited) + \\\n self.check_connected(board, width, index - width, visited) + \\\n self.check_connected(board, width, index + 1, visited) + \\\n self.check_connected(board, width, index + width, visited)\n\n def add_border(self, board): # adds border to board\n xw = BLOCKCHAR * (self.width + 3)\n xw += (BLOCKCHAR * 2).join([board[p:p + self.width] for p in range(0, len(board), self.width)])\n xw += BLOCKCHAR * (self.width + 3)\n return xw\n\n def remove_border(self, board):\n newboard = ''\n for r in range(self.width + 2, len(board) - (self.width + 2), self.width + 2):\n newboard += board[r + 1: self.width + r + 1]\n return newboard\n\n def combine(self, board, new_board): # combines 2 boards together\n combined_board = '-' * len(board)\n for i in range(len(board)):\n a, b = board[i], new_board[i]\n if a == b:\n combined_board = combined_board[:i] + a + combined_board[i + 1:]\n elif a == OPENCHAR:\n combined_board = combined_board[:i] + b + combined_board[i + 1:]\n elif b == OPENCHAR:\n combined_board = combined_board[:i] + a + combined_board[i + 1:]\n elif ((a.isalpha() or a == PROTECTEDCHAR) and b == BLOCKCHAR) or (b == PROTECTEDCHAR and a == BLOCKCHAR):\n return board, len(board)\n elif a.isalpha() and b == PROTECTEDCHAR:\n combined_board = combined_board[:i] + a + combined_board[i + 1:]\n elif b == PROTECTEDCHAR and not a.isalpha():\n combined_board = combined_board[:i] + b + combined_board[i + 1:]\n else:\n combined_board = combined_board[:i] + a + combined_board[i + 1:]\n return combined_board, combined_board.count(BLOCKCHAR)\n\n def clean_protected(self):\n self.board = self.board.replace(PROTECTEDCHAR, OPENCHAR)\n\n def transpose(self, xw, newWidth):\n return ''.join([xw[col::newWidth] for col in range(newWidth)])\n\n def display_board(self, board):\n for i in range(self.height):\n for j in range(self.width):\n print(board[i * self.width + j], end=\" \")\n print()\n\n def display_board_in_file(self, board, file):\n for i in range(self.height):\n for j in range(self.width):\n print(board[i * self.width + j], end=\" \", file=file)\n print('\\n', file=file)\n\n def make_patterns(self):\n for word in self.vocab:\n word = word.upper()\n key = '-' * len(word)\n if key not in self.patterns:\n self.patterns[key] = {word}\n else:\n words = self.patterns[key]\n words.add(word)\n self.patterns[key] = words\n for pos in range(len(word)):\n new_key = key[:pos] + word[pos] + key[pos + 1:]\n if new_key not in self.patterns:\n self.patterns[new_key] = {word}\n else:\n words = self.patterns[new_key]\n words.add(word)\n self.patterns[new_key] = words\n self.letter_count[word[pos]] += 1\n\n def find_word_pos(self, board):\n down = dict()\n across = dict()\n for pos in range(len(board)):\n if board[pos] != '#' and (pos % self.width == 0 or board[pos - 1] == '#'):\n pattern, a = board[pos], pos + 1\n while a < pos + self.width - pos % self.width and board[a] != '#':\n pattern += board[a]\n a += 1\n across[pos] = pattern\n if board[pos] != '#' and (pos < self.width or board[pos - self.width] == '#'):\n pattern, a = board[pos], pos + self.width\n while a < len(board) and board[a] != '#':\n pattern += board[a]\n a += self.width\n down[pos] = pattern\n return down, across\n\n def solve_board(self, board, used, down, across):\n \"\"\"\n fill board in with words from vocab, save their positions, direction, and definition\n :return:\n \"\"\"\n # if board is full, check that all words in board are real words (ie in the vocab)\n # if a word is not a real word, return none; if all words are real, return board\n # find position w/ pattern easiest to fill in (has the fewest possibilities, or already partially filled)\n # find words that can fit that pattern, choose the most likely to be used (common word? common letter?)\n # for every possible word, place it in the board and recur\n if '-' not in board:\n for word in down.values():\n if word not in self.vocab:\n return None\n for word in across.values():\n if word not in self.vocab:\n return None\n return board\n pattern, index, possible_words = self.most_constrained_pattern(down, across)\n possible_words = list(set(possible_words) - set(used))\n possible_words.sort(key=self.heuristic, reverse=True)\n for word in possible_words:\n new_board = self.add_word(board, word, index)\n new_used_words = used.copy()\n new_used_words.add(word)\n new_down, new_across = self.find_word_pos(new_board)\n if index[1] == 'D':\n words = self.new_words(across, new_across)\n else:\n words = self.new_words(down, new_down)\n bad_board = False\n for pos in words:\n pat = words[pos]\n if '-' not in pat:\n if pat in used or pat not in self.vocab:\n bad_board = True\n break\n else:\n new_used_words.add(pat)\n else:\n if index[1] == \"A\":\n word_list = self.get_possible_words(pat, (pos % self.width + index[0] - pos) // self.width)\n else:\n word_list = self.get_possible_words(pat, index[0] + (pos // self.width - index[0] // self.width) * self.width - pos)\n word_list = list(set(word_list) - set(new_used_words))\n if len(word_list) == 0:\n bad_board = True\n break\n if bad_board:\n continue\n else:\n newBoard = self.solve_board(new_board, new_used_words, new_down, new_across)\n if newBoard is not None:\n return newBoard\n return None\n\n def heuristic(self, word):\n val = 0\n for letter in word:\n if letter in self.letter_count:\n val += self.letter_count[letter]\n return val\n\n def most_constrained_pattern(self, down, across):\n words = None\n pattern, index = '', (-1, 'x')\n for pos in down:\n pat = down[pos]\n if pat.count('-') != 0:\n possible_words = self.get_possible_words(pat)\n if words is None or len(possible_words) <= len(words):\n words = possible_words\n pattern, index = pat, (pos, \"D\")\n for pos in across:\n pat = across[pos]\n if pat.count('-') != 0:\n possible_words = self.get_possible_words(pat)\n if words is None or len(possible_words) <= len(words):\n words = possible_words\n pattern, index = pat, (pos, \"A\")\n return pattern, index, words\n\n def get_possible_words(self, pattern, new_pos=-1):\n if pattern in self.patterns or new_pos == -1:\n return self.patterns[pattern]\n elif len(pattern.strip('-')) == 1:\n return set()\n else:\n new_pat = '-' * new_pos + pattern[new_pos] + '-' * (len(pattern) - new_pos - 1)\n if new_pat in self.patterns:\n new_words = self.patterns[new_pat]\n else:\n new_words = set()\n old_words = self.patterns[pattern[:new_pos] + '-' + pattern[new_pos + 1:]]\n possible_words = new_words & old_words\n self.patterns[pattern] = possible_words\n return possible_words\n\n def add_word(self, board, word, index):\n if index[1] == 'A':\n start = index[0]\n board = board[:start] + word + board[start + len(word):]\n else:\n start = index[0]\n for i in range(len(word)):\n pos = start + i * self.width\n board = board[:pos] + word[i] + board[pos + 1:]\n return board\n\n def new_words(self, old, new):\n words = dict()\n for key in old:\n if new[key] != old[key]:\n words[key] = new[key]\n return words\n\n def get_game(self):\n \"\"\"\n makes a file with the clean generated board and words/clues\n :return:\n \"\"\"\n f = open('crossword.txt', 'w')\n self.display_board_in_file(self.board, f)\n print(\"DOWN\", file=f)\n self.down, self.across = self.find_word_pos(self.solved_board)\n for pos in self.down:\n print(pos, ': ', random.choice(self.vocab[self.down[pos]]), end='\\n', file=f)\n print(\"ACROSS\", file=f)\n for pos in self.across:\n print(pos, ': ', random.choice(self.vocab[self.across[pos]]), end='\\n', file=f)\n print(\"Game ready\")\n f.close()\n\n def get_answers(self):\n f = open('answers.txt', 'w')\n print(\"DOWN\", file=f)\n self.down, self.across = self.find_word_pos(self.solved_board)\n for pos in self.down:\n print(pos, ': ', self.down[pos], end='\\n', file=f)\n print(\"ACROSS\", file=f)\n for pos in self.across:\n print(pos, ': ', self.across[pos], end='\\n', file=f)\n f.close()\n\n def pick_pos_heuristic(self, pos, board):\n pos_row, pos_col = pos // self.width, pos % self.width\n up, down, left, right = -1, -1, -1, -1\n next_block = board.find('#')\n while next_block > 0:\n nb_row, nb_col = next_block // self.width, next_block % self.width\n if nb_col == pos_col:\n if nb_row < pos_row:\n up = pos_row - nb_row - 1\n else:\n down = nb_row - pos_row - 1\n elif nb_row == pos_row:\n if nb_col > pos_col:\n right = nb_col - pos_col - 1\n else:\n left = pos_col - nb_col - 1\n else:\n if up == -1: up = pos_row\n if down == -1: down = len(board) // self.width - pos_row - 1\n if left == -1: left = pos_col\n if right == -1: right = self.width - pos_col - 1\n next_block = board.find('#', next_block + 1)\n if up == -1: up = pos_row\n if down == -1: down = len(board) // self.width - pos_row - 1\n if left == -1: left = pos_col\n if right == -1: right = self.width - pos_col - 1\n return left * right + up * down\n"} {"blob_id": "95d9e4316d5e750b59494ec85fe388cd45fbe118", "repo_name": "Dawyer/Code", "path": "/problems/LeetCode/LeetCode365. \u6c34\u58f6\u95ee\u9898.py", "length_bytes": 1547, "score": 3.875, "int_score": 4, "content": "# \u6709\u4e24\u4e2a\u5bb9\u91cf\u5206\u522b\u4e3a x\u5347 \u548c y\u5347 \u7684\u6c34\u58f6\u4ee5\u53ca\u65e0\u9650\u591a\u7684\u6c34\u3002\u8bf7\u5224\u65ad\u80fd\u5426\u901a\u8fc7\u4f7f\u7528\u8fd9\u4e24\u4e2a\u6c34\u58f6\uff0c\u4ece\u800c\u53ef\u4ee5\u5f97\u5230\u6070\u597d z\u5347 \u7684\u6c34\uff1f\n#\n# \u5982\u679c\u53ef\u4ee5\uff0c\u6700\u540e\u8bf7\u7528\u4ee5\u4e0a\u6c34\u58f6\u4e2d\u7684\u4e00\u6216\u4e24\u4e2a\u6765\u76db\u653e\u53d6\u5f97\u7684 z\u5347 \u6c34\u3002\n#\n# \u4f60\u5141\u8bb8\uff1a\n#\n# \u88c5\u6ee1\u4efb\u610f\u4e00\u4e2a\u6c34\u58f6\n# \u6e05\u7a7a\u4efb\u610f\u4e00\u4e2a\u6c34\u58f6\n# \u4ece\u4e00\u4e2a\u6c34\u58f6\u5411\u53e6\u5916\u4e00\u4e2a\u6c34\u58f6\u5012\u6c34\uff0c\u76f4\u5230\u88c5\u6ee1\u6216\u8005\u5012\u7a7a\n# \u793a\u4f8b 1: (From the famous \"Die Hard\" example)\n#\n# \u8f93\u5165: x = 3, y = 5, z = 4\n# \u8f93\u51fa: True\n# \u793a\u4f8b 2:\n#\n# \u8f93\u5165: x = 2, y = 6, z = 5\n# \u8f93\u51fa: False\nimport math\n#\u6df1\u5ea6\u4f18\u5148\u641c\u7d22\n# def canMeasureWater(x:int,y:int,z:int) -> bool:\n# stack=[(0,0)]\n# seen=set()\n# while stack:\n# remain_x,remain_y = stack.pop()\n# if remain_x == z or remain_y == z or remain_x+remain_y == z:\n# return True\n# if(remain_x,remain_y) in seen:\n# continue\n# seen.add((remain_x,remain_y))\n# stack.append((x,remain_y))\n# stack.append((remain_x,y))\n# stack.append((0,remain_y))\n# stack.append((remain_x,0))\n#\n# stack.append((remain_x - min(remain_x,y-remain_y),remain_y + min(remain_x,y - remain_y)))\n# stack.append((remain_x + min(remain_y,x-remain_x),remain_y - min(remain_y,x - remain_x)))\n# return False\n\n#\u6700\u5927\u516c\u7ea6\u6570\ndef canMeasureWater(x,y,z) -> bool:\n if x+y 0:\n # Load file to an array.\n word_json = json.loads(word_text)\n word_list = word_json[\"array\"]\n # Get word from user. \n word = input(\"What name are we looking for? \")\n # Run word search function.\n advanced_search(word_list, word)"} {"blob_id": "1801c12b1078e9ee15ddfd5c33e574e4bc7bccf7", "repo_name": "CuriousG102/stay-in-your-lane", "path": "/prediction.py", "length_bytes": 3675, "score": 3.8125, "int_score": 4, "content": "import enum\nimport math\n\nimport numpy as np\nimport track_floor_utils\n\nCAR_AXLE_FRONT = .127\nCAR_AXLE_BACK = - .16\nCAR_LENGTH = abs(CAR_AXLE_BACK) + abs(CAR_AXLE_FRONT)\n\nclass Circle:\n class CircleSide(enum.Enum):\n LEFT = 1\n RIGHT = 2\n def __init__(self, radius, side):\n self.radius = radius\n self.side = side\n\nclass Line:\n pass\n\ndef telemetry_for_steering_pure(s_angle):\n '''\n Returns a relative representation of the car's path if it continues at \n a given\n speed and s_angle indefinitely. This representation can take the form of\n objects of two different types: Circle and Line. Line simply represents\n that the car will remain travelling straight. Circle shows that, given \n enough time in the current configuration, the car will travel in a circle\n of radius radius. Side on the circle represents the starting point of the \n car. LEFT means that that the first derivative of theta is negative and the\n car is considered to start at theta=pi. \n RIGHT means that the first derivative\n of theta is positive and the car is considered to start at theta=0. \n '''\n s_angle_original = s_angle\n s_angle = math.radians(abs(s_angle))\n\n if abs(s_angle_original) <= 0.1:\n return Line()\n\n radius = CAR_LENGTH / math.tan(s_angle)\n side = (Circle.CircleSide.LEFT \n if s_angle_original > 0 \n else Circle.CircleSide.RIGHT)\n\n return Circle(radius, side)\n\ndef telemetry_after_delta_time_pure(speed, s_angle, pos, rot_y, delta_time):\n ''' \n Returns a single point prediction of where a car will end up in a global coordinate space\n given speed, steering angle, position, and rotation of the car in that space, after a time \n delta_time. The prediction is returned as a tuple containing a tuple and a float:\n ((predicted_x, predicted_z,), predicted_rot_y,)\n '''\n x, z = pos\n rot_y = math.radians(rot_y)\n s_angle_original = s_angle\n s_angle = math.radians(s_angle) \n\n d = -CAR_AXLE_BACK + CAR_AXLE_FRONT\n initial_back_x = x + math.sin(rot_y) * CAR_AXLE_BACK\n initial_back_z = z + math.cos(rot_y) * CAR_AXLE_BACK\n\n if abs(s_angle_original) > 0.1:\n final_back_x = (\n d * 1 / math.tan(s_angle) \n * (math.cos(rot_y - speed * delta_time * math.tan(s_angle) / d) \n - math.cos(rot_y)) * .1\n + x)\n final_back_z = (\n d * 1 / math.tan(s_angle) \n * (math.sin(rot_y) \n - math.sin(rot_y - speed * delta_time * math.tan(s_angle) / d)) * .1\n + z)\n final_rot_y = math.tan(s_angle) / d * speed * delta_time + rot_y\n\n else:\n delta_back_x = speed * delta_time * math.sin(rot_y)\n final_back_x = initial_back_x + delta_back_x\n delta_back_z = speed * delta_time * math.cos(rot_y)\n final_back_z = initial_back_z + delta_back_z\n delta_rot_y = 0\n final_rot_y = rot_y + delta_rot_y\n\n final_pos = (final_back_x + abs(CAR_AXLE_BACK) * math.sin(final_rot_y),\n final_back_z + abs(CAR_AXLE_BACK) * math.cos(final_rot_y),)\n\n return (final_pos, np.rad2deg(final_rot_y))\n\ndef telemetry_after_delta_time(telemetry, pos, rot_y, delta_time):\n '''\n Returns ((x, z), rot_y) predicted on track floor after delta time.\n\n Takes:\n t: Telemetry\n x: Known or guessed position of car\n z: Known or guessed position of car\n rot_y: Known or guessed rotation of car on y axis\n delta_time: Amount of time that passes while producing our estimate.\n '''\n \n return telemetry_after_delta_time_pure(\n telemetry.speed, telemetry.steering, pos, rot_y, delta_time)\n"} {"blob_id": "644d713a70616bdd1bf96fc7b5d3ec57b0b70320", "repo_name": "miniyk2012/leetcode", "path": "/leetcode_projects/leetcode_307/solution.py", "length_bytes": 705, "score": 3.5, "int_score": 4, "content": "from typing import List\r\n\r\nfrom leetcode_projects.data_structs import FenwickTree\r\n\r\n\r\nclass NumArray:\r\n\r\n def __init__(self, nums: List[int]):\r\n self.nums = nums\r\n self.tree = FenwickTree(len(nums))\r\n for i, val in enumerate(nums):\r\n self.tree.update(i + 1, val)\r\n\r\n def update(self, i: int, val: int) -> None:\r\n self.tree.update(i + 1, val - self.nums[i])\r\n self.nums[i] = val\r\n\r\n def sumRange(self, i: int, j: int) -> int:\r\n return self.tree.query(j + 1) - self.tree.query(i)\r\n\r\n\r\ndef test():\r\n nums = [1, 3, 5]\r\n obj = NumArray(nums)\r\n assert obj.sumRange(0, 2) == 9\r\n obj.update(1, 2)\r\n assert obj.sumRange(0, 2) == 8\r\n\r\n\r\n"} {"blob_id": "06bf46704dc016f452616554f8e654aa7c09db43", "repo_name": "lim1202/LeetCode", "path": "/Tree/recover_binary_search_tree.py", "length_bytes": 1576, "score": 3.8125, "int_score": 4, "content": "\"\"\"Recover Binary Search Tree\n\nTwo elements of a binary search tree (BST) are swapped by mistake.\nRecover the tree without changing its structure.\n\nNote:\n A solution using O(n) space is pretty straight forward.\n Could you devise a constant space solution?\n\"\"\"\nfrom binarytree import build\n\n\ndef recover_tree(root):\n \"\"\"Recover the binary search tree\"\"\"\n found = False\n pre_cur = None\n pre1 = None\n pre2 = None\n\n if root is None:\n return\n\n cur = root\n while cur is not None:\n if cur.left is None:\n if pre_cur and pre_cur.value > cur.value:\n if not found:\n pre1 = pre_cur\n found = True\n pre2 = cur\n\n pre_cur = cur\n cur = cur.right\n else:\n pre = cur.left\n while pre.right and pre.right.value != cur.value:\n pre = pre.right\n if pre.right is None:\n pre.right = cur\n cur = cur.left\n else:\n if pre_cur.value > cur.value:\n if not found:\n pre1 = pre_cur\n found = True\n pre2 = cur\n pre_cur = cur\n pre.right = None\n cur = cur.right\n\n if pre1 and pre2:\n temp = pre1.value\n pre1.value = pre2.value\n pre2.value = temp\n\n return\n\nif __name__ == \"__main__\":\n my_tree = build([4, 2, 7, 1, 3, 6, 5])\n print(my_tree)\n recover_tree(my_tree)\n print(my_tree)\n"} {"blob_id": "b7562b42d5ec5f67f96ca44118108160869005b5", "repo_name": "WeizhengZhou/leetcodepy", "path": "/permutation_sequence.py", "length_bytes": 990, "score": 3.671875, "int_score": 4, "content": "\n\nclass Solution(object):\n \"\"\"\n >>> solution = Solution()\n \"\"\"\n\n def getPermutation(self, n, k):\n if n <= 0:\n return ''\n if n == 1:\n return '1'\n\n facts = self.factorial(n)\n k -= 1\n\n used = [False,] * n\n res = [0,] * n\n for i in range(n-1):\n rank = k / facts[i+1]\n j = 0\n for j in range(n):\n if used[j]:\n continue\n else:\n rank -= 1\n if rank < 0:\n used[j] = True\n res[i] = (j + 1)\n break\n k = k % facts[i+1]\n\n i = n -1\n rank = 0\n j = 0\n for j in range(n):\n if not used[j]:\n res[i] = (j + 1)\n break\n return ''.join([str(r) for r in res])\n\n\n def factorial(self, n):\n if n <= 0:\n return []\n\n res = [1,] * n\n\n for i in range(1, len(res)):\n res[i] = res[i-1] * (i + 1)\n\n return res[::-1] # Reversed.\n\n\nif __name__ == '__main__':\n s = Solution()\n print s.getPermutation(3, 6)\n # import doctest\n # doctest.testmod()\n"} {"blob_id": "0cd1daf18969c117c4640b84934c05089f0bfc1c", "repo_name": "SaiSudhaV/coding_platforms", "path": "/inorder.py", "length_bytes": 496, "score": 3.765625, "int_score": 4, "content": "# 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\nclass Solution:\n # @param A : list of integers\n # @return the root node in the tree\n def buildTree(self, A):\n if A:\n root, high_index = TreeNode(max(A)), A.index(max(A))\n root.left, root.right = self.buildTree(A[:high_index]), self.buildTree(A[high_index + 1:])\n return root\n return None"} {"blob_id": "2aafb31c282a774e14c52a8b3df691d86cd8600b", "repo_name": "egreenius/ai.algorithms_python", "path": "/lesson_8/les_8_hw_2.py", "length_bytes": 4132, "score": 3.765625, "int_score": 4, "content": "\"\"\"\n2. \u0414\u043e\u0440\u0430\u0431\u043e\u0442\u0430\u0442\u044c \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u0414\u0435\u0439\u043a\u0441\u0442\u0440\u044b (\u0440\u0430\u0441\u0441\u043c\u0430\u0442\u0440\u0438\u0432\u0430\u043b\u0441\u044f \u043d\u0430 \u0443\u0440\u043e\u043a\u0435), \u0447\u0442\u043e\u0431\u044b \u043e\u043d \u0434\u043e\u043f\u043e\u043b\u043d\u0438\u0442\u0435\u043b\u044c\u043d\u043e \u0432\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u043b \u0441\u043f\u0438\u0441\u043e\u043a \u0432\u0435\u0440\u0448\u0438\u043d,\n\u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u043d\u0435\u043e\u0431\u0445\u043e\u0434\u0438\u043c\u043e \u043e\u0431\u043e\u0439\u0442\u0438.\n\"\"\"\nfrom collections import deque\n\n\ng = [\n [0, 0, 1, 1, 9, 0, 0, 0],\n [0, 0, 9, 4, 0, 0, 5, 0],\n [0, 9, 0, 0, 3, 0, 6, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 1, 0],\n [0, 0, 0, 0, 0, 0, 5, 0],\n [0, 0, 7, 0, 8, 1, 0, 0],\n [0, 0, 0, 0, 0, 1, 2, 0],\n]\n\n\ndef dijkstra(graph, start):\n length = len(graph)\n is_visited = [False] * length # \u0432 \u0441\u043f\u0438\u0441\u043a\u0435 \u0431\u0443\u0434\u0435\u043c \u0445\u0440\u0430\u043d\u0438\u0442\u044c \u0438\u043d\u0444\u043e\u0440\u043c\u0430\u0446\u0438\u044e, \u043f\u043e\u0441\u0435\u0449\u0430\u043b\u0438 \u043c\u044b \u0432\u0435\u0440\u0448\u0438\u043d\u0443 \u0438\u043b\u0438 \u043d\u0435\u0442\n cost = [float('inf')] * length # \u0432 \u044d\u0442\u043e\u043c \u0441\u043f\u0438\u0441\u043a\u0435 \u0441\u0442\u043e\u0438\u043c\u043e\u0441\u0442\u044c \u043f\u0443\u0442\u0438, \u043f\u043e\u043a\u0430 \u043b\u0435\u0436\u0438\u0442 \u0431\u0435\u0441\u043a\u043e\u043d\u0435\u0447\u043d\u043e\u0441\u0442\u044c\n parent = [-1] * length # \u043f\u043e\u043a\u0430 \u043d\u0435 \u0437\u043d\u0430\u0435\u043c \u0440\u043e\u0434\u0438\u0442\u0435\u043b\u044f \u0432\u0435\u0440\u0448\u0438\u043d\u044b \u0442\u043e -1, \u0430 \u043a\u043e\u0433\u0434\u0430 \u0443\u0437\u043d\u0430\u0435\u043c \u0431\u0443\u0434\u0435\u043c \u0437\u0430\u043f\u0438\u0441\u044b\u0432\u0430\u0442\u044c \u0440\u043e\u0434\u0438\u0442\u0435\u043b\u044f - \u043d\u043e\u043c\u0435\u0440 \u0432\u0435\u0440\u0448\u0438\u043d\u044b\n\n cost[start] = 0 # \u0441\u0442\u043e\u0438\u043c\u043e\u0441\u0442\u044c \u0434\u043e \u0432\u0435\u0440\u0448\u0438\u043d\u044b \u0441 \u043a\u043e\u0442\u043e\u0440\u043e\u0439 \u043d\u0430\u0447\u0438\u043d\u0430\u0435\u043c = 0\n min_cost = 0 # \u0437\u0434\u0435\u0441\u044c \u0431\u0443\u0434\u0435\u043c \u0445\u0440\u0430\u043d\u0438\u0442\u044c \u043c\u0438\u043d\u0438\u043c\u0430\u043b\u044c\u043d\u0443\u044e \u0441\u0442\u043e\u0438\u043c\u043e\u0441\u0442\u044c. \u0411\u0443\u0434\u0435\u0442 \u043f\u043e\u043a\u0430\u0437\u044b\u0432\u0430\u0442\u044c \u0434\u0432\u0438\u0433\u0430\u0435\u043c\u0441\u044f \u043c\u044b \u043f\u043e \u0433\u0440\u0430\u0444\u0443 \u0438\u043b\u0438 \u0443\u0436\u0435 \u043d\u0435\u0442\n start_way = start # \u0441\u043e\u0445\u0440\u0430\u043d\u0438\u043c \u043d\u0430\u0447\u0430\u043b\u044c\u043d\u043e\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 \u0432\u0435\u0440\u0448\u0438\u043d\u044b, \u0441 \u043a\u043e\u0442\u043e\u0440\u043e\u0439 \u043d\u0430\u0447\u0438\u043d\u0430\u0435\u043c \u043e\u0431\u0445\u043e\u0434\n\n while min_cost < float('inf'): # \u0431\u0430\u0437\u043e\u0432\u044b\u0439 \u0446\u0438\u043a\u043b \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u0430 \u0414\u0435\u0439\u043a\u0441\u0442\u0440\u044b\n\n is_visited[start] = True # \u0441\u0442\u0430\u0440\u0442\u043e\u0432\u0430\u044f \u0432\u0435\u0440\u0448\u0438\u043d\u0430 \u044f\u0432\u043b. \u043f\u043e\u0441\u0435\u0449\u0435\u043d\u043d\u043e\u0439\n\n for i, vertex in enumerate(graph[start]): # \u043f\u0440\u043e\u0439\u0434\u0435\u043c\u0441\u044f \u043c\u0430\u0442\u0440\u0438\u0446\u0435 \u0441\u043c\u0435\u0436\u043d\u043e\u0441\u0442\u0438 \u0432\u0435\u0440\u0448\u0438\u043d\u044b, \u0441 \u043a\u043e\u0442\u043e\u0440\u043e\u0439 \u043d\u0430\u0447\u0430\u043b\u0438\n if vertex != 0 and not is_visited[i]: # \u043d\u0430 \u043c\u043e\u0439 \u0432\u0437\u0433\u043b\u044f\u0434 \u0438\u043c\u0435\u043d\u0430 \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u044b\u0445 \u043d\u0435 \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0443\u044e\u0442 \u0444\u0430\u043a\u0442\u0443,\n # \u043d\u043e \u043c\u0435\u043d\u044f\u0442\u044c \u043d\u0435 \u0441\u0442\u0430\u043b\n\n if cost[i] > vertex + cost[start]:\n cost[i] = vertex + cost[start]\n parent[i] = start # \u0437\u0430\u043f\u0438\u0448\u0435\u043c \u0440\u043e\u0434\u0438\u0442\u0435\u043b\u0435\u0439, \u0434\u043b\u044f \u043a\u0430\u0436\u0434\u043e\u0439 \u0440\u0430\u0441\u0441\u043c\u043e\u0442\u0440\u0435\u043d\u043d\u043e\u0439 \u0432\u0435\u0440\u0448\u0438\u043d\u044b. \u0417\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u043c\u043e\u0433\u0443\u0442 \u043c\u0435\u043d\u044f\u0442\u044c\u0441\u044f\n # \u043f\u043e \u0445\u043e\u0434\u0443 \u0434\u0432\u0438\u0436\u0435\u043d\u0438\u044f \u043f\u043e \u043e\u0431\u0449\u0435\u043c\u0443 \u0446\u0438\u043a\u043b\u0443\n\n min_cost = float('inf')\n for i in range(length):\n if min_cost > cost[i] and not is_visited[i]:\n min_cost = cost[i]\n start = i # \u0437\u0434\u0435\u0441\u044c \u0432\u0441\u044f \u043c\u0430\u0433\u0438\u044f. \u043f\u0435\u0440\u0435\u043c\u0435\u0449\u0430\u0435\u043c \u043d\u0430\u0447\u0430\u043b\u043e \u043e\u0431\u0445\u043e\u0434\u0430 \u043d\u0430 \u043d\u043e\u0432\u0443\u044e \u0432\u0435\u0440\u0448\u0438\u043d\u0443\n\n \"\"\" \u0417\u0434\u0435\u0441\u044c \u043d\u0430\u0447\u0438\u043d\u0430\u0435\u0442\u0441\u044f \u0434\u043e\u0440\u0430\u0431\u043e\u0442\u043a\u0430 \u043f\u043e \u0437\u0430\u0434\u0430\u043d\u0438\u044e. \u0418\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0435\u043c \u0441\u043f\u0438\u0441\u043e\u043a parent, \u0432 \u043d\u0435\u043c \u0435\u0441\u0442\u044c \u0432\u0441\u044f \u043d\u0443\u0436\u043d\u0430\u044f \u043d\u0430\u043c \u0438\u043d\u0444\u043e\u0440\u043c\u0430\u0446\u0438\u044f\"\"\"\n way = [None] * length # \u0437\u0434\u0435\u0441\u044c \u0431\u0443\u0434\u0435\u043c \u0445\u0440\u0430\u043d\u0438\u0442\u044c \u043f\u0443\u0442\u044c \u043a \u0432\u0435\u0440\u0448\u0438\u043d\u0430\u043c\n way_cost = {} # \u0432 \u0441\u043b\u043e\u0432\u0430\u0440\u0435 \u0431\u0443\u0434\u0435\u043c \u0445\u0440\u0430\u043d\u0438\u0442\u044c \u0432\u0435\u0440\u0448\u0438\u043d\u0443 \u0438 \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0443\u044e\u0449\u0438\u0435 \u0435\u0439 \u043f\u0443\u0442\u044c \u0438 \u0441\u0442\u043e\u0438\u043c\u043e\u0441\u0442\u044c\n for i in range(length): # \u0446\u0438\u043a\u043b \u043e\u0431\u0445\u043e\u0434\u0430 \u043f\u043e \u0441\u043f\u0438\u0441\u043a\u0443 parent\n way[i] = deque()\n if cost[i] == float('inf'):\n way[i].appendleft('\u041d\u0435\u0442 \u043c\u0430\u0440\u0448\u0440\u0443\u0442\u0430')\n else:\n way[i].appendleft(i)\n if parent[i] == -1:\n way_cost[i] = way[i], cost[i]\n continue\n j = i\n while parent[j] != start_way:\n way[i].appendleft(parent[j])\n j = parent[j]\n else:\n way[i].appendleft(start_way)\n way_cost[i] = way[i], cost[i]\n return way_cost\n\n\ns = int(input('\u041e\u0442 \u043a\u0430\u043a\u043e\u0439 \u0432\u0435\u0440\u0448\u0438\u043d\u044b \u0438\u0434\u0442\u0438: '))\nway_cost = dijkstra(g, s)\nprint(f'\u0422\u043e\u0447\u043a\u0430 \u0441\u0442\u0430\u0440\u0442\u0430 {s}')\nprint('\u0414\u043b\u0438\u043d\u0430 \u043f\u0443\u0442\u0438 \u0438 \u043c\u0430\u0440\u0448\u0440\u0443\u0442 \u0434\u043e \u0432\u0435\u0440\u0448\u0438\u043d:')\nfor key, value in way_cost.items():\n print(f'{key}: \u0434\u043b\u0438\u043d\u0430 \u043f\u0443\u0442\u0438: {value[1]},\\t \u043c\u0430\u0440\u0448\u0440\u0443\u0442: {list(value[0])}')\n\n# {1: [4, 6, 2, 1], 2: [4, 6, 2], 3: [4, 6, 2, 1, 3], 5: [4, 6, 5], 6: [4, 6]}"} {"blob_id": "5239cf3f87e79c606e9489a6858e22dc3b1d4a05", "repo_name": "gotgotaind/aind-sudoku", "path": "/solution.py", "length_bytes": 9256, "score": 3.5, "int_score": 4, "content": "import traceback\nimport logging\nimport re\n\nassignments = []\n\n\nrows = 'ABCDEFGHI'\ncols = '123456789'\n\ndef cross(a, b):\n return [s+t for s in a for t in b]\n\nboxes = cross(rows, cols)\n\nrow_units = [cross(r, cols) for r in rows]\ncolumn_units = [cross(rows, c) for c in cols]\nsquare_units = [cross(rs, cs) for rs in ('ABC','DEF','GHI') for cs in ('123','456','789')]\ndiagonal_units=[[rows[i]+cols[i] for i in range(9)],[rows[8-i]+cols[i] for i in range(9)]]\n \nunitlist = row_units + column_units + square_units + diagonal_units\nunits = dict((s, [u for u in unitlist if s in u]) for s in boxes)\npeers = dict((s, set(sum(units[s],[]))-set([s])) for s in boxes)\n\n\ndef assign_value(values, box, value):\n \"\"\"\n Please use this function to update your values dictionary!\n Assigns a value to a given box. If it updates the board record it.\n \"\"\"\n values[box] = value\n if len(value) == 1:\n assignments.append(values.copy())\n return values\n\ndef naked_twins(values):\n \"\"\"Eliminate values using the naked twins strategy.\n Args:\n values(dict): a dictionary of the form {'box_name': '123456789', ...}\n\n Returns:\n the values dictionary with the naked twins eliminated from peers.\n \"\"\"\n\n # Find all instances of naked twins\n # Eliminate the naked twins as possibilities for their peers\n \n for unit in unitlist:\n for box1 in unit:\n if len(values[box1])==2:\n #search for another box with the same possible values\n for box2 in unit:\n if ((box1!=box2) and (values[box1]==values[box2])):\n #removes the twin values from all other box in the unit\n for box3 in unit:\n if ((box3!=box1) and (box3!=box2)):\n box3_v=values[box3]\n box1_v=values[box1]\n #not necessary but easier to check the algo is working as intented\n if ( re.search(box1_v[0],box3_v) or re.search(box1_v[1],box3_v) ):\n box3_nv=box3_v\n box3_nv=box3_nv.replace(box1_v[0],'')\n box3_nv=box3_nv.replace(box1_v[1],'')\n assign_value(values, box3, box3_nv)\n pass\n return(values)\n \ndef naked_tuples(values):\n \"\"\"Eliminate values using the naked tuples strategy.\n Args:\n values(dict): a dictionary of the form {'box_name': '123456789', ...}\n\n Returns:\n the values dictionary with the naked tuples eliminated from peers.\n \"\"\"\n \n for unit in unitlist:\n \n # for each unit, build a reverse dictionary of the list of boxes\n # having the same possible values\n rev_val=dict()\n for box in unit:\n v_box=values[box]\n \n # If the 'list of possible values' is already a key, append the box\n # to the existing list,\n # else initialize a new list\n if v_box in rev_val.keys():\n rev_val[v_box].append(box)\n else:\n rev_val[v_box]=[box]\n pass\n \n for tuple_v,tuple_box_list in rev_val.items():\n \n #if there are as many possibles values as the number of boxes for which\n #those values are the only possible values.\n #we can eliminate those values of the possible values of other boxes in the\n #same unit \n if ( len(tuple_v)==len(tuple_box_list) ):\n for box in unit:\n if box not in tuple_box_list:\n box_v=values[box]\n #remove each possible values of the tuple from the target box \n for v in tuple_v:\n if v in values[box]:\n box_v=box_v.replace(v,'')\n if box_v!=values[box]:\n assign_value(values, box, box_v)\n \n return(values)\n \n \n \n \n \ndef cross(A, B):\n \"Cross product of elements in A and elements in B.\"\n return [s+t for s in a for t in b]\n\ndef grid_values(grid):\n \"\"\"\n Convert grid into a dict of {square: char} with '123456789' for empties.\n Args:\n grid(string) - A grid in string form.\n Returns:\n A grid in dictionary form\n Keys: The boxes, e.g., 'A1'\n Values: The value in each box, e.g., '8'. If the box has no value, then the value will be '123456789'.\n \"\"\"\n i=0\n sudoku=dict()\n \n for value in grid:\n if value == \".\":\n value = '123456789'\n sudoku[boxes[i]]=value\n i=i+1\n \n return sudoku\n\ndef display(values):\n \"\"\"\n Display the values as a 2-D grid.\n Args:\n values(dict): The sudoku in dictionary form\n \"\"\"\n width = 1+max(len(values[s]) for s in boxes)\n line = '+'.join(['-'*(width*3)]*3)\n for r in rows:\n print(''.join(values[r+c].center(width)+('|' if c in '36' else '')\n for c in cols))\n if r in 'CF': print(line)\n return\n\ndef eliminate(values):\n for box,value in values.items():\n if ( len ( value ) == 1 ):\n for peer in peers[ box ]:\n new_peer_value=''\n for possible_peer_value in values[peer]:\n if ( possible_peer_value != value ):\n new_peer_value=new_peer_value+possible_peer_value\n assign_value(values, peer, new_peer_value)\n \n return values \n\ndef only_choice(values):\n for unit in unitlist:\n for i in range(1,10):\n i=str(i)\n possible_positions=0\n for box in unit:\n if ( i in values[box] ):\n possible_positions=possible_positions+1\n matched_box=box\n if ( possible_positions == 1 ):\n assign_value(values, matched_box, i)\n \n \n return values\n\ndef reduce_puzzle(values):\n stalled = False\n while not stalled:\n # Check how many boxes have a determined value\n solved_values_before = len([box for box in values.keys() if len(values[box]) == 1])\n\n # Your code here: Use the Eliminate Strategy\n values=eliminate(values)\n # Your code here: Use the Only Choice Strategy\n values=only_choice(values)\n #now with the naked twins strategy\n #values=naked_twins(values)\n #now with the naked tuples strategy\n values=naked_tuples(values)\n # Check how many boxes have a determined value, to compare\n solved_values_after = len([box for box in values.keys() if len(values[box]) == 1])\n # If no new values were added, stop the loop.\n stalled = solved_values_before == solved_values_after\n # Sanity check, return False if there is a box with zero available values:\n if len([box for box in values.keys() if len(values[box]) == 0]):\n return False\n return values\n\ndef search(values):\n \"Using depth-first search and propagation, create a search tree and solve the sudoku.\"\n # First, reduce the puzzle using the previous function\n values=reduce_puzzle(values)\n if values is False:\n return False\n \n # Choose one of the unfilled squares with the fewest possibilities\n smallest_box_size=9\n smallest_box='solved!'\n for box,value in values.items():\n if ( (len(value) <= smallest_box_size) and ( len(value) > 1 ) ):\n smallest_box=box\n smallest_box_size=len(value)\n \n if ( smallest_box == 'solved!' ):\n print('It is solved!')\n return values\n \n # Now use recursion to solve each one of the resulting sudokus, and if one returns a value (not False), return that answer!\n for possible_value in values[smallest_box]:\n new_values=values.copy()\n assign_value(new_values, smallest_box, possible_value)\n attempt=search(new_values)\n #make it stop the for loop it is has found a solution\n #else it would continue to search other branches for a good solution and it seems\n #it can take a long time\n if attempt:\n return attempt\n\ndef solve(grid):\n \"\"\"\n Find the solution to a Sudoku grid.\n Args:\n grid(string): a string representing a sudoku grid.\n Example: '2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3'\n Returns:\n The dictionary representation of the final sudoku grid. False if no solution exists.\n \"\"\"\n return search(grid_values(grid))\n\nif __name__ == '__main__':\n diag_sudoku_grid = '2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3'\n display(solve(diag_sudoku_grid))\n\n try:\n from visualize import visualize_assignments\n visualize_assignments(assignments)\n\n except SystemExit:\n pass\n except Exception as e:\n print('We could not visualize your board due to a pygame issue. Not a problem! It is not a requirement.')\n"} {"blob_id": "3a1e39da4a8a37aaf689abac9585b10d2d4ddc7d", "repo_name": "csenn/alg-practice", "path": "/pattern_match/aho_corasick_alt_1.py", "length_bytes": 3085, "score": 3.609375, "int_score": 4, "content": "class Node:\n def __init__(self, label):\n self.label = label\n self.map = {}\n self.output = set()\n self.fail = None\n def get_label(self):\n return self.label\n \n def get_children(self):\n return self.map.iteritems()\n \n def add_output(self, word):\n self.output.add(word)\n \n def get_child(self, char):\n return self.map.get(char, None)\n \n def get_or_add_child(self, char):\n p = self.get_child(char)\n if not p:\n p = self.add_child(char)\n return p\n \n def add_child(self, char):\n if self.map.has_key(char):\n return self.map[char]\n else:\n n = Node(char)\n self.map[char] = n\n return n\n \n def get_fail(self):\n return self.fail\n \n def set_fail(self, f):\n self.fail = f\n \n def is_world(self):\n return bool(self.output)\n \n def get_out_put(self):\n return self.output\n \n def __str__(self):\n return 'label: {}, map:{}'.format(self.label, str(self.map))\n \n \nclass ACAutomaton:\n def __init__(self):\n self.root = Node('-1')\n self.has_built = False\n \n def add_word(self, word):\n p = self.root\n for i in range(len(word)):\n c = word[i]\n p = p.get_or_add_child(c)\n if i == len(word) - 1:\n p.add_output(word)\n \n def build_fail(self):\n # print self.root\n # print self.root.get_children()\n self.root.set_fail(self.root)\n q = []\n chilren = self.root.get_children()\n for k, v in chilren:\n v.set_fail(self.root)\n q.append(v)\n \n while q:\n p = q.pop()\n for k, v in p.get_children():\n q.append(v)\n pf = p.get_fail()\n pfc = pf.get_child(k)\n print 'aaaa', pfc == v, k, pf.label, pfc\n while not pfc and pf != self.root:\n pf = pf.get_fail()\n pfc = pf.get_child(k)\n if pfc:\n v.set_fail(pfc)\n else:\n v.set_fail(self.root)\n \n def build(self, words):\n for w in words:\n self.add_word(w)\n self.build_fail()\n self.has_built = True\n \n def traverse(self, word):\n p = ac.root\n i = 0\n res = []\n while i < len(word):\n c = word[i]\n pc = p.get_child(c)\n # print pc\n while not pc:\n p = p.get_fail()\n pc = p.get_child(c)\n if p == self.root and not pc:\n i += 1\n break\n if pc:\n p = pc\n i += 1\n res.extend(p.get_out_put())\n return res\n\n# words = ['he', 'she', 'his', 'her', 'hers']\nwords = ['aardva']\nac = ACAutomaton()\nac.build(words)\nres = ac.traverse('shherishers')\nprint res\n#['he', 'her', 'she', 'her', 'hers']\nres = ac.traverse('shershehishers')\nprint res\n#['she', 'her', 'hers', 'she', 'his', 'she', 'her', 'hers']"} {"blob_id": "4f3706fbfbd856564a2fbdec7c8fe1191600bb6f", "repo_name": "LazyerIJ/Algorithm", "path": "/Problem/Kakao/2017_blind/kakao_2017_\uc154\ud2c0\ubc84\uc2a4.py", "length_bytes": 2619, "score": 3.796875, "int_score": 4, "content": "'''\nhttps://www.welcomekakao.com/learn/courses/30/lessons/17678\n'''\ndef solution(n, t, m, timetable):\n '''\n 09:00\ubd80\ud130 t\ubd84 \uac04\uaca9\uc73c\ub85c n\ubc88 m\uba85\uc744 \ud0dc\uc6b8 \uc218 \uc788\ub294 \ubc84\uc2a4\uac00 \uc628\ub2e4.\n timetable\uc758 \uc2dc\uac04 \uc21c\uc11c\ub85c \ud06c\ub8e8\uac00 \uc904\uc744 \uc120\ub2e4.\n \ub2a6\uc5b4\ub3c4 \uba87 \uc2dc \uae4c\uc9c0 \uc904\uc744 \uc11c\uc57c \ud558\ub294\uac00\n\n for\ubb38\uc744 \ubc97\uc5b4\ub098\uc11c \ub9c8\uc9c0\ub9c9\uc5d0 return\uc5d0 if\ucc98\ub9ac\ub97c \ud558\uc9c0\uc54a\uc544 \uace8\uba39\uc5c8\uc74c.\n '''\n from datetime import datetime, timedelta\n\n def add_time(time):\n time = datetime.strptime('09:00', '%H:%M') + timedelta(milliseconds=time*60*1000)\n return \"{:0>2}:{:0>2}\".format(time.hour, time.minute)\n def minus_one(time):\n time = datetime.strptime('{}:{}'.format(time[:2], time[-2:]), '%H:%M')\n time = time - timedelta(milliseconds=60*1000)\n return \"{:0>2}:{:0>2}\".format(time.hour, time.minute)\n\n last_bus = add_time(t*(n-1))\n timetable = sorted([x for x in timetable if x<=last_bus])\n\n if len(timetable)==0:\n return last_bus\n\n for idx in range(n): # \ubc84\uc2a4\uac00 \uc624\ub294 \uc218\n max_people = (n-idx)*m\n crue = 0 # \ud0d1\uc2b9\ud55c \ud06c\ub8e8 \uc218\n cur_time = add_time(t*idx)\n while crue < m and timetable[0]<=cur_time:\n last_crue = timetable.pop(0)\n crue += 1 # \ud0d1\uc2b9\uc790 + 1\n max_people -= 1 # \ucd1d \ud0d1\uc2b9 \uac00\ub2a5 \uc218 -1\n if len(timetable)==0:\n if max_people>0:\n return last_bus\n return minus_one(last_crue)\n if max_people>0:\n return last_bus\n return minus_one(last_crue)\n\n\nif __name__ == '__main__':\n n = 2\n t = 10\n m = 1\n timetable = [\"08:00\"]\n rs = \"09:10\"\n print('case1>>', rs, solution(n, t, m, timetable))\n\n n = 2\n t = 10\n m = 2\n timetable = [\"09:10\", \"09:09\", \"08:00\"]\n rs = \"09:09\"\n print('case2>>', rs, solution(n, t, m, timetable))\n\n n = 2\n t = 1\n m = 2\n timetable = [\"09:00\", \"09:00\", \"09:00\", \"09:00\"]\n rs = \"08:59\"\n print('case3>>', rs, solution(n, t, m, timetable))\n\n n = 1\n t = 1\n m = 5\n timetable = [\"00:01\", \"00:01\", \"00:01\", \"00:01\", \"00:01\"]\t\n rs = \"00:00\"\n print('case4>>', rs, solution(n, t, m, timetable))\n\n n = 1\n t = 1\n m = 1\n timetable = [\"23:59\"]\n rs = \"09:00\"\n print('case5>>', rs, solution(n, t, m, timetable))\n\n n = 10\n t = 60\n m = 45\n timetable = [\"23:59\", \"23:59\", \"23:59\", \"23:59\", \"23:59\", \"23:59\",\n \"23:59\", \"23:59\", \"23:59\", \"23:59\", \"23:59\", \"23:59\",\n \"23:59\", \"23:59\", \"23:59\", \"23:59\", ]\n rs = \"18:00\"\n print('case6>>', rs, solution(n, t, m, timetable))\n"} {"blob_id": "4f653a89440903308ea4d299145c87a558cd1838", "repo_name": "mc422/leetcode", "path": "/Permutations.py", "length_bytes": 1229, "score": 3.53125, "int_score": 4, "content": "class Solution(object):\n def permute(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[List[int]]\n \"\"\"\n ans = []\n if len(nums) == 0:\n return ans\n for i in nums:\n if not ans:\n ans.append([i])\n else:\n new_ans = []\n for l in ans:\n for k in range(len(l)+1):\n new_list = [digit for digit in l]\n new_list.insert(k, i)\n new_ans.append(new_list)\n ans = new_ans\n return\n\n def permuteUnique(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[List[int]]\n \"\"\"\n nums.sort()\n if len(nums) == 0: return []\n if len(nums) == 1: return [nums]\n ans = []\n for i in range(len(nums)):\n if i > 0 and nums[i-1] == nums[i]:\n continue\n else:\n follows = self.permuteUnique(nums[:i] + nums[i+1:])\n for j in follows:\n ans.append([nums[i]] + j)\n return ans\n\nsolution = Solution()\n# print solution.permute([1,2,3])\nprint solution.permuteUnique([1,1,2])"} {"blob_id": "3ffe1dd5a57014f68bda5925dace6f8539bd8bfc", "repo_name": "simonfqy/SimonfqyGitHub", "path": "/lintcode/easy/464_sort_integers_ii.py", "length_bytes": 4753, "score": 3.828125, "int_score": 4, "content": "'''\nLink: https://www.lintcode.com/problem/sort-integers-ii/description\n'''\n\n# This is copied from the teachings of Jiuzhang.com. Other versions of quick sort do exist.\nclass Solution:\n \"\"\"\n @param A: an integer array\n @return: nothing\n \"\"\"\n def sortIntegers2(self, A):\n # write your code here\n self.quick_sort(A, 0, len(A) - 1)\n \n \n def quick_sort(self, A, start, end):\n if start >= end:\n return\n pivot = A[(start + end) // 2]\n left, right = start, end\n \n # Here we need to have left <= right in this while block. Because if we do not,\n # we would cause overlapping portions in left and right sorted subarrays, and stackoverflow.\n while left <= right:\n # If an array is composed of the same values, then it would undergo O(n) swaps and result\n # in two sorted subarrays with similar size. The swapping seems to be unnecessary, but if\n # we avoid swapping by setting the conditions to be A[left] <= pivot and A[right] >= pivot,\n # it would result in left == right + 1, and right unchanged. Thus it would cause stack overflow\n # error. So we must set the conditions to be A[left] < pivot and A[right] > pivot, at the\n # expense of 'unnecessary' swaps.\n while left <= right and A[left] < pivot:\n left += 1\n while left <= right and A[right] > pivot:\n right -= 1\n if left <= right:\n A[left], A[right] = A[right], A[left]\n left += 1\n right -= 1\n \n self.quick_sort(A, start, right)\n self.quick_sort(A, left, end)\n \n\n# Also copied from the teachings of Jiuzhang.com. Uses merge sort. \nclass Solution:\n \"\"\"\n @param A: an integer array\n @return: nothing\n \"\"\"\n def sortIntegers2(self, A):\n # write your code here\n temp = [0] * len(A)\n # Pass the temp array as a parameter to avoid claiming new space in each invocation of merge_sort().\n self.merge_sort(A, 0, len(A) - 1, temp)\n \n \n def merge_sort(self, A, start, end, temp):\n if start >= end:\n return\n left_end = (start + end) // 2\n self.merge_sort(A, start, left_end, temp)\n self.merge_sort(A, left_end + 1, end, temp)\n self.merge(A, start, end, temp)\n \n \n def merge(self, A, start, end, temp):\n left_end = (start + end) // 2\n temp_ind = start\n left_index = start\n right_index = left_end + 1\n \n while left_index <= left_end and right_index <= end:\n if A[left_index] <= A[right_index]:\n temp[temp_ind] = A[left_index]\n left_index += 1\n else:\n temp[temp_ind] = A[right_index]\n right_index += 1\n temp_ind += 1\n \n while left_index <= left_end:\n temp[temp_ind] = A[left_index]\n temp_ind += 1\n left_index += 1\n \n while right_index <= end:\n temp[temp_ind] = A[right_index]\n temp_ind += 1\n right_index += 1\n \n for i in range(start, end + 1):\n # Copy the values from temp array to the original array.\n A[i] = temp[i]\n \n \n# My solution based on https://labuladong.github.io/algo/di-yi-zhan-da78c/shou-ba-sh-66994/gui-bing-p-1387f/.\n# Essentially the same as the solution above.\nclass Solution:\n \"\"\"\n @param a: an integer array\n @return: nothing\n \"\"\"\n def sort_integers2(self, a: List[int]):\n if not a:\n return\n self.temp = list(a)\n self.sort(a, 0, len(a) - 1)\n return a\n\n def sort(self, a, start, end):\n if start >= end:\n return\n mid = (start + end) // 2\n self.sort(a, start, mid)\n self.sort(a, mid + 1, end)\n self.merge(a, start, end)\n\n def merge(self, a, start, end):\n self.temp[start : end + 1] = a[start : end + 1]\n left_end = (start + end) // 2\n a_ind = start\n left_ind = start\n right_ind = left_end + 1\n\n while left_ind <= left_end and right_ind <= end:\n if self.temp[left_ind] <= self.temp[right_ind]:\n a[a_ind] = self.temp[left_ind]\n left_ind += 1\n else:\n a[a_ind] = self.temp[right_ind]\n right_ind += 1\n a_ind += 1\n\n if left_ind <= left_end:\n a[a_ind : end + 1] = self.temp[left_ind : left_end + 1]\n\n if right_ind <= end:\n a[a_ind : end + 1] = self.temp[right_ind : end + 1]\n \n \n"} {"blob_id": "e2abeca0d65a295844309e360730ee48824f2c49", "repo_name": "TopHatCroat/advent-of-code-2018", "path": "/day07/first.py", "length_bytes": 975, "score": 3.625, "int_score": 4, "content": "import operator\nfrom collections import defaultdict\n\ndef topological_sort(graph):\n in_degree = { e : 0 for e in graph }\n for edge in graph:\n for vertex in graph[edge]:\n in_degree[vertex] += 1\n\n to_visit = list(filter(lambda x: in_degree[x] == 0, in_degree))\n path = []\n while to_visit:\n edge = min(to_visit)\n to_visit.remove(edge)\n path.append(edge)\n for vertex in graph[edge]:\n in_degree[vertex] -= 1\n if in_degree[vertex] == 0:\n to_visit.append(vertex)\n\n if len(path) == len(graph):\n return path\n \n return [] # there is a cycle, return empty list\n\nsteps = [ (line[5], line[36]) for line in open(\"input.txt\").readlines() ]\nlast = set(map(operator.itemgetter(1), steps)) - set(map(operator.itemgetter(0), steps))\ngraph = defaultdict(list)\ngraph[last.pop()] = []\n\nfor s in steps:\n graph[s[0]] += [s[1]]\n\nresult = topological_sort(graph)\nprint(\"\".join(result))"} {"blob_id": "776b6492fa6be10ab3b37d7367e17c651c9700e3", "repo_name": "raobystorm/algorithms", "path": "/LCOJ_112_py/LCOJ_112_py.py", "length_bytes": 665, "score": 3.796875, "int_score": 4, "content": "\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n # @param {TreeNode} node\n # @param {integer} sum\n def dfs(self, node, sum):\n if node is None:\n return False\n if node.val == sum and node.left is None and node.right is None:\n return True\n\n return self.dfs(node.left, sum - node.val) or self.dfs(node.right, sum - node.val)\n # @param {TreeNode} root\n # @param {integer} sum\n # @return {boolean}\n def hasPathSum(self, root, sum):\n return self.dfs(root, sum)\n "} {"blob_id": "7ebc9e10b3b37d76208c0058284322fb0c8d0ab3", "repo_name": "shobhitgupta01/algorithms", "path": "/DivideNConquer/max_subarray.py", "length_bytes": 1908, "score": 4.125, "int_score": 4, "content": "# Project : Finding the maximum sub-array\n# Author : Shobhit Gupta\n# Created : 4/11/2020\n#Last Edited : 4/11/12020\n\n\n# Function to find the max crossing subarray\ndef find_max_crossing_subarray(A,beg,mid,end):\n\n # Finding the max sub array left of mid\n left_sum = float('-inf')\n sum = 0\n for i in range(mid,beg-1,-1):\n sum += A[i]\n if sum > left_sum:\n left_sum = sum\n max_left = i\n\n # Finding the max sub-array right of mid\n right_sum = float('-inf')\n sum = 0\n\n for i in range(mid+1,end+1):\n sum += A[i]\n if sum > right_sum:\n right_sum = sum\n max_right = i\n\n return max_left, max_right, left_sum+right_sum\n\n# Recursive function to find the max sub-array\ndef find_max_subarray(A,beg,end):\n\n #base case - if single element, return the element\n if beg == end:\n return beg,end,A[beg]\n else:\n mid = (beg + end) // 2 #integral division\n\n #left part of the sub problem\n left_low, left_high, left_sum = find_max_subarray(A,beg,mid)\n\n #right part of the subproblem\n right_low, right_high, right_sum = find_max_subarray(A,mid+1,end)\n\n #crossing subarray\n cross_low, cross_high, cross_sum = find_max_crossing_subarray(A,beg,mid,end)\n\n #comparing the sums\n if left_sum >= right_sum and left_sum >= cross_sum:\n return left_low, left_high, left_sum\n elif right_sum >= left_sum and right_sum >= cross_sum:\n return right_low, right_high, right_sum\n else:\n return cross_low, cross_high, cross_sum\n\n\n# Running the code:\nif __name__ == '__main__':\n array = [13,-3,-25,20,-3,-16,-23,18,20,-7,12,-5,-22,15,-4,7]\n\n low,high,sum = find_max_subarray(array,0,len(array)-1)\n\n # print(\"The correct answer is ({},{},{})\".format(6,10,28))\n print(\"\\nThe computed answer is ({},{},{})\".format(low,high,sum))\n\n\n"} {"blob_id": "f16d7c6facf1004be355418705d8c1fc6fc63cfb", "repo_name": "LouisYLWang/Algorithms", "path": "/Merge_sort/merge_sort.py", "length_bytes": 1574, "score": 4.03125, "int_score": 4, "content": "\n''' MergeSort\nInput: array A of n distinct integers. \nOutput: array with the same integers, sorted from smallest to largest.\n\nignoring base cases \nC := recursively sort \ufb01rst half of A \nD := recursively sort second half of A \nreturn Merge (C,D)\n'''\n\n\ndef merge_sort(array_b):\n b_len = len(array_b)\n cd_len = int(b_len//2)\n\n if b_len > 1:\n array_c = merge_sort(array_b[:cd_len])\n array_d = merge_sort(array_b[cd_len:])\n return merge(array_c, array_d)\n else:\n return array_b # did not consider this condition at first\n\n\n\n'''Merge\nInput: sorted arrays C and D (length n/2 each). \nOutput: sorted array B (length n). \nSimplifying assumption: n is even.\n\n i := 1\n j := 1 \n for k := 1 to n do \n if C[i] 0, 'Array must not be empty'\n Tree = BinaryNode(arr[0], comparator)\n for value in arr[1:]:\n Tree.insert(value)\n return Tree\n\n\n# Write a function to compare whether two binary trees are identical. \n# Identical trees have the same key value at each position and the same structure.\ndef compare_tree(tree_a: BinaryNode, tree_b: BinaryNode):\n # in order traversal\n if not tree_a and not tree_b:\n return True\n elif (tree_a and not tree_b) or (tree_b and not tree_a):\n return False\n else:\n return (\n tree_a.get_data() == tree_b.get_data() and \n compare_tree(tree_a.get_next_left(), tree_b.get_next_left()) and\n compare_tree(tree_a.get_next_right(), tree_b.get_next_right())\n )\n\nif __name__ == \"__main__\":\n compare = lambda a, b : a < b\n test_arr_a = [1, 6, 3, 4, 5, 7, 9, 2, 3, 8]\n test_arr_b = [1, 6, 3, 4, 5, 7, 9, 2, 3, 9]\n binary_tree_a = create_binary_tree(test_arr_a, compare)\n binary_tree_b = create_binary_tree(test_arr_b, compare)\n binary_tree_c = create_binary_tree(test_arr_b, compare)\n assert compare_tree(binary_tree_a, binary_tree_b) == False\n assert compare_tree(binary_tree_b, binary_tree_c) == True\n\n\n"} {"blob_id": "1a192a33d78b3d3565801cba43f7f7cce928d75e", "repo_name": "renato-bohler/sistemas-inteligentes", "path": "/GeneticAlgorithm/src/Busca_Largura.py", "length_bytes": 5501, "score": 3.578125, "int_score": 4, "content": "# Autores: Davi Boberg e Renato B\u00f6hler\nfrom Node import Node\n\n# Representa\u00e7\u00e3o do estado\n# (x, y, d )\n# ([0 9], [0 9], {W,A,S,D})\nestadoInicial = (9,9,'W')\nestadoFinal = (8,2,'S')\n\n# Fun\u00e7\u00f5es\n\n# Recebe dois estados adjacentes e determina a a\u00e7\u00e3o necess\u00e1ria para realizar a transi\u00e7\u00e3o\ndef determinar_acao(origem, destino): \n\t\tdelta_x = destino[0] - origem[0]\n\t\tdelta_y = destino[1] - origem[1]\n\t\td_origem = origem[2]\n\t\td_destino = destino[2]\n\n\t\tif (delta_y == -1 and d_origem == 'W' and d_destino == 'W') or (delta_x == -1 and d_origem == 'A' and d_destino == 'A') or (delta_y == 1 and d_origem == 'S' and d_destino == 'S') or (delta_x == 1 and d_origem == 'D' and d_destino == 'D'):\n\t\t\t\t# Mover para frente\n\t\t\t\treturn 'straight'\n\t\telif (d_origem == 'W' and d_destino == 'A') or (d_origem == 'A' and d_destino == 'S') or (d_origem == 'S' and d_destino == 'D') or (d_origem == 'D' and d_destino == 'W'):\n\t\t\t\t# Rotacionar para esquerda\n\t\t\t\treturn 'left'\n\t\telif (d_origem == 'W' and d_destino == 'D') or (d_origem == 'D' and d_destino == 'S') or (d_origem == 'S' and d_destino == 'A') or (d_origem == 'A' and d_destino == 'W'):\n\t\t\t\t# Rotacionar para direita\n\t\t\t\treturn 'right'\n\n\t\traise Exception('Os estados {origem} e {destino} n\u00e3o s\u00e3o adjacentes'.format(origem=origem, destino=destino))\n\n# Recebe o n\u00f3 destino e retorna a sequ\u00eancia de estados adjacentes da raiz at\u00e9 ele\ndef determinar_caminho(destino, printCaminho = False):\n\t\tcaminho = [destino.data]\n\n\t\tnoAtual = destino\n\t\twhile noAtual.parent != None:\n\t\t\t\tcaminho.insert(0, noAtual.parent.data)\n\t\t\t\tnoAtual = noAtual.parent\n\n\t\tif printCaminho == True:\n\t\t\t\tprint(\"Caminho gerado: {caminho}\".format(caminho=caminho))\n\t\t\t\tprint()\n\t\treturn caminho\n\ndef imprimir_caminho(caminho):\n\tlinha = 0\n\twhile linha <= 9:\n\t\tcoluna = 0\n\t\twhile coluna <= 9:\n\t\t\tif [True for node in caminho if linha == node[1] and coluna == node[0]]:\n\t\t\t\tprint('o', end='')\n\t\t\telif coluna == 8 and linha == 28:\n\t\t\t\tprint('g', end='')\n\t\t\telif coluna > 3 and linha == 5:\n\t\t\t\tprint('x', end='')\n\t\t\telse:\n\t\t\t\tprint('-', end='')\n\n\t\t\tcoluna += 1\n\t\tlinha += 1\n\t\tprint()\n\tprint()\n\ndef gerar_planejamento(destino):\n\t\tacoes = []\n\t\tcaminho = determinar_caminho(destino, False)\n\n\t\tif len(caminho) < 2:\n\t\t\t\treturn acoes\n\n\t\torigem = caminho.pop(0)\n\t\twhile caminho:\n\t\t\t\tdestino = caminho.pop(0)\n\t\t\t\tacoes.append(determinar_acao(origem, destino))\n\t\t\t\torigem = destino\n\n\t\treturn acoes\n\n# Recebe um estado e retorna uma lista com todas as transi\u00e7\u00f5es poss\u00edveis para ele\ndef transicoes_possiveis(estado):\n\t\tmovimentos_possiveis = ['straight', 'left', 'right']\n\n\t\tx = estado[0]\n\t\ty = estado[1]\n\t\td = estado[2]\n\n\t\t# Limites do mapa\n\t\t# N\u00e3o pode sair do mapa\n\t\tif (y == 0 and d == 'W') or (x == 0 and d == 'A') or (y == 9 and d == 'S') or (x == 9 and d == 'D'):\n\t\t\t\tmovimentos_possiveis.remove('straight')\n\n\t\t# N\u00e3o pode virar pra onde n\u00e3o tem trilha\n\t\tif (y == 0 and d == 'D') or (x == 0 and d == 'W') or (y == 9 and d == 'A') or (x == 9 and d == 'S'):\n\t\t\t\tmovimentos_possiveis.remove('left')\n\n\t\tif (y == 0 and d == 'A') or (x == 0 and d == 'S') or (y == 9 and d == 'D') or (x == 9 and d == 'W'):\n\t\t\t\tmovimentos_possiveis.remove('right')\n\n\t\t# Obstru\u00e7\u00f5es do mapa\n\n\t\t# Parte inferior da obstru\u00e7\u00e3o\n\t\tif x >= 4 and y == 6 and d == 'W':\n\t\t\t\tmovimentos_possiveis.remove('straight')\n\n\t\t# Parte lateral da obstru\u00e7\u00e3o\n\t\tif x == 3 and y == 5 and d == 'D':\n\t\t\t\tmovimentos_possiveis.remove('straight')\n\n\t\t# Parte superior da obstru\u00e7\u00e3o\n\t\tif x >= 4 and y == 4 and d == 'S':\n\t\t\t\tmovimentos_possiveis.remove('straight')\n\n\t\treturn estados_possiveis(estado, movimentos_possiveis)\n\ndef estados_possiveis(estado, movimentos_possiveis):\n\t\testados = set()\n\n\t\tx = estado[0]\n\t\ty = estado[1]\n\t\td = estado[2]\n\n\t\t# Pode andar para frente\n\t\tif 'straight' in movimentos_possiveis:\n\t\t\t\tnovo_x = x\n\t\t\t\tnovo_y = y\n\n\t\t\t\tif d == 'W':\n\t\t\t\t\t\tnovo_y = y-1\n\t\t\t\telif d == 'A':\n\t\t\t\t\t\tnovo_x = x-1\n\t\t\t\telif d == 'S':\n\t\t\t\t\t\tnovo_y = y+1\n\t\t\t\telif d == 'D':\n\t\t\t\t\t\tnovo_x = x+1\n\n\t\t\t\testados.add((novo_x, novo_y, d))\n\n\t\t# Pode rotacionar para esquerda\n\t\tif 'left' in movimentos_possiveis:\n\t\t\t\tnova_direcao = d\n\n\t\t\t\tif d == 'W':\n\t\t\t\t\t\tnova_direcao = 'A'\n\t\t\t\telif d == 'A':\n\t\t\t\t\t\tnova_direcao = 'S'\n\t\t\t\telif d == 'S':\n\t\t\t\t\t\tnova_direcao = 'D'\n\t\t\t\telif d == 'D':\n\t\t\t\t\t\tnova_direcao = 'W'\n\n\t\t\t\testados.add((x,y,nova_direcao))\n\n\t\t# Pode rotacionar para direita\n\t\tif 'right' in movimentos_possiveis:\n\t\t\t\tnova_direcao = d\n\n\t\t\t\tif d == 'W':\n\t\t\t\t\t\tnova_direcao = 'D'\n\t\t\t\telif d == 'A':\n\t\t\t\t\t\tnova_direcao = 'W'\n\t\t\t\telif d == 'S':\n\t\t\t\t\t\tnova_direcao = 'A'\n\t\t\t\telif d == 'D':\n\t\t\t\t\t\tnova_direcao = 'S'\n\n\t\t\t\testados.add((x,y,nova_direcao))\n\n\t\treturn estados\n\ndef busca_largura(origem, destino):\n\t\t# Ra\u00edz da \u00e1rvore\n\t\tnoAtual = Node(origem, None)\n\t\tpendentes = [noAtual]\n\t\tvisitados = set()\n\n\t\twhile pendentes:\n\t\t\t\tnoAtual = pendentes.pop(0)\n\t\t\t\tif noAtual.data not in visitados:\n\t\t\t\t\t\ttransicoes = transicoes_possiveis(noAtual.data)\n\t\t\t\t\t\tfor transicao in transicoes:\n\t\t\t\t\t\t\t\ttransicaoNo = Node(transicao, noAtual)\n\n\t\t\t\t\t\t\t\tif transicao == destino:\n\t\t\t\t\t\t\t\t\t\tvisitados.add(noAtual.data)\n\t\t\t\t\t\t\t\t\t\timprimir_caminho(determinar_caminho(transicaoNo))\n\t\t\t\t\t\t\t\t\t\treturn gerar_planejamento(transicaoNo)\n\n\t\t\t\t\t\t\t\tpendentes.append(transicaoNo)\n\n\t\t\t\t\t\tvisitados.add(noAtual.data)\n\n\t\traise Exception('O estado {destino} n\u00e3o \u00e9 alcan\u00e7\u00e1vel a partir de {origem}'.format(origem=origem, destino=destino))\n\ndef search(start_point, end_point):\n\tplanning = busca_largura(start_point, end_point)\n\treturn planning\n\nif __name__ == '__main__':\n\tsearch()"} {"blob_id": "a120f2270107af88c68f49a1c59631b60bf7509e", "repo_name": "fzn0728/nlp-study", "path": "/HW2_CNN/cnn.py", "length_bytes": 6929, "score": 3.75, "int_score": 4, "content": "from tools import load_data, read_vocab, sigmoid, tanh, show_model\nfrom nltk import WordNetLemmatizer, word_tokenize,download\n#download('punkt')\nimport numpy as np\n\n\"\"\"\nThis cell shows you how the model will be used, you have to finish the cell below before you\ncan run this cell. \n\nOnce the implementation is done, you should hype tune the parameters to find the best config\n\"\"\"\n\nfrom sklearn.model_selection import train_test_split\ndata = load_data(\"train.txt\")\nvocab = read_vocab(\"vocab.txt\")\nX, y = data.text, data.target\nX_train, X_dev, y_train, y_dev = train_test_split(X, y, test_size=0.3)\n\nclass CNNTextClassificationModel:\n def __init__(self, vocab, window_size=2, F=100, alpha=0.1):\n \"\"\"\n F: number of filters\n alpha: back propagatoin learning rate\n \"\"\"\n self.vocab = vocab\n self.window_size = window_size\n self.F = F\n self.alpha = alpha\n\n # U and w are the weights of the hidden layer, see Fig 1 in the pdf file\n # U is the 1D convolutional layer with shape: voc_size * num_filter * window_size\n self.U = np.random.normal(loc=0, scale=0.01, size=(len(vocab), F, window_size))\n # w is the weights of the activation layer (after max pooling)\n self.w = np.random.normal(loc=0, scale=0.01, size=(F + 1))\n\n def pipeline(self, X):\n \"\"\"\n Data processing pipeline to:\n 1. Tokenize, Normalize the raw input\n 2. Translate raw data input into numerical encoded vectors\n\n :param X: raw data input\n :return: list of lists\n\n For example:\n X = [\"Apples orange banana\",\n \"orange apple bananas\"]\n returns:\n [[0, 1, 2],\n [0, 2, 3]]\n \"\"\"\n X2 = []\n unknown = vocab['__unknown__']\n default = vocab['.']\n wnet = WordNetLemmatizer()\n\n for i in range(len(X)):\n cleaned_tokens = [self.vocab.get(wnet.lemmatize(w), unknown) for w in word_tokenize(X[i])]\n if len(cleaned_tokens) < self.window_size:\n cleaned_tokens = cleaned_tokens + [default] * (self.window_size - len(cleaned_tokens))\n X2.append(cleaned_tokens)\n\n return X2\n\n @staticmethod\n def accuracy(probs, labels):\n assert len(probs) == len(labels), \"Wrong input!!\"\n a = np.array(probs)\n b = np.array(labels)\n\n return 1.0 * (a == b).sum() / len(b)\n\n def train(self, X_train, y_train, X_dev, y_dev, nEpoch=50):\n \"\"\"\n Function to fit the model\n :param X_train, X_dev: raw data input\n :param y_train, y_dev: label\n :nEpoch: number of training epoches\n \"\"\"\n X_train = self.pipeline(X_train)\n X_dev = self.pipeline(X_dev)\n\n for epoch in range(nEpoch):\n self.fit(X_train, y_train)\n\n accuracy_train = self.accuracy(self.predict(X_train), y_train)\n accuracy_dev = self.accuracy(self.predict(X_dev), y_dev)\n\n print(\"Epoch: {}\\tTrain accuracy: {:.3f}\\tDev accuracy: {:.3f}\"\n .format(epoch, accuracy_train, accuracy_dev))\n\n def fit(self, X, y):\n \"\"\"\n :param X: numerical encoded input\n \"\"\"\n for (data, label) in zip(X, y):\n self.backward(data, label)\n\n return self\n\n def predict(self, X):\n \"\"\"\n :param X: numerical encoded input\n \"\"\"\n result = []\n for data in X:\n if self.forward(data)[\"prob\"] > 0.5:\n result.append(1)\n else:\n result.append(0)\n\n return result\n\n def forward(self, word_indices):\n \"\"\"\n :param word_indices: a list of numerically ecoded words\n :return: a result dictionary containing 3 items -\n result['prob']: \\hat y in Fig 1.\n result['h']: the hidden layer output after max pooling, h = [h1, ..., hf]\n result['hid']: argmax of F filters, e.g. j of x_j\n e.g. for the ith filter u_i, tanh(word[hid[j], hid[j] + width]*u_i) = h_i\n \"\"\"\n assert len(word_indices) >= self.window_size, \"Input length cannot be shorter than the window size\"\n\n h = np.zeros(self.F + 1, dtype=float)\n hid = np.zeros(self.F, dtype=int)\n prob = 0.0\n\n # layer 1. compute h and hid\n # loop through the input data of word indices and\n # keep track of the max filtered value h_i and its position index x_j\n # h_i = max(tanh(weighted sum of all words in a given window)) over all windows for u_i\n \"\"\"\n Implement your code here\n \"\"\"\n for F_index in range(len(self.U[0])):\n temp_list = []\n for word_indices_ind in range(len(word_indices) - self.window_size + 1):\n window_sum = 0.0\n for window_ind in range(self.window_size):\n window_sum += self.U[word_indices[word_indices_ind + window_ind]][F_index][window_ind]\n #print(word_indices_ind, self.U[word_indices[word_indices_ind+window_ind]][F_index][window_ind])\n temp_list.append(tanh(window_sum))\n h[F_index] = np.max(temp_list)\n hid[F_index] = np.argmax(temp_list)\n h[-1] = 1\n\n # layer 2. compute probability\n # once h and hid are computed, compute the probabiliy by sigmoid(h^TV)\n \"\"\"\n Implement your code here\n \"\"\"\n prob_sum = 0.0\n for w_i, h_i in zip(self.w, h):\n prob_sum += w_i * h_i\n\n prob = sigmoid(prob_sum)\n # return result\n return {\"prob\": prob, \"h\": h, \"hid\": hid}\n\n def backward(self, word_indices, label):\n \"\"\"\n Update the U, w using backward propagation\n\n :param word_indices: a list of numerically ecoded words\n :param label: int 0 or 1\n :return: None\n\n update weight matrix/vector U and V based on the loss function\n \"\"\"\n\n pred = self.forward(word_indices)\n prob = pred[\"prob\"]\n h = pred[\"h\"]\n hid = pred[\"hid\"]\n\n L = -(label) * np.log(prob) - (1 - label) * np.log(1 - prob)\n # print(L)\n # update U and w here\n # to update V: w_new = w_current + d(loss_function)/d(w)*alpha\n # to update U: U_new = U_current + d(loss_function)/d(U)*alpha\n # Hint: use Q6 in the first part of your homework\n \"\"\"\n Implement your code here\n \"\"\"\n old_w = self.w[:]\n self.w = self.w + (label - prob) * h * self.alpha\n # print(h)\n for F_index in range(self.F):\n incre = (label - prob) * old_w[F_index] * (1 - h[F_index] ** 2)\n # print((label - prob),old_w[F_index],(1-h[F_index]**2))\n for i in range(self.window_size):\n self.U[word_indices[hid[F_index] + i]][F_index][i] += incre * self.alpha\n\n\ncls = CNNTextClassificationModel(vocab)\ncls.train(X_train, y_train, X_dev, y_dev, nEpoch=10)"} {"blob_id": "692b1612065f1549b65a0af65593ac7ce4944aa4", "repo_name": "Jackyzzk/Algorithms", "path": "/\u4f4d\u8fd0\u7b97-04-0260. \u53ea\u51fa\u73b0\u4e00\u6b21\u7684\u6570\u5b57 III.py", "length_bytes": 1442, "score": 3.71875, "int_score": 4, "content": "class Solution(object):\n \"\"\"\n\u7ed9\u5b9a\u4e00\u4e2a\u6574\u6570\u6570\u7ec4 nums\uff0c\u5176\u4e2d\u6070\u597d\u6709\u4e24\u4e2a\u5143\u7d20\u53ea\u51fa\u73b0\u4e00\u6b21\uff0c\u5176\u4f59\u6240\u6709\u5143\u7d20\u5747\u51fa\u73b0\u4e24\u6b21\u3002\n\u627e\u51fa\u53ea\u51fa\u73b0\u4e00\u6b21\u7684\u90a3\u4e24\u4e2a\u5143\u7d20\u3002\n\u8f93\u5165: [1,2,1,3,2,5]\n\u8f93\u51fa: [3,5]\n\u7ed3\u679c\u8f93\u51fa\u7684\u987a\u5e8f\u5e76\u4e0d\u91cd\u8981\uff0c\u5bf9\u4e8e\u4e0a\u9762\u7684\u4f8b\u5b50\uff0c [5, 3] \u4e5f\u662f\u6b63\u786e\u7b54\u6848\u3002\n\u4f60\u7684\u7b97\u6cd5\u5e94\u8be5\u5177\u6709\u7ebf\u6027\u65f6\u95f4\u590d\u6742\u5ea6\u3002\u4f60\u80fd\u5426\u4ec5\u4f7f\u7528\u5e38\u6570\u7a7a\u95f4\u590d\u6742\u5ea6\u6765\u5b9e\u73b0\uff1f\n\u94fe\u63a5\uff1ahttps://leetcode-cn.com/problems/single-number-iii\n \"\"\"\n def singleNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n t, ret = 0, [0, 0]\n for x in nums:\n t ^= x # \u5f02\u6216\u7684\u7ed3\u679c\u8868\u793a\u5728\u54ea\u4e9b\u4f4d\u7f6e\u4e0a\u662f\u4e0d\u540c\u7684\n t &= -t # t & (-t) \u8868\u793a\u5f97\u5230 t \u7684\u6700\u540e\u4e00\u4e2a 1 \u8fde\u540c\u5b83\u6240\u5728\u7684\u4f4d\n for x in nums:\n if x & t: # \u6216\u8fd0\u7b97\u6dfb\u52a0\u5c5e\u6027\uff0c\u4e0e\u8fd0\u7b97\u5224\u65ad\u5c5e\u6027\uff0c\u5f02\u6216\u8fd0\u7b97\u6d88\u53bb\u5c5e\u6027\uff0c\u8fd9\u91cc\u7684\u5224\u65ad\u5c31\u662f\u8d77\u5230\u4e00\u4e2a\u5212\u5206\u7684\u4f5c\u7528\n ret[0] ^= x # \u91cd\u590d\u51fa\u73b0\u7684\u5143\u7d20\u4e5f\u4f1a\u56e0\u4e3a\u5177\u6709\u76f8\u540c\u7684\u7279\u5f81\u800c\u88ab\u5212\u5230\u540c\u4e00\u8fb9\uff0c\u7136\u540e\u5f02\u6216\u8fd0\u7b97\u540e\u53c8\u7b49\u4e8e 0\n else:\n ret[1] ^= x # \u8fd9\u4e00\u6b65\u5176\u5b9e\u53ef\u4ee5\u4f18\u5316\uff0cret[1] = ret[0] ^ t(\u7b2c\u4e00\u6b21for\u540e\u7684t) \uff0c\u56e0\u4e3a t = ret[0] ^ ret[1]\n return ret\n\n\ndef main():\n nums = [1, 2, 1, 3, 2, 5]\n test = Solution()\n ret = test.singleNumber(nums)\n print(ret)\n\n\nif __name__ == '__main__':\n main()\n"} {"blob_id": "44effcf8ffce5c99b797a76a3fcaca921ef138ff", "repo_name": "PDorrian/classification-neural-network", "path": "/Matrix.py", "length_bytes": 3325, "score": 3.703125, "int_score": 4, "content": "import random\nimport numpy as np\n\n\nclass Matrix:\n def __init__(self, rows, cols):\n self.rows = rows\n self.cols = cols\n self.data = [[0] * cols for _ in range(rows)]\n\n def randomize(self):\n for i in range(self.rows):\n for j in range(self.cols):\n self.data[i][j] = random.uniform(-1, 1)\n\n @staticmethod\n def multiply(a, b):\n # Ensure matrices are the correct dimensions\n if a.cols != b.rows:\n print(\"Columns of A must match rows of B.\")\n else:\n result = Matrix(a.rows, b.cols)\n for i in range(result.rows):\n for j in range(result.cols):\n total = 0\n for k in range(a.cols):\n total += a.data[i][k] * b.data[k][j]\n result.data[i][j] = total\n return result\n\n def scale(self, n):\n if type(n) == Matrix:\n for i in range(self.rows):\n for j in range(self.cols):\n self.data[i][j] *= n.data[i][j]\n else:\n for i in range(self.rows):\n for j in range(self.cols):\n self.data[i][j] *= n\n\n def add(self, n):\n # Element-wise addition\n if type(n) == Matrix:\n for i in range(self.rows):\n for j in range(self.cols):\n self.data[i][j] += n.data[i][j]\n # Scalar addition\n else:\n for i in range(self.rows):\n for j in range(self.cols):\n self.data[i][j] += n\n\n @staticmethod\n def subtract(a, b):\n if a.rows == b.rows and a.cols == b.cols:\n result = Matrix(a.rows, a.cols)\n for i in range(a.rows):\n for j in range(a.cols):\n result.data[i][j] = a.data[i][j] - b.data[i][j]\n return result\n else:\n print(\"Matrices must have equal rows and columns for subtraction.\")\n\n @staticmethod\n def transpose(matrix):\n result = Matrix(matrix.cols, matrix.rows)\n for i in range(matrix.rows):\n for j in range(matrix.cols):\n result.data[j][i] = matrix.data[i][j]\n return result\n\n def print(self):\n for i in range(self.rows):\n for j in range(self.cols):\n print(\"{:8}\".format(self.data[i][j]), end=\" \")\n print(\"\")\n\n # Apply some function to each element in the matrix\n def map(self, func):\n for i in range(self.rows):\n for j in range(self.cols):\n val = self.data[i][j]\n self.data[i][j] = func(val)\n\n @staticmethod\n def map_static(matrix, func):\n result = Matrix(matrix.rows, matrix.cols)\n for i in range(result.rows):\n for j in range(result.cols):\n val = matrix.data[i][j]\n result.data[i][j] = func(val)\n return result\n\n @staticmethod\n def from_array(arr):\n matrix = Matrix(len(arr), 1)\n for i in range(len(arr)):\n matrix.data[i][0] = arr[i]\n return matrix\n\n @staticmethod\n def to_array(matrix):\n arr = []\n for i in range(matrix.rows):\n for j in range(matrix.cols):\n arr.append(matrix.data[i][j])\n return arr\n"} {"blob_id": "669077ee810f9970e43997c41078d78064e761cd", "repo_name": "bssrdf/pyleet", "path": "/F/FindWinneronaTicTacToeGame.py", "length_bytes": 3525, "score": 3.8125, "int_score": 4, "content": "'''\n-Medium-\n\nTic-tac-toe is played by two players A and B on a 3 x 3 grid.\n\nHere are the rules of Tic-Tac-Toe:\n\nPlayers take turns placing characters into empty squares (\" \").\nThe first player A always places \"X\" characters, while the second player B always places \"O\" characters.\n\"X\" and \"O\" characters are always placed into empty squares, never on filled ones.\nThe game ends when there are 3 of the same (non-empty) character filling any row, column, or diagonal.\nThe game also ends if all squares are non-empty.\nNo more moves can be played if the game is over.\nGiven an array moves where each element is another array of size 2 corresponding to the row and column \nof the grid where they mark their respective character in the order in which A and B play.\n\nReturn the winner of the game if it exists (A or B), in case the game ends in a draw return \"Draw\", \nif there are still movements to play return \"Pending\".\n\nYou can assume that moves is valid (It follows the rules of Tic-Tac-Toe), the grid is initially empty \nand A will play first.\n\n \n\nExample 1:\n\nInput: moves = [[0,0],[2,0],[1,1],[2,1],[2,2]]\nOutput: \"A\"\nExplanation: \"A\" wins, he always plays first.\n\"X \" \"X \" \"X \" \"X \" \"X \"\n\" \" -> \" \" -> \" X \" -> \" X \" -> \" X \"\n\" \" \"O \" \"O \" \"OO \" \"OOX\"\nExample 2:\n\nInput: moves = [[0,0],[1,1],[0,1],[0,2],[1,0],[2,0]]\nOutput: \"B\"\nExplanation: \"B\" wins.\n\"X \" \"X \" \"XX \" \"XXO\" \"XXO\" \"XXO\"\n\" \" -> \" O \" -> \" O \" -> \" O \" -> \"XO \" -> \"XO \" \n\" \" \" \" \" \" \" \" \" \" \"O \"\nExample 3:\n\nInput: moves = [[0,0],[1,1],[2,0],[1,0],[1,2],[2,1],[0,1],[0,2],[2,2]]\nOutput: \"Draw\"\nExplanation: The game ends in a draw since there are no moves to make.\n\"XXO\"\n\"OOX\"\n\"XOX\"\nExample 4:\n\nInput: moves = [[0,0],[1,1]]\nOutput: \"Pending\"\nExplanation: The game has not finished yet.\n\"X \"\n\" O \"\n\" \"\n \n\nConstraints:\n\n1 <= moves.length <= 9\nmoves[i].length == 2\n0 <= moves[i][j] <= 2\nThere are no repeated elements on moves.\nmoves follow the rules of tic tac toe.\n\n\n'''\n\nclass Solution(object):\n def tictactoe(self, moves):\n \"\"\"\n :type moves: List[List[int]]\n :rtype: str\n \"\"\"\n board = [[' ']*3 for _ in range(3)]\n def winner(x,y,c):\n cnt = 0 \n for i in range(3):\n if board[i][y] == c: cnt += 1\n if cnt == 3: return True\n cnt = 0 \n for j in range(3):\n if board[x][j] == c: cnt += 1\n if cnt == 3: return True \n if y-x == 0:\n cnt = 0 \n for i in range(3):\n if board[i][i] == c: cnt += 1\n if cnt == 3: return True\n if y+x == 2:\n cnt = 0 \n for i in range(3):\n if board[i][2-i] == c: cnt += 1\n if cnt == 3: return True\n return False\n steps = 0\n for i, (x,y) in enumerate(moves):\n (c,p) = ('X','A') if i%2==0 else ('O','B')\n board[x][y] = c\n steps += 1\n if steps >= 5:\n if winner(x, y, c): return p \n return 'Draw' if steps == 9 else 'Pending'\n\n\nif __name__ == \"__main__\":\n print(Solution().tictactoe([[0,0],[2,0],[1,1],[2,1],[2,2]]))\n print(Solution().tictactoe([[0,0],[1,1],[0,1],[0,2],[1,0],[2,0]]))\n print(Solution().tictactoe([[0,0],[1,1],[2,0],[1,0],[1,2],[2,1],[0,1],[0,2],[2,2]]))\n print(Solution().tictactoe([[2,0],[1,0],[1,1],[0,2]]))"} {"blob_id": "47b41d68d4ad9bbd5f039ee4cc9c275337f291fe", "repo_name": "gregorysimpson13/leetcode", "path": "/medium/longest_continuous_subarray_abs_dif.py", "length_bytes": 2527, "score": 3.75, "int_score": 4, "content": "# 1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit\n# https://leetcode.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/\n\n# Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.\n\n \n\n# Example 1:\n\n# Input: nums = [8,2,4,7], limit = 4\n# Output: 2 \n# Explanation: All subarrays are: \n# [8] with maximum absolute diff |8-8| = 0 <= 4.\n# [8,2] with maximum absolute diff |8-2| = 6 > 4. \n# [8,2,4] with maximum absolute diff |8-2| = 6 > 4.\n# [8,2,4,7] with maximum absolute diff |8-2| = 6 > 4.\n# [2] with maximum absolute diff |2-2| = 0 <= 4.\n# [2,4] with maximum absolute diff |2-4| = 2 <= 4.\n# [2,4,7] with maximum absolute diff |2-7| = 5 > 4.\n# [4] with maximum absolute diff |4-4| = 0 <= 4.\n# [4,7] with maximum absolute diff |4-7| = 3 <= 4.\n# [7] with maximum absolute diff |7-7| = 0 <= 4. \n# Therefore, the size of the longest subarray is 2.\n# Example 2:\n\n# Input: nums = [10,1,2,4,7,2], limit = 5\n# Output: 4 \n# Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5.\n# Example 3:\n\n# Input: nums = [4,2,2,2,4,4,2,2], limit = 0\n# Output: 3\n\n\nimport heapq\nfrom collections import defaultdict\ndef longestSubarray(nums, limit) -> int:\n max_length = 1\n min_heap, max_heap = [nums[0]], [-1 * nums[0]]\n min_removed_dict = defaultdict(int)\n max_removed_dict = defaultdict(int)\n heapq.heapify(min_heap)\n heapq.heapify(max_heap)\n start, end = 0, 0\n while end < len(nums) - 1:\n while abs(min_heap[0] - (-1 * max_heap[0])) <= limit:\n max_length = max(max_length, (end - start) + 1)\n if end >= len(nums) - 1: break\n end = end + 1\n heapq.heappush(min_heap, nums[end])\n heapq.heappush(max_heap, -1 * nums[end])\n left_item = nums[start]\n start = start + 1\n min_removed_dict[left_item] += 1\n max_removed_dict[left_item] += 1\n while min_removed_dict[min_heap[0]] > 0:\n min_removed_dict[min_heap[0]] -= 1\n heapq.heappop(min_heap)\n while max_removed_dict[-1 * max_heap[0]] > 0:\n max_removed_dict[-1 * max_heap[0]] -= 1\n heapq.heappop(max_heap)\n return max_length\n\n\n\nprint(longestSubarray([8,2,4,7], 4), 2)\nprint(longestSubarray([10,1,2,4,7,2], 5), 4)\nprint(longestSubarray([4,2,2,2,4,4,2,2], 0), 3)"} {"blob_id": "bfdbec052f94ce07a15d7966fe0d09866ad39254", "repo_name": "bsuncin/Demo_Code", "path": "/Fibonacci/Fibonacci_Recursive.py", "length_bytes": 866, "score": 4.3125, "int_score": 4, "content": "# The goal of this program is to show the exponential\r\n# time complexity of this naive approach to the \r\n# Fibonacci problem.\r\n\r\n#tracks the operations per calculation\r\noperations = 0\r\n\r\n# Accepts an position x as an integer. Calculates the \r\n# Fibonacci sequence up to position x. Returns the\r\n# Fibonacci number at position x.\r\ndef calcFib(x):\r\n global operations\r\n operations += 1\r\n\r\n if x == 0:\r\n return 0\r\n elif x == 1:\r\n return 1\r\n else:\r\n return calcFib(x - 1) + calcFib(x - 2)\r\n\r\ntry:\r\n while True:\r\n position = input('Enter the fib you want to calc: ')\r\n val = int(position)\r\n print('#: ' + str(calcFib(val)))\r\n print('# of operations: ' + str(operations))\r\n operations = 0 # resets operation count for a new operation\r\n\r\nexcept ValueError:\r\n pass # input was not a valid integer "} {"blob_id": "8e6175002aad3bee4ff7b06cfbc6579d045ebb25", "repo_name": "vrlambert/project_euler", "path": "/46_Goldbacks_other_conjecture.py", "length_bytes": 403, "score": 3.65625, "int_score": 4, "content": "from PE_useful import eratosthenes\n\nlimit = 10000\n\nprimes = eratosthenes(limit)\n\nodd_composites = set([])\n\nfor p in primes:\n num = 1\n while p + 2 * num ** 2 < limit:\n to_add = p + 2 * num ** 2\n if to_add % 2 == 1:\n odd_composites.add(to_add)\n num += 1\n\nfor n in range(3,limit,2):\n if n in primes:\n continue\n if n not in odd_composites:\n print n\n"} {"blob_id": "c084182c8f78512a2fc023c224af9480adea81ae", "repo_name": "ficherfisher/leetcode", "path": "/jumpGame.py", "length_bytes": 475, "score": 3.765625, "int_score": 4, "content": "\ndef canJump(self, nums: List[int]) -> bool:\n position = len(nums) - 1\n steps = 0\n tag = 1\n while position > 0:\n for i in range(position):\n if i + nums[i] >= position:\n position = i\n steps += 1\n tag = 0\n break;\n if tag == 1:\n return False\n else:\n tag = 1\n return True\n\n\nif __name__ == \"__main__\":\n nums = [3,2,1,0,4]\n print(canJump(nums))\n\n"} {"blob_id": "2b1c79735c5b72a79d27cba810fbd1a13da06cdb", "repo_name": "alexkie007/offer", "path": "/Target Offer/65. \u4e0d\u7528\u52a0\u51cf\u4e58\u9664\u505a\u52a0\u6cd5.py", "length_bytes": 399, "score": 3.75, "int_score": 4, "content": "'''\n\u5199\u4e00\u4e2a\u51fd\u6570\uff0c\u6c42\u4e24\u4e2a\u6574\u6570\u4e4b\u548c\uff0c\u8981\u6c42\u5728\u51fd\u6570\u4f53\u5185\u4e0d\u5f97\u4f7f\u7528+\u3001-\u3001*\u3001/\u56db\u5219\u8fd0\u7b97\u7b26\u53f7\u3002\n'''\n\n\"\"\"\n\u89e3\u9898\u601d\u8def\uff1a\n\u52a0\u6cd5\u662f\u5f02\u6216\uff0c\u8fdb\u4f4d\u662f\u4e0e<<1\n\"\"\"\n\n\nclass Solution:\n def Add(self, num1, num2):\n while num2:\n num1, num2 = (num1 ^ num2) & 0xFFFFFFFF, (num1 & num2) << 1 & 0xFFFFFFFF\n return num1 if num1 <= 0x7FFFFFFF else ~(num1 ^ 0xFFFFFFFF)\n"} {"blob_id": "291b702af22b5d35f530fb1d0cf8c956b74b7f0d", "repo_name": "jsutch/Python-Algos", "path": "/binary_search_tree-balance-and-functions.py", "length_bytes": 7126, "score": 4.1875, "int_score": 4, "content": "import random\n\nclass BSTNode(object):\n \"\"\"\n A node has a value,a left object and a right object.\n Create a tree by creating a new single node:\n usage: foo = BSTNode(512)\n \"\"\"\n def __init__(self, key):\n self.val = key\n self.left = self.right = None\n\n\n# BST Methods\ndef insert(root, node):\n \"\"\"\n insert the given key into the BST\n usage: insert(bsttree, BSTNode(val))\n insert(foo, BSTNode(random.randint(1,4096)))\n \"\"\"\n # case where root is empty\n if root is None:\n root = node\n else:\n # case where tree exists and value goes right\n if root.val < node.val:\n if root.right is None:\n root.right = node\n else:\n insert(root.right, node)\n else:\n if root.left is None:\n root.left = node\n else:\n insert(root.left, node)\n\n\ndef search(root, key):\n \"\"\"\n Does key exist in the BST?\n usage: search(foo, 555)\n returns: value or False\n \"\"\"\n if root is None:\n return False\n elif root.val == key:\n return root.val\n elif root.val > key:\n return search(root.left, key)\n return search(root.right, key)\n\n\ndef minvalue(node): \n \"\"\"\n return the smallest valued node. needed for delete\n \"\"\"\n cursor = node \n # loop down to find the leftmost leaf \n while(cursor.left is not None): \n cursor = cursor.left \n return cursor \n\n\ndef minvalueval(node): \n \"\"\"\n return the smallest valued node's value for testing\n \"\"\"\n cursor = node \n # loop down to find the leftmost leaf \n while(cursor.left is not None): \n cursor = cursor.left \n return cursor.val\n\n\ndef aslist(node):\n \"\"\"\n return inorder bst as a list. needed for randomval\n \"\"\"\n if node is None:\n return []\n return aslist(node.left) + [node.val] + aslist(node.right)\n\ndef randomval(root):\n \"\"\"\n return a random value from from the bst.\n utility to test delete. \n \"\"\"\n return random.choice(aslist(root))\n \ndef delete(root, key):\n \"\"\"\n returns a BST without the deleted value\n \"\"\"\n if root is None:\n return root\n # Is key in left or right?\n if key < root.val:\n root.left = delete(root.left, key)\n elif (key > root.val):\n root.right = delete(root.right, key)\n # Is root the key?\n else:\n # Case with no child\n if root.left is None:\n temp = root.right\n root = None\n return temp\n elif root.right is None:\n temp = root.left\n root = None\n return temp\n # with two children get the inOrder successor\n # smallest on right subtree\n temp = minvalue(root.right)\n root.val = temp.val\n root.right = delete(root.right, temp.val)\n #\n return root\n\n\n\n# Traversals\n# Depth First traversals\ndef inorder(root):\n \"\"\"\n DFT returns nodes in non-decreasing order\n print left -> root -> right\n \"\"\"\n if root:\n inorder(root.left)\n print(root.val)\n inorder(root.right)\n\ndef preorder(root):\n \"\"\"\n DFT used to create a copy of the tree\n print root -> left -> right\n \"\"\"\n if root:\n print(root.val)\n preorder(root.left)\n preorder(root.right)\n\ndef postorder(root):\n \"\"\"\n DFT - used to delete a tree\n print left -> right -> root\n \"\"\"\n if root:\n postorder(root.left)\n postorder(root.right)\n print(root.val)\n\n\n# Breadth first Traversals\ndef height(node):\n \"\"\"\n Find height of node. Needed for levelorder traversal\n \"\"\"\n if node is None:\n return 0\n else:\n lh = height(node.left)\n rh = height(node.right)\n #\n if lh > rh:\n return lh + 1\n else:\n return rh + 1\n\ndef givenlevel(root, level):\n \"\"\"\n find the givenlevel of the level. Needed for levelorder traversal\n \"\"\"\n if root is None:\n return\n if level == 1:\n print(root.val)\n elif level > 1:\n givenlevel(root.left, level -1)\n givenlevel(root.right, level -1)\n\ndef levelorder(root):\n \"\"\"\n levelorder is a Breadth First Traversal that prints all nodes per-level\n and iterates through the levels\n relies on height() and givenlevel() functions\n print all node values at level 1, then level 2, etc\n usage: levelorder(foo)\n \"\"\"\n h = height(root)\n for i in range(1, h + 1):\n givenlevel(root, i)\n\n\ndef printlevel(root):\n [(print(\"=== Level\", x, \"===\"), givenlevel(root, x)) for x in range(1,height(root))]\n\n\n# Balancing a tree\n# is a tree balanced?\ndef isbalanced(root):\n if root is None:\n return True\n return isbalanced(root.right) and isbalanced(root.left) and abs(height(root.left) - height(root.right)) <= 1\n\n#\n# breaking this into 3 parts - balance() is the wrapper, store() builds an inorder array of the values \n# and build() recursively rebuilds the inorder array into a balanced tree\n# handing back to balance() to return the BST object\n# creating an balanced BST from an unbalanced BST looks like this:\n# newobject = balance()\n#\ndef store(root, nodearr):\n \"\"\"\n recreate the bst as an inorder array.\n needed by balance\n \"\"\"\n if not root:\n return\n store(root.left, nodearr)\n nodearr.append(root.val)\n store(root.right, nodearr)\n\n\ndef build(nodearr):\n \"\"\"\n rebuild the bst from the inorder array\n needed by balance\n \"\"\"\n if not nodearr:\n return None\n mid = len(nodearr) // 2\n node = BSTNode(nodearr[mid])\n node.left = build(nodearr[:mid])\n node.right = build(nodearr[mid + 1:])\n return node\n\n\ndef balance(root):\n \"\"\"\n - get inorder traversal of existing BST as an array\n - create a new BST object sorted by the midpoint\n - return the object\n \"\"\"\n nodes = []\n store(root, nodes)\n return build(nodes)\n\n\n\n# Helper code\n# create and populate a tree\n\"\"\"\nfoo = BSTNode(500)\n[insert(foo, BSTNode(random.randint(1,1024))) for x in range(20)]\n\"\"\"\n\n# test harness\n# create tree\nfoo = BSTNode(500)\nIn [425]: type(foo)\nOut[425]: \n\nIn [426]: foo.val\nOut[426]: 500\n\n[insert(foo, BSTNode(random.randint(1,1024))) for x in range(20)]\nprint(\"printlevels\")\nprintlevel(foo)\n\n# Traversing\nprint(\"Traversing Utils\")\nprint(\"DFS traversing\")\nprint(\"inorder traverse\")\ninorder(foo)\nprint(\"preorder traverse\")\npreorder(foo)\nprint(\"postorder traverse\")\npostorder(foo)\nprint(\"BFS traversing\")\nlevelorder(foo)\n# Balancing\nprint(\"is balanced?\")\nisbalanced(foo)\nfoo = balance(foo)\nisbalanced(foo)\nprint(\"inorder - balanced\")\ninorder(foo)\nprint(aslist((foo)))\n\n# Deletes\nprint(\"show bst as a list\")\nprint(aslist(foo))\nrandvalue = randomval(foo)\nprint(f'grabbing random value <<{randvalue}>> from the bst for deletion')\nprint('verify value from search')\nprint(search(foo, randvalue))\nprint(\"Delete the value from the bst\")\nfoo = delete(foo, randvalue)\nprint(f'search for value >>{randvalue}<< in bst')\nprint(search(foo, randvalue))\nprint(aslist(foo))\nprint('is the new tree balanced?')\nprint(isbalanced(foo))\n"} {"blob_id": "2ee550729cc2c530f844f2ecead5d6f7d6db9026", "repo_name": "GZHOUW/Algorithm", "path": "/LeetCode Problems/DFS/Number of Islands.py", "length_bytes": 1858, "score": 3.765625, "int_score": 4, "content": "'''\nGiven a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.\n\nExample 1:\nInput:\n11110\n11010\n11000\n00000\nOutput: 1\n\nExample 2:\nInput:\n11000\n11000\n00100\n00011\nOutput: 3\n'''\n\nclass Solution():\n\n def countIslands(self, grid):\n self.grid = grid\n if len(self.grid) == 0: # edge case: no element\n return 0\n\n r = len(self.grid)\n c = len(self.grid[0])\n\n if r == 1 and c == 1: # edge case: one element\n return str(self.grid[0][0])\n\n count = 0\n for i in range(r):\n for j in range(c):\n if self.grid[i][j] == \"1\": # when encounter 1, add count, change the \"island\" to 0\n count += 1\n self.sinkIsland(i, j)\n return count\n\n def sinkIsland(self, i, j):\n neighbors = self.getNeighbors(i, j) # get the adjacent 1s to the current 1\n\n if not neighbors: # when there are no more adjacent 1\n return\n\n for idx in neighbors: # [(0, 2), (0, 0)]\n self.grid[idx[0]][idx[1]] = \"0\" # change current 1 to 0\n self.sinkIsland(idx[0], idx[1]) # sink the rest of island\n\n\n\n def getNeighbors(self, i, j):\n neighbors = []\n for idx in [(i-1, j), (i, j+1), (i+1, j), (i, j-1)]: # up, right, down, left\n if idx[0] >=0 and idx[0] < len(self.grid) and idx[1] >= 0 and idx[1] < len(self.grid[0]) and self.grid[idx[0]][idx[1]] == \"1\":\n neighbors.append(idx)\n return neighbors\n\ngrid = [[\"1\",\"1\",\"1\",\"1\",\"0\"],\n [\"1\",\"1\",\"0\",\"1\",\"0\"],\n [\"1\",\"1\",\"0\",\"0\",\"0\"],\n [\"0\",\"0\",\"0\",\"0\",\"0\"]]\n\na = Solution()\nprint(a.countIslands(grid))\n"} {"blob_id": "3b3c00e7cdf565194eb63709f347e66af31bafec", "repo_name": "quqixun/SIFTDescriptor", "path": "/classify_SIFT.py", "length_bytes": 4196, "score": 3.640625, "int_score": 4, "content": "# Created by Qixun Qu\n# quqixun@gmail.com\n# 2017/04/05\n#\n\n# This script provides functions for generating\n# SIFT descriptors on images which consist of\n# digits. This script and relative functions\n# are tested under Python 3.5.2.\n\n\nimport numpy as np\nimport generate_SIFT as gs\n\n\ndef prepare_digits(data_set, obj_pos):\n ''' PREPARE_DIGITS\n\n This function is to compute SIFT-like descriptors\n for each image in training set.\n\n Input argements:\n\n - data_set : a training set with 100 images\n - obj_pos : a matrix consists of the size of each\n training image and the position of centre\n\n Outputs:\n\n - data_desc : all descriptors of training images\n - data_labels : all labels for training images\n\n '''\n\n # Get the number of images in training set\n obj_num = data_set.shape[1]\n\n # Initialize outputs, in this case, there are 72\n # descriptors of every training image\n data_desc = np.zeros([1, obj_num, gs.DESC_ALL_NUM])\n data_labels = np.zeros([1, obj_num])\n\n for i in range(obj_num):\n # Calculate each training image's descriptor\n temp = gs.gradient_descriptor(data_set[0, i][0], obj_pos)\n data_desc[0, i] = temp.flatten()\n data_labels[0, i] = data_set[0, i][1]\n\n return data_desc, np.int32(data_labels)\n\n\ndef classify_digit(test, train_desc, train_labels, obj_pos):\n ''' CLASSIFY_DIGIT\n\n Get the label of one test image which consists of a digit.\n\n Input arguments:\n\n - test : a testing image contains one digit\n - train_desc, train_label : SIFT descriptors and labels\n for training images\n - obj_pos : a matrix consists of the size of each training\n image and the position of centre\n\n Output:\n\n - label : a number shows the digit in test set\n\n '''\n\n # Calculate the descriptor for test image\n # desc will be a 72 x 1 vector\n desc = gs.gradient_descriptor(test, obj_pos).flatten()\n\n # Initialize the distance to the maximum value, since the descriptor\n # vector has 72 elements that are normalized from 0 to 1, the maximum\n # distance between two descriptors is 72 according to the distance\n # equation: sum((desc1 - desc2)^2)\n dis = gs.DESC_ALL_NUM\n\n # Initialize the label for one test image, -1 is not included in\n # any posible results, if -1 appears in classification, which\n # means there are mistakes in the process of computing descriptors\n label = -1\n\n for i in range(train_desc.shape[1]):\n # Compare the descriptor of test image to each descriptor of\n # training image, calculate the distance between two descriptors\n dis_tmp = np.sum(np.power(desc - train_desc[0, i], 2))\n\n # Reserve the label of one training image that has\n # the minimum distance with the test image\n if dis_tmp < dis:\n dis = dis_tmp\n label = train_labels[0, i]\n\n return int(label)\n\n\ndef classify_all_digit(validate, train_desc, train_label, obj_pos):\n ''' CLASSIFY_ALL_DIGIT\n\n Classify all validation images in validation set and show\n classification result.\n\n Input argements:\n\n - validate : an image set contains 50 images with labels\n - train_desc, train_label : SIFT descriptors and labels\n for training images\n - obj_pos : a matrix consists of the size of each training\n image and the position of centre\n\n '''\n\n # Obtain the number of validation image\n obj_num = validate.shape[1]\n\n # Initialize the number of digits that\n # can be classified correctly\n right_pred = 0\n\n for i in range(obj_num):\n # Get label of ith validation image\n label = classify_digit(validate[0, i][0],\n train_desc, train_label, obj_pos)\n\n # Accumelate the number of digits that\n # can be classified correctly\n if label == validate[0, i][1]:\n right_pred += 1\n\n # Compute classification accuracy and print result\n accuracy = right_pred / obj_num * 100\n\n print(\"Validate all {} images,\".format(obj_num))\n print(\"{0:.2f}% validation images can be recognized.\".format(accuracy))\n\n return\n"} {"blob_id": "74a8c9372282cfe4c635e3ade0c383e45e04d80f", "repo_name": "filozyu/leetcode-journey", "path": "/src/backtracking/restore_ip_address.py", "length_bytes": 1374, "score": 3.703125, "int_score": 4, "content": "def restoreIpAddresses(s):\n \"\"\"\n Backtracking\n Time: O(1) since backtrack only considers at most the first 12 digits in s\n Space: O(1) size of curr_res is constant (4), so is the recursion stack\n \"\"\"\n res = []\n\n def backtrack(start, curr_res):\n # exit if we have used all s and ended up with four numbers\n if len(curr_res) == 4 and start == len(s):\n res.append(\".\".join(curr_res[:]))\n\n # each number can consists of 1 to 3 digits (range from 0 to 255)\n # note we do not need to check whether start + 3 <= len(s)\n # since the slicing below will stop when reaching the end\n for i in range(start, start+3):\n next_part = s[start: i + 1]\n # stop if the sliced part is None or the number is above 255\n if next_part == \"\" or int(next_part) > 255:\n break\n\n # stop if the sliced part contains more than 1 digit and the the first digit is 0\n if len(next_part) > 1 and next_part[0] == \"0\":\n break\n\n # stop if the length is already 4 (in this case start != len(s))\n if len(curr_res) >= 4:\n break\n\n curr_res.append(next_part)\n backtrack(i + 1, curr_res)\n curr_res.pop()\n\n backtrack(0, [])\n\n return res\n\n\ntest = \"010010\"\nprint(restoreIpAddresses(test))\n"} {"blob_id": "a4d9ed4727d5180cfe7bb87b4a9d99b114abbe4d", "repo_name": "ktp-forked-repos/algorithms-8", "path": "/python/maze_game/maze_ball_game.py", "length_bytes": 4775, "score": 4.03125, "int_score": 4, "content": "# !/bin/python\n\n\"\"\"\nProblem: There is a maze game where the ball can go in any of 4 directions. It can go all the way\nuntil it hits a wall or a block. Determine whether the ball can hit the exit cell.\n\nNotes: \n * I decided to represent walls as a list of tuples. They are indicating the map.\n * Start cell and maze exit cell are also tuples\n * size is indicating a size of maze.\n * I build a graph from these given data determining states (moves) of the ball as vertices of\n the graph.\n\"\"\"\n\nwalls = [(0, 0), (0, 5), (2, 5), (3, 1), (3, 2), (3, 5), (5, 0), (5, 2), (5, 3), (5, 5)]\n\nstart = (5, 3)\n\nmaze_exit = (2, 0)\n\nsize = 5\n\n\nclass Vertex(object):\n def __init__(self, coordinate: tuple):\n self.__first = coordinate[0]\n self.__second = coordinate[1]\n self.__neighbours = list()\n self.__visited = False\n\n @property\n def first(self):\n return self.__first\n\n @property\n def second(self):\n return self.__second\n\n @property\n def neighbours(self):\n return self.__neighbours\n\n @property\n def visited(self):\n return self.__visited\n\n @visited.setter\n def visited(self, value: bool):\n self.__visited = value\n\n def __str__(self):\n return '{0} {1}'.format(self.first, self.second)\n\n def __getitem__(self, item):\n if item == 0:\n return self.first\n if item == 1:\n return self.second\n\n def __eq__(self, other):\n return self.first == other.first and self.second == other.second\n\n\ndef construct_edge_tuples(vertex):\n return [(0, vertex.second), (size, vertex.second), (vertex.first, 0), (vertex.first, size)]\n\n\ndef get_neighbours(vertex, blocks):\n potential_neighbours = [neighbour for neighbour in blocks\n if vertex.first == neighbour[0] or vertex.second == neighbour[1]]\n potential_neighbours = list(set().union(potential_neighbours, construct_edge_tuples(vertex)))\n return potential_neighbours\n\n\ndef more_then_by_item(vertex1, vertex2, item_to_compare):\n return vertex1[item_to_compare] > vertex2[item_to_compare]\n\n\ndef validate_n(vertex: Vertex, neighbour: Vertex, blocks):\n for i in range(0, 2):\n index_to_compare = i+1 if not i else i-1\n if vertex[i] == neighbour[i]:\n coordinate_range = range(neighbour[index_to_compare]-1, vertex[index_to_compare], -1) \\\n if more_then_by_item(neighbour, vertex, index_to_compare) \\\n else range(vertex[index_to_compare]-1, neighbour[index_to_compare], -1)\n\n if not coordinate_range:\n return False\n for step in coordinate_range:\n step_tuple = (step, vertex[i]) if not index_to_compare else (vertex[i], step)\n if step_tuple in blocks:\n return False\n return True\n\n\nclass Graph(object):\n def __init__(self):\n self.__vertices = list()\n\n @property\n def vertices(self):\n return self.__vertices\n\n def add_edge(self, vertex, neighbour):\n if vertex not in self.vertices:\n self.vertices.append(vertex)\n if neighbour not in self.vertices:\n self.vertices.append(neighbour)\n\n if neighbour not in vertex.neighbours:\n vertex.neighbours.append(neighbour)\n\n def get_vertex_from_tuple(self, vertex_tuple):\n existing_v = [vertex for vertex in self.vertices\n if vertex.first == vertex_tuple[0] and vertex.second == vertex_tuple[1]]\n return existing_v[0] if existing_v else Vertex(vertex_tuple)\n\n def print_graph(self):\n print(\"Printing\")\n index = 0\n for v in self.vertices:\n print(\"round: \", index)\n print(v, end=' -> ' if v.neighbours else '\\n')\n for index, n in enumerate(v.neighbours):\n print(n, end=' -> ' if index != len(v.neighbours) - 1 else '\\n')\n index += 1\n print()\n\n\ndef find_exit(graph, start_coordinate, exit_coordinate):\n start_vertex = Vertex(start_coordinate)\n stack = list()\n stack.append(start_vertex)\n\n while stack:\n cur_v = stack.pop()\n cur_v.visited = True\n print(\"CURRENT\", cur_v)\n for neighbour in get_neighbours(cur_v, walls):\n neighbour_v = graph.get_vertex_from_tuple(neighbour)\n if validate_n(cur_v, neighbour_v, walls) and cur_v != neighbour_v:\n graph.add_edge(cur_v, neighbour_v)\n stack.append(neighbour_v) if not neighbour_v.visited else None\n graph.print_graph()\n return True if Vertex(exit_coordinate) in graph.vertices else False\n\n\nif __name__ == \"__main__\":\n graph = Graph()\n print(\"FOUND EXIT\") if find_exit(graph, start, maze_exit) else print(\"EXIT WAS NOT FOUND\")\n"} {"blob_id": "8a09879a9a767c9666111b993dc3ad4c34c747ed", "repo_name": "nezlobnaya/leetcode_solutions", "path": "/find_pairs_to_sum.py", "length_bytes": 965, "score": 4.28125, "int_score": 4, "content": "\"\"\"\nFind all the pairs of two integers in an unsorted array that sum up to a given S. For example, if the array is [3, 5, 2, -4, 8, 11] and the sum is 7, your program should return [[11, -4], [2, 5]] because 11 + -4 = 7 and 2 + 5 = 7.\n\"\"\"\n\n\n# we need to loop through the array\n# check the every pair of integers\n# return all pairs which sum up to S \n# creating a new array\n\ndef pair_integers(arr, S):\n result = []\n hash = {}\n for i in range(len(arr)):\n element = S - arr[i]\n if element in hash:\n result.append([arr[i], element])\n else:\n hash[arr[i]] = arr[i]\n return result[::-1]\n \n\n\n\n# def pair_integers(arr, S):\n# result = []\n# for i in range(len(arr)):\n# for j in range(i + 1, len(arr)):\n# if arr[i] + arr[j] == S:\n# result.append([arr[j], arr[i]])\n# # else:\n# # return None\n# return result[::-1]\n\narr = [3, 5, 2, -4, 8, 11]\nS = 7\n\nprint(pair_integers(arr, S))\n# output [[11, -4], [2, 5]]"} {"blob_id": "983d4a37dbc462349636524d6b387506025c8807", "repo_name": "rupampatil/InterviewPractice", "path": "/LeetCode/numberOfIslands.py", "length_bytes": 853, "score": 3.5, "int_score": 4, "content": "class Solution(object):\n def numIslands(self, grid):\n \"\"\"\n :type grid: List[List[str]]\n :rtype: int\n \"\"\"\n if not grid:\n return 0\n islands = 0\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] == \"1\":\n islands+=1\n #Ru\n self.DFS(grid, i, j) \n return islands\n \n def DFS(self, grid, x, y):\n #check if coordinate is valid and is land\n if ((x < 0) or (x >= len(grid)) or (y < 0) or (y >= len(grid[0])) or (grid[x][y] != '1')):\n return\n #mark as visited\n grid[x][y] = \"X\"\n #perform DFS on neighbors\n self.DFS(grid, x+1, y)\n self.DFS(grid, x-1, y)\n self.DFS(grid, x, y+1)\n self.DFS(grid, x, y-1)\n "} {"blob_id": "e57c9ba5abc2279c010029aa0dd4f29427f3c92c", "repo_name": "ashwinashok9111993/eegpy", "path": "/doc/examples/som.py", "length_bytes": 4015, "score": 3.921875, "int_score": 4, "content": "#!/usr/bin/env python\n# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-\n# vi: set ft=python sts=4 ts=4 sw=4 et:\n### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n#\n# See COPYING file distributed along with the PyMVPA package for the\n# copyright and license terms.\n#\n### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n\"\"\"\nSelf-organizing Maps\n====================\n\n.. index:: mapper, self-organizing map, SOM, SimpleSOMMapper\n\nThis is a demonstration of how a self-organizing map (SOM), also known\nas a Kohonen network, can be used to map high-dimensional data into a\ntwo-dimensional representation. For the sake of an easy visualization\n'high-dimensional' in this case is 3D.\n\nIn general, SOMs might be useful for visualizing high-dimensional data\nin terms of its similarity structure. Especially large SOMs (i.e. with\nlarge number of Kohonen units) are known to perform mappings that\npreserve the topology of the original data, i.e. neighboring data\npoints in input space will also be represented in adjacent locations\non the SOM.\n\nThe following code shows the 'classic' color mapping example, i.e. the\nSOM will map a number of colors into a rectangular area.\n\"\"\"\n\nfrom mvpa.suite import *\n\n\"\"\"\nFirst, we define some colors as RGB values from the interval (0,1),\ni.e. with white being (1, 1, 1) and black being (0, 0, 0). Please\nnote, that a substantial proportion of the defined colors represent\nvariations of 'blue', which are supposed to be represented in more\ndetail in the SOM.\n\"\"\"\n\ncolors = np.array(\n [[0., 0., 0.],\n [0., 0., 1.],\n [0., 0., 0.5],\n [0.125, 0.529, 1.0],\n [0.33, 0.4, 0.67],\n [0.6, 0.5, 1.0],\n [0., 1., 0.],\n [1., 0., 0.],\n [0., 1., 1.],\n [1., 0., 1.],\n [1., 1., 0.],\n [1., 1., 1.],\n [.33, .33, .33],\n [.5, .5, .5],\n [.66, .66, .66]])\n\n# store the names of the colors for visualization later on\ncolor_names = \\\n ['black', 'blue', 'darkblue', 'skyblue',\n 'greyblue', 'lilac', 'green', 'red',\n 'cyan', 'violet', 'yellow', 'white',\n 'darkgrey', 'mediumgrey', 'lightgrey']\n\n\"\"\"\nNow we can instantiate the mapper. It will internally use a so-called\nKohonen layer to map the data onto. We tell the mapper to use a\nrectangular layer with 20 x 30 units. This will be the output space of\nthe mapper. Additionally, we tell it to train the network using 400\niterations and to use custom learning rate.\n\"\"\"\n\nsom = SimpleSOMMapper((20, 30), 400, learning_rate=0.05)\n\n\"\"\"\nFinally, we train the mapper with the previously defined 'color' dataset.\n\"\"\"\n\nsom.train(colors)\n\n\"\"\"\nEach unit in the Kohonen layer can be treated as a pointer into the\nhigh-dimensional input space, that can be queried to inspect which\ninput subspaces the SOM maps onto certain sections of its 2D output\nspace. The color-mapping generated by this example's SOM can be shown\nwith a single matplotlib call:\n\"\"\"\n\npl.imshow(som.K, origin='lower')\n\n\"\"\"\nAnd now, let's take a look onto which coordinates the initial training\nprototypes were mapped to. The get those coordinates we can simply feed\nthe training data to the mapper and plot the output.\n\"\"\"\n\nmapped = som(colors)\n\npl.title('Color SOM')\n# SOM's kshape is (rows x columns), while matplotlib wants (X x Y)\nfor i, m in enumerate(mapped):\n pl.text(m[1], m[0], color_names[i], ha='center', va='center',\n bbox=dict(facecolor='white', alpha=0.5, lw=0))\n\n\"\"\"\nThe text labels of the original training colors will appear at the 'mapped'\nlocations in the SOM -- and should match with the underlying color.\n\"\"\"\n\n# show the figure\nif cfg.getboolean('examples', 'interactive', True):\n pl.show()\n\n\"\"\"\nThe following figure shows an exemplary solution of the SOM mapping of the\n3D color-space onto the 2D SOM node layer:\n\n.. image:: ../pics/ex_som.*\n :align: center\n :alt: Color-space mapping by a self-organizing map.\n\n\"\"\"\n"} {"blob_id": "d25708b5b39b8e96e2d5de2c4e000ec4fff588ea", "repo_name": "sajjjadayobi/sadlearn", "path": "/Algorithm/Clustering/DBSCAN.py", "length_bytes": 2450, "score": 3.75, "int_score": 4, "content": "import numpy as np\r\n\r\n\"\"\"\r\nDBSCAN.py\r\ndetail: Clustering Algorithm \r\n\r\nauthor: sajjad ayobi\r\nsee others in repository : sadlearn\r\nin URL: https://github.com/sajjjadayobi/sadlearn/\r\n\r\ndate : 10/5/2018\r\n\"\"\"\r\n\r\n\r\nclass DBSCAN:\r\n \"\"\"\r\n DBSCAN is a Algorithm for clustering also can find Noise in data\r\n Good for data which contains clusters of similar density\r\n\r\n Parameters\r\n ----------\r\n x: list or np.ndarrary , most\r\n Data in the from of a matrix\r\n\r\n epsilon: float, optional\r\n maximum distance between tow sample in one class\r\n\r\n min_point: int, optional\r\n minimum number of sample in one class\r\n if neighbor of a sample was less than min_point, this sample is a Noise\r\n\r\n Attributes\r\n ----------\r\n labels: list of class number\r\n\r\n Note\r\n ----\r\n -1 in labels means it sample is Noise\r\n\r\n for example\r\n -----------\r\n >>> import numpy as np\r\n\r\n >>> db = DBSCAN(np.array())\r\n >>> labels = db.labels\r\n\r\n \"\"\"\r\n def __init__(self, x, epsilon=0.5, min_point=5):\r\n self.x = x\r\n self.eps = epsilon\r\n self.m_p = min_point\r\n\r\n def neighbor_points(self, x, k):\r\n neighbors = []\r\n for i in range(len(x)):\r\n # ouclidean distance\r\n if np.sqrt(np.square(x[k] - x[i]).sum()) < self.eps:\r\n neighbors.append(i)\r\n return neighbors\r\n\r\n def expand_cluster(self, labels, i, class_id):\r\n\r\n neighbors = self.neighbor_points(self.x, i)\r\n if len(neighbors) < self.m_p:\r\n labels[i] = -1\r\n return False\r\n\r\n for i in neighbors:\r\n labels[i] = class_id\r\n while len(neighbors) > 0:\r\n current = neighbors[0]\r\n new_neighbors = self.neighbor_points(self.x, current)\r\n\r\n if len(new_neighbors) >= self.m_p:\r\n for i in range(len(new_neighbors)):\r\n point = new_neighbors[i]\r\n if labels[point] is None:\r\n labels[point] = class_id\r\n neighbors.append(point)\r\n del neighbors[0]\r\n\r\n return True\r\n\r\n @property\r\n def labels(self):\r\n x = self.x\r\n labels = np.array([None] * len(x))\r\n\r\n class_id = 1\r\n for i in range(len(x)):\r\n if labels[i] is None:\r\n if self.expand_cluster(labels, i, class_id):\r\n class_id += 1\r\n return labels\r\n"} {"blob_id": "7cc49755b5b7b40c57ee4277053ecc9164c45508", "repo_name": "fengjiaxin/leetcode", "path": "/code/tree/129. Sum Root to Leaf Numbers.py", "length_bytes": 2334, "score": 4.0625, "int_score": 4, "content": "#!/usr/bin/env python \n# -*- coding: utf-8 -*-\n# @Time : 2019-07-16 09:11\n# @Author : \u51af\u4f73\u6b23\n# @File : 129. Sum Root to Leaf Numbers.py\n# @Desc :\n'''\n\nGiven a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.\n\nAn example is the root-to-leaf path 1->2->3 which represents the number 123.\n\nFind the total sum of all root-to-leaf numbers.\n\nNote: A leaf is a node with no children.\n\nExample:\n\nInput: [1,2,3]\n 1\n / \\\n 2 3\nOutput: 25\nExplanation:\nThe root-to-leaf path 1->2 represents the number 12.\nThe root-to-leaf path 1->3 represents the number 13.\nTherefore, sum = 12 + 13 = 25.\nExample 2:\n\nInput: [4,9,0,5,1]\n 4\n / \\\n 9 0\n / \\\n5 1\nOutput: 1026\nExplanation:\nThe root-to-leaf path 4->9->5 represents the number 495.\nThe root-to-leaf path 4->9->1 represents the number 491.\nThe root-to-leaf path 4->0 represents the number 40.\nTherefore, sum = 495 + 491 + 40 = 1026.\n'''\n\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n import math\n def sumNumbers(self, root: TreeNode) -> int:\n '''\n \u601d\u8def\uff1a\u5b58\u50a8\u6240\u6709\u6839\u8282\u70b9\u5230\u53f6\u5b50\u8282\u70b9\u7684\u7684\u8def\u5f84\u7684\u503c\uff0c\u8fd9\u4e2a\u80af\u5b9a\u4f7f\u7528\u56de\u6eaf\u6cd5\n '''\n if not root:\n return 0\n res_list = []\n temp_list = []\n\n def dfs_helper(node):\n # \u5982\u679c\u662f\u53f6\u5b50\u8282\u70b9\n if not node.left and not node.right:\n temp_list.append(node.val)\n res_list.append(temp_list.copy())\n temp_list.pop(-1)\n if node.left:\n temp_list.append(node.val)\n dfs_helper(node.left)\n temp_list.pop(-1)\n if node.right:\n temp_list.append(node.val)\n dfs_helper(node.right)\n temp_list.pop(-1)\n\n dfs_helper(root)\n\n def get_num(num_list):\n res_num = 0\n for index, num in enumerate(num_list[::-1]):\n res_num = res_num + num * int(math.pow(10, index))\n print(num_list[::-1])\n print(res_num)\n return res_num\n\n res_num = 0\n for temp in res_list:\n res_num += get_num(temp)\n return res_num\n"} {"blob_id": "a543509c1d2b22e1ce0429e27be4801be13e9eaf", "repo_name": "paulrodriguez/daily-coding-problem", "path": "/problem_229.py", "length_bytes": 1500, "score": 4.09375, "int_score": 4, "content": "'''\nSnakes and Ladders is a game played on a 10 x 10 board, the goal of which is get from square 1 to square 100. \nOn each turn players will roll a six-sided die and move forward a number of spaces equal to the result. \nIf they land on a square that represents a snake or ladder, \nthey will be transported ahead or behind, respectively, to a new square.\n\nFind the smallest number of turns it takes to play snakes and ladders.\n'''\nfrom collections import defaultdict\n\ndef minTurns(snakes,ladders):\n\tcurr, moves = 0,0\n\tvisited = defaultdict(bool)\n\to = []\n\treturn dfs(snakes,ladders,curr,moves,visited,o)\n\ndef dfs(snakes,ladders,curr,moves,visited,o):\n\t#print(curr)\n\tif curr == 100:\n\t\t#print('moves',moves)\n\t\t#print(o)\n\t\treturn moves\n\n\tif curr in snakes:\n\t\tcurr = snakes[curr]\n\t\tif visited[curr] == True:\n\t\t\treturn float('inf')\n\n\tif curr in ladders:\n\t\tcurr = ladders[curr]\n\t\tif visited[curr] == True:\n\t\t\treturn float('inf')\n\t\n\tvisited[curr] = True\n\tbest = float('inf')\n\tfor i in range(1,7):\n\t\tn = curr + i\n\t\t#print(curr,i,(curr+i),o,visited[n])\n\t\tif visited[n] == True or n > 100:\n\t\t\t#print('have visited',n)\n\t\t\tcontinue\n\n\t\t\n\t\t#visited[n] = True\n\t\to.append(curr+i)\n\t\tbest = min(best,dfs(snakes,ladders,curr+i,moves+1,visited,o))\n\t\to.pop()\n\t\t#visited[n] = False\n\tvisited[curr] = False\n\treturn best\n\nsnakes = {16: 6, 48: 26, 49: 11, 56: 53, 62: 19, 64: 60, 87: 24, 93: 73, 95: 75, 98: 78}\nladders = {1: 38, 4: 14, 9: 31, 21: 42, 28: 84, 36: 44, 51: 67, 71: 91, 80: 100}\n\nprint(minTurns(snakes,ladders))\n"} {"blob_id": "0b3c840cc1b1568c09a54fb50ef1ede8662ced1b", "repo_name": "ImrulKayes/DataStructuresAlgorithms", "path": "/HashMap and Array-2.py", "length_bytes": 12491, "score": 3.8125, "int_score": 4, "content": "class Solution:\r def firstNonrepeated1(self, st):\r \"Given a string, find the first non-repeating character in it.\"\r \"two pass solution, an optimization is below, consider the string might be very large\"\r dic={}\r for i in range(len(st)):\r dic[st[i]]=dic.get(st[i],0)+1\r for char in st:\r if dic[char]==1:\r return char\r return '-1'\r \r def firstNonrepeated(self, st):\r \"rather than treaversing the string twice, we can treaverse the count dic in the second pass\"\r dic={}\r for i in range(len(st)):\r \"along with count, we are keeping track when the char is first seen\"\r if dic.has_key(st[i]):\r dic[st[i]]=[dic[st[i]][0]+1,dic[st[i]][1]]\r else:\r dic[st[i]]=[1,i]\r\r res='-1'\r min=float('inf')\r \"need to find a char with count 1 and least index\"\r for k,v in dic.iteritems():\r if v[0]==1:\r if v[1]=0 and j>=0:\r sum=c+int(a[i])+int(b[j])\r output.append(str(sum%2))\r c=sum/2\r i-=1\r j-=1\r\r if i>=0:\r k=i\r while k>=0:\r sum=c+int(a[k])\r output.append(str(sum%2))\r c=sum/2\r k-=1 \r if j>=0:\r k=j\r while k>=0:\r sum=c+int(b[k])\r output.append(str(sum%2))\r c=sum/2\r k-=1 \r if c==1:\r output.append('1')\r\r return ''.join(output)[::-1]\r\r def lengthOfLastWord(self, s):\r \"\"\"\r return the lenght of last word in string s, might be leading and trailing zeros\r \"\"\"\r if not s:\r return 0\r\r for i in range(len(s)-1,-1,-1):\r if s[i]!=' ':\r break\r for j in range(i,-1,-1):\r if s[j]==' ':\r return len(s[j+1:i+1])\r return len(s[j:i+1])\r\r\r def isPalindrome(self, s):\r \"\"\"\r palindrome, only consider alphaneumaric\r \"\"\"\r if not s:\r return True\r s=s.lower()\r s1=[]\r\r for x in s:\r if (x>='a' and x<='z') or (x>='0' and x<='9'):\r s1.append(x)\r\r mid=len(s1)/2\r for i in range(mid):\r if s1[i]!=s1[len(s1)-1-i]:\r\r return False\r\r return True\r\r\r def strStr(self, haystack, needle):\r \"\"\"\r find first index of needle in haystack\r \"\"\"\r if not needle:\r return 0\r\r if not haystack:\r return -1\r\r for i in range(len(haystack)-(len(needle)-1)):\r if haystack[i:i+len(needle)]==needle:\r return i\r return -1 \r \r def findSubArray(self,nums,target):\r \"In an Array, find the Contiguous Subarray with Sum to a Given Value.\"\r \"keep two pointers, increse front if more elements needed, adjust tail if sum is greater\"\r \r if not nums: return []\r head,tail=0,0\r currSum=0\r while headtarget:\r currSum-=nums[tail]\r tail+=1\r else:\r currSum+=nums[head]\r head+=1\r return []\r \r def nextGreaterElement(self,nums):\r # Given an array, print the Next Greater Element (NGE) for every element.\r # The Next greater Element for an element x is the first greater element on the right side of x in array. Elements for which no greater element exist, consider next greater element as -1.\r # solution: push first element in a stack, for rest of the element if the element is geater than top of the stack pop all of the elements that are smaller, for them the element in the next greater\r # otherwise push the element in the stack, finally the elements remain in the stack have no next, so set -1 in output\r \r if not nums: return\r q=[nums[0]]\r for i in range(1,len(nums)):\r next=nums[i]\r if q:\r if q[-1]=s'\r 'sort and start collecting elements from the back O(nlogn), a better solution is below'\r b=sorted(nums)\r print b\r sum=0\r count=0\r\r for i in xrange(len(b)-1,-1,-1):\r sum+=nums[i]\r count+=1\r if sum>=s:\r return count\r return 0\r\r # also try to solve it by DP\r def minSubArrayLen(self, s, nums):\r # given n positive numbers and s, find min length subarry such that sums>=s\r # keep two pointers, current one adds new element, if sums>=s adjust minLength by incrementing first pointer to the nextest element where also sums>=s \r minLen, total, start = len(nums) + 1, 0, 0\r for i in range(len(nums)):\r total += nums[i]\r while total >= s:\r minLen=min(i - start + 1, minLen)\r total-= nums[start]\r start+=1\r return 0 if minLen > len(nums) else minLen \r \rsolution=Solution()\r#print solution.findSubArray([25, 12, 14, 22, 19, 15, 10, 23],55)\r#solution.nextGreaterElement([11, 13, 21, 3])\r#print solution.canPair([92, 75, 65, 48, 45, 35],10)\r#print solution.minDist([3, 5, 4, 2, 6, 3, 0, 0, 5, 4, 8, 3],3,6)\r#print solution.segNums([0, 1, 0, 1, 1, 1])\r\rdef hightestWaster(nums):\r #Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. http://www.geeksforgeeks.org/trapping-rain-water/\r # for each bar calculate higher left and right bar including itself\r # water trapper in a num is equal to min(left[i],right[i])-nums[i]\r \r left=[nums[i] for i in range(len(nums))]\r right=[nums[i] for i in range(len(nums))]\r for i in range(1,len(nums)):\r left[i]=max(left[i-1],nums[i])\r for i in range(len(nums)-2,-1,-1):\r right[i]=max(right[i+1],nums[i])\r waterVolume=0\r for i in range(len(nums)):\r waterVolume+=min(left[i],right[i])-nums[i]\r return waterVolume\r\r#print hightestWaster([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1])\r"} {"blob_id": "892179d480a4418ff5af670d62b4465f3765f786", "repo_name": "lengzhang/ucr_cs141_programming_assignment", "path": "/Programing_HW1/project/nearest_neighbor.py", "length_bytes": 4361, "score": 3.625, "int_score": 4, "content": "import sys\n\nclass Point :\n def __init__(self, x_val, y_val):\n self.x = x_val\n self.y = y_val\n\n def __repr__(self):\n return \"(%.2f, %.2f)\" % (self.x, self.y)\n\ndef Read_Points_From_Command_Line_File():\n points = []\n number_of_args = len(sys.argv)\n file = open(sys.argv[1],\"r\")\n\n for line in file:\n line.strip()\n x_y = line.split(\" \")\n points.append(Point(float(x_y[0]),float(x_y[1])))\n\n return points\n\ndef Write_to_File(filename, s):\n output = open(filename ,'w')\n output.write(str(s))\n output.write('\\n')\n\ndef Sort_by_x(points):\n for i in range(0,len(points)-1):\n for j in range(i+1,len(points)):\n if float(points[i].x) > float(points[j].x):\n temp = points[i]\n points[i] = points[j]\n points[j] = temp\n return points\n\ndef Sort_by_y(points):\n for i in range(0,len(points)-1):\n for j in range(i+1,len(points)):\n if float(points[i].y) > float(points[j].y):\n temp = points[i]\n points[i] = points[j]\n points[j] = temp\n return points\n\ndef Brute_Force(points):\n min_distance = 0;\n for i in range(0,len(points)-1):\n for j in range(i+1, len(points)):\n distances = ( (points[i].x - points[j].x) ** 2 + (points[i].y - points[j].y) ** 2 ) ** 0.5\n if i == 0 and j == 1:\n min_distance = distances\n else:\n if min_distance > distances:\n min_distance = distances\n return min_distance\n\ndef Divide_and_Conquer(points):\n # Step 1: Find a value mid_x for which exactly half the points have x_i < mid_x, and half have x_i > mid_x.\n # On this basis, split the points into two groups L and R.\n mid_x = (points[0].x + points[len(points) - 1].x) / 2\n #if (len(points) % 2) == 0:\n # mid_x = (points[(len(points) / 2) - 1].x + points[len(points) / 2].x) / 2\n #else:\n # mid_x = (points[len(points) // 2].x + points[(len(points) // 2) + 1].x) / 2\n points_L = []\n points_R = []\n for i in range(0,len(points)):\n if points[i].x < mid_x:\n points_L.append(points[i])\n else:\n points_R.append(points[i])\n # Step 2: Recursively n_d the closest pair in L and in R. Say these pairs are p_L1 and p_L2 in L and\n # p_R1 and q_R2 in R, with distances d_L and d_R respectively. Let d be the smaller of these\n # two distances.\n d_L = Brute_Force(points_L)\n d_R = Brute_Force(points_R)\n d = 0\n if d_L > d_R:\n d = d_R\n else:\n d = d_L\n # Step 3: It remains to be seen whether there is a point in L and a point in R that are less than distance d\n # apart from each other. To this end, discard all points with x_i < x - d or x_i > x + d and sort the\n # remaining points by their y-coordinate.\n new_points = []\n for i in range(0,len(points)):\n if points[i].x >= (mid_x - d) and points[i].x <= (mid_x + d):\n new_points.append(points[i])\n # Step 4: Case 1 - Less than 2 points with x_i < x - d or x_i > x + d in new_points\n # return the minimized distance between d_L and d_R\n if len(new_points) < 2:\n return d\n # Case 2 - More than 1 points with x_i < x - d or x_i > x + d in new_points\n # Sort new_points and list, and for each point, compute its distance\n # to the subsequent points in the list.\n # Return the minimized distance.\n else:\n new_points = Sort_by_y(new_points)\n d_M = Brute_Force(new_points)\n if d_M > d:\n return d\n else:\n return d_M\n\nimport timeit\npoints = Read_Points_From_Command_Line_File()\npoints = Sort_by_x(points)\n\n#Brute Force\nstart_BF = timeit.default_timer()\nmin_distance_by_BF = Brute_Force(points)\nstop_BF = timeit.default_timer()\nBF_time = float(stop_BF - start_BF)\n\n#Divide and Conquer\nstart_DC = timeit.default_timer()\nmin_distance_by_DC = Divide_and_Conquer(points)\nstop_DC = timeit.default_timer()\nDC_time = float(stop_DC - start_DC)\n\nprint(\"Brute Force time: \" + str(BF_time))\nprint(\"Divide and Conquer time: \" + str(DC_time))\n\nWrite_to_File(sys.argv[1].split('.')[0] + \"_distance.txt\", min_distance_by_DC)\n"} {"blob_id": "18e872f023432253f172b98de04359a3720189b1", "repo_name": "eroicaleo/LearningPython", "path": "/interview/leet/099_Recover_Binary_Search_Tree_v2.py", "length_bytes": 2342, "score": 4.0, "int_score": 4, "content": "import queue\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\ndef treeBuilder(nodeString):\n nodeList = nodeString[1:-1].split(',')\n nodeQueue = queue.Queue()\n root = TreeNode(int(nodeList[0]))\n currNode = root\n leftDone, rightDone = 0, 0\n for val in nodeList[1:]:\n print('processing %s' % val)\n print('leftDone,', leftDone, 'rightDone,', rightDone)\n if val != 'null':\n newNode = TreeNode(int(val))\n print(\"create new node: %d\" % newNode.val)\n nodeQueue.put(newNode)\n else:\n newNode = None\n\n if leftDone == 0:\n currNode.left, leftDone = newNode, 1\n elif rightDone == 0:\n currNode.right, rightDone = newNode, 1\n leftDone, rightDone = 0, 0\n currNode = nodeQueue.get()\n return root\n\ndef traverse(node):\n print('Node: %d' % node.val)\n if node.left != None:\n print('Left: %d' % node.left.val)\n if node.right != None:\n print('Right: %d' % node.right.val)\n if node.left != None:\n traverse(node.left)\n if node.right != None:\n traverse(node.right)\n\nclass Solution:\n def __init__(self):\n self.prev = None\n self.head = None\n self.tail = None\n self.max = None\n\n def recoverTree(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: void Do not return anything, modify root in-place instead.\n \"\"\"\n self.dualNode(root)\n self.head.val, self.tail.val = self.tail.val, self.head.val\n\n def dualNode(self, node):\n if node == None:\n return\n self.dualNode(node.left)\n if self.prev != None:\n if self.head == None and self.prev.val > node.val:\n self.head = self.prev\n self.prev = node\n if self.max == None or node.val > self.max:\n self.max = node.val\n if node.val < self.max:\n self.tail = node\n self.dualNode(node.right)\n\nsol = Solution()\nnodeString = '[1,3,null,null,2]'\nnodeString = '[3,1,4,null,null,2]'\nnodeString = '[3,null,2,null,1]'\nnodeString = '[2,3,1]'\nroot = treeBuilder(nodeString)\ntraverse(root)\nsol.dualNode(root)\nprint(sol.head.val, sol.tail.val)\nsol.recoverTree(root)\n"} {"blob_id": "b1753c04d2602b289f9633aaec75e07762b6e94a", "repo_name": "research-reuse/PISA", "path": "/pisa_basic/build_features.py", "length_bytes": 3649, "score": 3.609375, "int_score": 4, "content": "import random\n\ndef rSquared(observed, predicted):\n \"\"\"Calculate r-squared value for given data\"\"\"\n error = ((predicted-observed)**2).sum()\n mean_error = error/len(observed)\n return 1 - (mean_error/np.var(observed))\n\ndef gen_fits(x, y, degrees):\n \"\"\"Compute coefficients for given degree polynomial\n :param x: data frame\n :param y: data frame\n :param degrees: list\n :returns array list\"\"\"\n models = []\n for d in degrees:\n model = pylab.polyfit(x, y, d)\n models.append(model)\n return models\n\ndef test_fits(models, degrees, x, y):\n \"\"\"Compute R-squared value for given models with various polynomial degrees\n :param models: array list\n :param degrees: list\n :param x: data frame\n :param y: data frame\n :returns fit_goodness: dict\"\"\"\n fit_goodness = {}\n for i in range(len(models)):\n est_y = pylab.polyval(models[i], x)\n error = rSquared(y, est_y)\n fit_goodness[i] = error\n return fit_goodness\n\ndef test_fits_plot(models, degrees, x, y, title):\n \"\"\"Compute R-squared value for given models with various polynomial degrees\n and display results within a plot\n :param models: array list\n :param degrees: list\n :param x: data frame\n :param y: data frame\n :param title: str\"\"\"\n pylab.plot(x, y, 'o', label='Data')\n for i in range(len(models)):\n est_y = pylab.polyval(models[i], x)\n error = rSquared(y, est_y)\n pylab.plot(x, est_y, label='Fit of degree' + str(degrees[i])+', R2 = ' + str(round(error, 5)))\n pylab.legend(loc='best')\n pylab.title(title)\n\ndef test_fits_sea(models, degrees, x, y, title,):\n sns.regplot(x, y, fit_reg=False, label='Data')\n for i in range(len(models)):\n sns.regplot(x, y, order=i, line_kws={\"color\": \"r\", \"alpha\": 0.4, \"lw\": 5},\n label='Fit of degree' + str(degrees[i]))\n plt.title(title)\n\ndegrees = (1, 2, 3, 4)\nmodels = gen_fits(pisa_ave_gdp_ppp_log['gdp_ppp_log'], pisa_ave_gdp_ppp_log['ave_result'], degrees)\ntest_fits_sea(models, degrees, pisa_ave_gdp_ppp_log['gdp_ppp_log'], pisa_ave_gdp_ppp_log['ave_result'], 'Goodness of fit')\n\n\n\n\ndef split_data(x, y):\n \"\"\"Split data set into subsets for training and testing\n :param x: data frame column\n :param y: data frame column\n :returns 4 lists\"\"\"\n to_train = random.sample(range(len(x)), len(x) // 2)\n train_x, train_y, test_x, test_y = [], [], [], []\n for i in range(len(x)):\n if i in to_train:\n train_x.append(x[i])\n train_y.append(y[i])\n else:\n test_x.append(x[i])\n test_y.append(y[i])\n return train_x, train_y, test_x, test_y\n\ndef compare_predictive_power(num_subsets, degrees, x, y):\n \"\"\"Take data set and perform cross-validation using repeated random sampling,\n print R-squared and standard deviation for each dimension model\n :param num_subsets: int\n :param degrees: list\n :param x: data frame\n :param y: data frame\"\"\"\n r_squares = {}\n results = pd.DataFrame(index=range(1, 1+len(degrees)), columns=['mean', 'sd'])\n for d in degrees:\n r_squares[d] = []\n for f in range(num_subsets):\n train_x, train_y, test_x, test_y = split_data(x, y)\n for d in degrees:\n model = pylab.polyfit(train_x, train_y, d)\n est_y_vals = pylab.polyval(model, test_x)\n r_squares[d].append(rSquared(test_y, est_y_vals))\n print('Mean R-squares for test data')\n for d in degrees:\n mean = round(sum(r_squares[d]) / len(r_squares[d]), 4)\n sd = round(np.std(r_squares[d]), 4)\n results.loc[d] = [mean, sd]\n return results\n"} {"blob_id": "776b058b87bd84bf11d38c3024893cf004e884f7", "repo_name": "SunnyRaj94/Machine-Learning-From-Scratch", "path": "/linear_algebra/05_inverse_of_matrix.py", "length_bytes": 3940, "score": 3.8125, "int_score": 4, "content": "\"\"\"\nCreated on 16/12/2019\n@author: Sunny Raj\n\"\"\"\n\"\"\"\nproblem statement:\nWrite a program to find inverse matrix of matrix X\n\"\"\"\n#method to setup the value of row and column for input matrices\ndef criteria_setup():\n while True:\n try:\n value=int(input())\n break\n except ValueError:\n print(\"try again with proper value\")\n return value\n# method/function to take input in matrix\ndef value_input(row,col):\n #initializing empty matrix\n matrix = []\n #looping through the given row value\n for index_x in range(row):\n #initializing a temperory variable\n temp=[]\n #looping through the given column value\n for index_y in range(col):\n while True:\n try:\n value = int(input(\"enter value for [{}],[{}]\".format(index_x,index_y)))\n break\n except ValueError:\n print(\"try again with proper integer value\")\n #adding values to one row\n temp.append(value)\n #Aadding list into a list\n matrix.append(temp)\n #returning the 2d list / matrix\n return matrix\n\n#function to print row wise matrix\ndef display_matrix(matrix):\n for mat in matrix:\n print(mat)\n\ndef getMatrixMinor(m,i,j):\n return [row[:j] + row[j+1:] for row in (m[:i]+m[i+1:])]\n\ndef getMatrixDeternminant(m):\n #base case for 2x2 matrix\n if len(m) == 2:\n return m[0][0]*m[1][1]-m[0][1]*m[1][0]\n #initializing determinantt\n determinant = 0\n #looping in range length of matrix\n for c in range(len(m)):\n determinant += ((-1)**c)*m[0][c]*getMatrixDeternminant(getMatrixMinor(m,0,c))\n return determinant\n#function to find transpose of matrix\ndef transposeMatrix(matrix):\n #returning transposed matrix\n return list(map(list,zip(*matrix)))\n#function to find inverse of matrix\ndef getMatrixInverse(m):\n #determinant of given matrix\n determinant = getMatrixDeternminant(m)\n #special case for 2x2 matrix:\n if len(m) == 2:\n return [[m[1][1]/determinant, -1*m[0][1]/determinant],\n [-1*m[1][0]/determinant, m[0][0]/determinant]]\n\n #find matrix of cofactors\n cofactors = []\n #finding co factors of each element wise\n for r in range(len(m)):\n #cofactors\n cofactorRow = []\n for c in range(len(m)):\n minor = getMatrixMinor(m,r,c)\n cofactorRow.append(((-1)**(r+c)) * getMatrixDeternminant(minor))\n cofactors.append(cofactorRow)\n cofactors = transposeMatrix(cofactors)\n for r in range(len(cofactors)):\n for c in range(len(cofactors)):\n cofactors[r][c] = cofactors[r][c]/determinant\n return cofactors\ndef divide(matrix_one,div_value,row,col):\n #initializing empty matrix\n matrix = []\n #looping through the row value\n for index_x in range(row):\n #initializing a temp variable\n temp = []\n #looping through the column value\n for index_y in range(col):\n #adding both values\n value = matrix_one[index_x][index_y]/div_value\n temp.append(value)\n matrix.append(temp)\n return matrix\n\n\ndef runner():\n while True:\n try:\n print(\"Enter row value for first matrix\")\n row = criteria_setup()\n print(\"Enter column value for first matrix\")\n col = criteria_setup()\n assert row==col\n break\n except AssertionError:\n print(\"row and column value must be equal to find inverse of a matrix\")\n print(\"your entered matrix is :\")\n #obtaining matrix by input\n my_matrix = value_input(row,col)\n #displaying matrix\n display_matrix(my_matrix)\n #finding inverse by calling inverse function\n inverse_matrix=getMatrixInverse(my_matrix)\n #printing the inverse matrix\n print(\"inverse of given matrix is : \")\n display_matrix(inverse_matrix)\n\nrunner()"} {"blob_id": "bec023c716aad7a3e6ce8ac8a1dff246cc280ad1", "repo_name": "jungleQi/leetcode-sections", "path": "/classification/algorithm/2-dynamic programming/1-knapsack model/9-1155. Number of Dice Rolls With Target Sum.py", "length_bytes": 578, "score": 3.734375, "int_score": 4, "content": "'''\nYou have d dice, and each die has f faces numbered 1, 2, ..., f.\n\nReturn the number of possible ways (out of f^d total ways) modulo 10^9 + 7 to roll the dice\nso the sum of the face up numbers equals target.\n'''\n\ndef numRollsToTarget(d, f, target):\n dp = [[0]*(target+1) for _ in range(d+1)]\n dp[0][0] = 1\n for i in range(1, d+1):\n for j in range(i,target+1):\n for m in range(1,f+1):\n if m<=j:\n dp[i][j] += dp[i-1][j-m]\n\n return dp[-1][-1]%(10**9+7)\nd = 2\nf = 6\ntarget = 7\nprint(numRollsToTarget(d, f, target))\n"} {"blob_id": "0c45e7b824d178aef48c3d89cca53f35f3be4e01", "repo_name": "hinesd/EncryptionAlogorithms", "path": "/playfairEncrypt.py", "length_bytes": 2758, "score": 3.828125, "int_score": 4, "content": "# -*- coding: utf-8 -*-\n\n#iostream\n\nimport sys\n\ndef Encrypt(key, file):\n #check for key and file\n if isinstance(key, str) and isinstance(file, str):\n #create array of words\n f = open(file)\n text = f.readlines()\n stringList = []\n newLine = []\n chopLine = []\n for x in text:\n stringList.append(x)\n print(stringList)\n for x in stringList:\n line = list(x)\n for y in line:\n if(y.isalpha()): \n newLine.append(y.upper())\n else:\n newLine.append(y)\n print(newLine)\n i = 0\n while i < (len(newLine)-1):\n if(newLine[i].isalpha() and newLine[i+1].isalpha()):\n if(newLine[i]=='J'):\n newLine[i]='I'\n if(newLine[i+1]=='J'):\n newLine[i+1]='I'\n if(newLine[i]==newLine[i+1]):\n chopLine.append(newLine[i] + 'X')\n i+=1\n else:\n chopLine.append(newLine[i] + newLine[i+1])\n i += 2\n elif(newLine[i].isalpha()):\n if(newLine[i]=='J'):\n newLine[i]='I'\n chopLine.append(newLine[i] + 'Z')\n chopLine.append(newLine[i+1])\n i += 2\n else:\n chopLine.append(newLine[i])\n i += 1\n print(chopLine)\n #create key\n keyTable = makeKey(key)\n print(keyTable)\n #create empty coded text string\n codedText = \"\" \n for j in chopLine:\n if(len(j) == 2):\n row1, col1 = divmod(keyTable.index(j[0]), 5)\n row2, col2 = divmod(keyTable.index(j[1]), 5)\n\n if row1 == row2:\n codedText += keyTable[row1*5+(col1+1)%5]\n codedText += keyTable[row2*5+(col2+1)%5]\n elif col1 == col2:\n codedText += keyTable[((row1+1)%5)*5+col1]\n codedText += keyTable[((row2+1)%5)*5+col2]\n else: # rectangle\n codedText += keyTable[row1*5+col2]\n codedText += keyTable[row2*5+col1]\n else:\n codedText+=j\n print(codedText)\n else:\n \tprint(\"give me a key and then the name of your file \")\n\ndef makeKey(key):\n keyTable = []\n alphabet = \"ABCDEFGHIKLMNOPQRSTUVWXYZ\"\n for char in key.upper():\n if char not in keyTable and char in alphabet:\n keyTable.append(char)\n for char in alphabet:\n if char not in keyTable:\n keyTable.append(char)\n return keyTable\n\nEncrypt(sys.argv[1],sys.argv[2])\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"} {"blob_id": "10ebb4297c3e1ae2cb4f992f48ffa436c0b60d53", "repo_name": "danyfang/SourceCode", "path": "/py/leetcode/SetIntersection.py", "length_bytes": 1074, "score": 3.640625, "int_score": 4, "content": "'''\nLeetcode problem No 757 Set Intersection Size At Least Two\nSolution written by Xuqiang Fang on 8 July, 2018\n'''\n\nclass Solution:\n def intersectionSizeTwo(self, intervals):\n \"\"\"\n :type intervals: List[List[int]]\n :rtype: int\n \"\"\"\n intervals.sort(key = lambda x : x[1])\n #print(intervals)\n ans = [intervals[0][-1]-1, intervals[0][-1]]\n for it in intervals:\n left = ans[-2]\n right = ans[-1]\n if right < it[0]:\n ans.append(it[-1]-1)\n ans.append(it[-1])\n elif left < it[0]:\n if right == it[-1]:\n ans.pop()\n ans.append(right-1)\n ans.append(right)\n else:\n ans.append(it[-1])\n #print(ans)\n return len(ans)\n\ndef main():\n s = Solution()\n intervals = [[1, 2], [2, 3], [2, 4], [4, 5]]\n print(s.intersectionSizeTwo(intervals))\n intervals = [[2, 5], [3, 5], [1, 3], [1, 4]]\n print(s.intersectionSizeTwo(intervals))\nmain()\n"} {"blob_id": "8e10fb09fbada488afad7a8c07c300814a74c05a", "repo_name": "bssrdf/pyleet", "path": "/R/RectangleAreaII.py", "length_bytes": 6136, "score": 3.640625, "int_score": 4, "content": "'''\nhttps://leetcode.com/problems/rectangle-area-ii/\n\nWe are given a list of (axis-aligned) rectangles. Each rectangle[i] =\n[x1, y1, x2, y2] , where (x1, y1) are the coordinates of the bottom-left \n corner, and (x2, y2) are the coordinates of the top-right corner of the \n ith rectangle.\n\nFind the total area covered by all rectangles in the plane. Since the answer \nmay be too large, return it modulo 10^9 + 7.\n\nExample 1:\n\nInput: [[0,0,2,2],[1,0,2,3],[1,0,3,1]]\nOutput: 6\nExplanation: As illustrated in the picture.\nExample 2:\n\nInput: [[0,0,1000000000,1000000000]]\nOutput: 49\nExplanation: The answer is 10^18 modulo (10^9 + 7), which is (10^9)^2 = (-7)^2 = 49.\nNote:\n\n1 <= rectangles.length <= 200\nrectanges[i].length = 4\n0 <= rectangles[i][j] <= 10^9\nThe total area covered by all rectangles will never exceed 2^63 - 1 and thus \nwill fit in a 64-bit signed integer.\n\n'''\n\nimport heapq\n\nclass Node(object):\n def __init__(self, start, end):\n self.start, self.end = start, end\n self.total = self.count = 0\n self._left = self._right = None\n\n @property\n def mid(self):\n return (self.start + self.end) // 2\n\n @property\n def left(self):\n self._left = self._left or Node(self.start, self.mid)\n return self._left\n\n @property\n def right(self):\n self._right = self._right or Node(self.mid, self.end)\n return self._right\n\n def print_count(self):\n print('start, end, count, total : ',\n self.start, self.end, self.count, self.total)\n if self._left:\n self._left.print_count()\n if self._right:\n self._right.print_count() \n\n ''' \n\n The data array for segmentation tree is made up of all the x-coordinates \n encountered in sweep line algorithm.\n\n The segmentation tree leaves in this problem take the form of [i, i+1] \n rather than [i, i].\n\n ST leave of range [i, i+1] contains value of X[i+1] - X[i], if the count \n of this range is larger than 0.\n \n Adding and removing edges is done by updating ranges, specifically the \n count attributes. Note that count field is updated only for leave nodes. \n For nonleave nodes, we only update total field.\n\n '''\n def update(self, i, j, val):\n if i >= j: return 0\n if self.start == i and self.end == j: \n self.count += val\n else:\n self.left.update(i, min(self.mid, j), val)\n self.right.update(max(self.mid, i), j, val)\n\n if self.count > 0: \n self.total = X[self.end] - X[self.start]\n else: \n self.total = self.left.total + self.right.total\n\n return self.total\n\nclass Solution(object):\n def rectangleAreaSegTree(self, rectangles):\n \"\"\"\n :type rectangles: List[List[int]]\n :rtype: int\n \"\"\"\n OPEN, CLOSE = 1, -1\n events = []\n global X\n X = set()\n for x1, y1, x2, y2 in rectangles:\n events.append((y1, OPEN, x1, x2))\n events.append((y2, CLOSE, x1, x2))\n X.add(x1)\n X.add(x2)\n events.sort()\n\n X = sorted(X)\n Xi = {x: i for i, x in enumerate(X)}\n\n active = Node(0, len(X) - 1)\n ans = 0\n cur_x_sum = 0\n cur_y = events[0][0]\n\n for y, typ, x1, x2 in events:\n ans += cur_x_sum * (y - cur_y) \n cur_x_sum = active.update(Xi[x1], Xi[x2], typ)\n print(y, typ, cur_y, ans, cur_x_sum)\n active.print_count()\n cur_y = y\n\n return ans % (10**9 + 7)\n\n def rectangleAreaDivideandConquer(self, rectangles):\n \"\"\"\n :type rectangles: List[List[int]]\n :rtype: int\n \"\"\"\n def getSum(batch):\n batch.sort(key=lambda x: x[1])\n temp = [] \n temp.append(batch[0])\n i = 1\n while i < len(batch):\n cur = batch[i]\n end = temp[-1]\n if cur[1] <= end[3]:\n end[3] = max(end[3], cur[3])\n else:\n temp.append(cur)\n i += 1\n sm = 0\n for t in temp:\n sm += t[3] - t[1]\n return sm\n \n def verticalCut(batch, queue):\n mi = batch[0][2] if not queue else queue[0][0]\n\n for rec in batch:\n mi = min(mi, rec[2])\n \n for rec in batch:\n if rec[2] > mi:\n right = [mi, rec[1], rec[2], rec[3]]\n rec[2] = mi\n heapq.heappush(queue, right)\n\n queue = rectangles\n heapq.heapify(queue)\n \n total = 0\n while queue:\n batch = [] \n cur = heapq.heappop(queue)\n batch.append(cur)\n while queue and queue[0][0] == cur[0]:\n batch.append(heapq.heappop(queue))\n \n verticalCut(batch, queue)\n total += getSum(batch) * (batch[0][2] - batch[0][0])\n \n return total % (1000000000 + 7)\n\n def rectangleArea(self, rectangles):\n \"\"\"\n :type rectangles: List[List[int]]\n :rtype: int\n \"\"\" \n xs = sorted(set([x for x1, y1, x2, y2 in rectangles for x in [x1, x2]]))\n x_i = {v: i for i, v in enumerate(xs)}\n count = [0] * len(x_i)\n L = []\n for x1, y1, x2, y2 in rectangles:\n L.append([y1, x1, x2, 1])\n L.append([y2, x1, x2, -1])\n L.sort()\n cur_y = cur_x_sum = area = 0\n for y, x1, x2, sig in L:\n area += (y - cur_y) * cur_x_sum\n cur_y = y\n for i in range(x_i[x1], x_i[x2]):\n count[i] += sig\n cur_x_sum = sum(x2 - x1 if c else 0 for x1, x2, c in zip(xs, xs[1:], count))\n return area % (10 ** 9 + 7)\n\nif __name__ == \"__main__\": \n print(Solution().rectangleArea([[0,0,2,2],[1,0,2,3],[1,0,3,1]]))\n print(Solution().rectangleAreaSegTree([[0,0,2,2],[1,0,2,3],[1,0,3,1]]))\n print(Solution().rectangleAreaDivideandConquer([[0,0,2,2],[1,0,2,3],[1,0,3,1]]))"} {"blob_id": "5c2609c5507007c0429e052d331c54bc47a6e519", "repo_name": "saetar/pyEuler", "path": "/not_done/euler_086.py", "length_bytes": 2101, "score": 3.828125, "int_score": 4, "content": "# -*- coding: utf-8 -*-\n# ~ Jesse Rubin ~ project Euler ~\n\"\"\"\nCuboid route\nhttp://projecteuler.net/problem=86\nA spider, S, sits in one corner of a cuboid room, measuring 6 by 5 by 3, and a\nfly, F, sits in the opposite corner. By travelling on the surfaces of the room\nthe shortest \"straight line\" distance from S to F is 10 and the path is shown\non the diagram.\n\nHowever, there are up to three \"shortest\" path candidates for any given cuboid\nand the shortest route doesn't always have integer length. It can be shown that\nthere are exactly 2060 distinct cuboids, ignoring rotations, with integer\ndimensions, up to a maximum size of M by M by M, for which the shortest route\nhas integer length when M = 100. This is the least value of M for which the\nnumber of solutions first exceeds two thousand; the number of solutions\nwhen M = 99 is 1975. Find the least value of M such that the number of\nsolutions first exceeds one million.\n\"\"\"\nfrom __future__ import division\nfrom bib.maths import pytriple_gen, Vuple\nfrom math import sqrt\nfrom itertools import count\n\ndef cuboid_routes(m):\n total = 0\n maxhp = sqrt(1+(5*(m**2)))\n for p in pytriple_gen(maxhp):\n trip = Vuple(p)\n while trip[0]<=m:\n cubs = set()\n for i in range(1, trip[0]):\n c = tuple(sorted([i, trip[0]-i, trip[1]]))\n if max(c)<=m:\n cubs.add(c)\n if trip[1]-trip[0]<=trip[0]:\n for i in range(trip[1]-trip[0], (trip[1]//2)+2):\n cubs.add(tuple(sorted([trip[0], trip[1]-i, i])))\n total += len(cubs)\n trip += Vuple(p)\n return total\n\n\nassert 1975 == cuboid_routes(99)\nassert 2060 == cuboid_routes(100)\n\n# a = cuboid_routes(1816)\n# print(a)\n# a = cuboid_routes(1817)\n# print(a)\n# # a = cuboid_routes(1818) #ANSWER\n# print(a)\n# a = cuboid_routes(1819)\n# print(a)\n# a = cuboid_routes(1820)\n# print(a)\n# # for mm in count(100):\n# # ans = (cuboid_routes(mm))\n# # print(ans, mm)\n# # if ans > 1000000:\n# # break\n#\n#\n\ndef p086():\n pass\n\n\nif __name__ == '__main__':\n p086()\n"} {"blob_id": "0743849f184d5055155ee69ce3c1a52ebb1b4098", "repo_name": "bssrdf/pyleet", "path": "/Q/QueriesonaPermutationWithKey.py", "length_bytes": 2517, "score": 3.59375, "int_score": 4, "content": "'''\n-Medium-\n\nGiven the array queries of positive integers between 1 and m, you have to process all queries[i] \n(from i=0 to i=queries.length-1) according to the following rules:\n\nIn the beginning, you have the permutation P=[1,2,3,...,m].\n\nFor the current i, find the position of queries[i] in the permutation P (indexing from 0) and then \nmove this at the beginning of the permutation P. Notice that the position of queries[i] in P is \nthe result for queries[i].\n\nReturn an array containing the result for the given queries.\n\n \n\nExample 1:\n\nInput: queries = [3,1,2,1], m = 5\nOutput: [2,1,2,1] \nExplanation: The queries are processed as follow: \nFor i=0: queries[i]=3, P=[1,2,3,4,5], position of 3 in P is 2, then we move 3 to the beginning of P resulting in P=[3,1,2,4,5]. \nFor i=1: queries[i]=1, P=[3,1,2,4,5], position of 1 in P is 1, then we move 1 to the beginning of P resulting in P=[1,3,2,4,5]. \nFor i=2: queries[i]=2, P=[1,3,2,4,5], position of 2 in P is 2, then we move 2 to the beginning of P resulting in P=[2,1,3,4,5]. \nFor i=3: queries[i]=1, P=[2,1,3,4,5], position of 1 in P is 1, then we move 1 to the beginning of P resulting in P=[1,2,3,4,5]. \nTherefore, the array containing the result is [2,1,2,1]. \nExample 2:\n\nInput: queries = [4,1,2,2], m = 4\nOutput: [3,1,2,0]\nExample 3:\n\nInput: queries = [7,5,5,8,3], m = 8\nOutput: [6,5,0,7,5]\n \n\nConstraints:\n\n1 <= m <= 10^3\n1 <= queries.length <= m\n1 <= queries[i] <= m\n\n'''\n\n\nclass Fenwick:\n def __init__(self, n):\n sz = 1\n while sz <= n:\n sz *= 2\n self.size = sz\n self.data = [0] * sz\n\n def sum(self, i):\n s = 0\n while i > 0:\n s += self.data[i]\n i -= i & -i\n return s\n\n def add(self, i, x):\n while i < self.size:\n self.data[i] += x\n i += i & -i\n\nclass Solution(object):\n def processQueries(self, queries, n):\n \"\"\"\n :type queries: List[int]\n :type m: int\n :rtype: List[int]\n \"\"\"\n fenw = Fenwick(2 * n)\n vimap = {}\n for i in range(1, n + 1):\n fenw.add(i + n, 1)\n vimap[i] = i + n\n cur = n\n \n ans = []\n for q in queries:\n i = vimap.pop(q)\n rank = fenw.sum(i-1)\n ans.append(rank)\n \n vimap[q] = cur\n fenw.add(i, -1)\n fenw.add(cur, 1)\n cur -= 1\n return ans\n\nif __name__ == \"__main__\":\n print(Solution().processQueries([3,1,2,1], 5))"} {"blob_id": "9297af31c61e520ba2d737c1d3ad6724f532fe43", "repo_name": "Programmer-Admin/binarysearch-editorials", "path": "/Square One.py", "length_bytes": 792, "score": 3.6875, "int_score": 4, "content": "\"\"\"\nSquare One\n\nSimilar idea to the Largest square medium problem, with the additional constraint that all values are equal. \n\nWe create the additionnal dp matrix that stores the largest square with bottom-right corner at [i][j]. Then we iterate over the matrix: if a value is equal to its top, top-left and left values, then we can make a larger square with the smallest of its neighboring values.\n\"\"\"\nclass Solution:\n def solve(self, matrix):\n dp =[[1]* len(matrix[0]) for _ in matrix]\n for i in range(1,len(matrix)):\n for j in range(1,len(matrix[0])):\n if matrix[i][j] == matrix[i-1][j-1] == matrix[i][j-1] == matrix[i-1][j]:\n dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1])+1\n return max(v for r in dp for v in r)\n"} {"blob_id": "a4f5432dffe8162dc92ca355d8636b92798c99f8", "repo_name": "lynkeib/LeetCode", "path": "/ByTags/Two Pointers/457. Circular Array Loop.py", "length_bytes": 2110, "score": 3.578125, "int_score": 4, "content": "class Solution(object):\n def circularArrayLoop(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n for i in range(len(nums)):\n if nums[i] == 0:\n continue\n\n slow, fast = i, self.getIndex(i, nums)\n while nums[slow] * nums[fast] > 0 and nums[slow] * nums[self.getIndex(fast, nums)] > 0:\n if slow == fast:\n if fast == self.getIndex(fast, nums):\n break\n return True\n slow = self.getIndex(slow, nums)\n fast = self.getIndex(self.getIndex(fast, nums), nums)\n slow = i\n thisVal = nums[slow]\n while nums[slow] * thisVal > 0:\n nextSlow = self.getIndex(slow, nums)\n nums[slow] = 0\n slow = nextSlow\n return False\n\n def getIndex(self, index, nums):\n return (index + nums[index]) % len(nums)\n\n\n\ndef circular_array_loop_exists(arr):\n for i in range(len(arr)):\n is_forward = arr[i] >= 0 # if we are moving forward or not\n slow, fast = i, i\n\n # if slow or fast becomes '-1' this means we can't find cycle for this number\n while True:\n # move one step for slow pointer\n slow = find_next_index(arr, is_forward, slow)\n # move one step for fast pointer\n fast = find_next_index(arr, is_forward, fast)\n if (fast != -1):\n # move another step for fast pointer\n fast = find_next_index(arr, is_forward, fast)\n if slow == -1 or fast == -1 or slow == fast:\n break\n\n if slow != -1 and slow == fast:\n return True\n\n return False\n\n\ndef find_next_index(arr, is_forward, current_index):\n direction = arr[current_index] >= 0\n\n if is_forward != direction:\n return -1 # change in direction, return -1\n\n next_index = (current_index + arr[current_index]) % len(arr)\n\n # one element cycle, return -1\n if next_index == current_index:\n next_index = -1\n\n return\n"} {"blob_id": "98f63a81f83c8003fba2da4c2b791794ad8c08e3", "repo_name": "valenvivaldi/aima-python", "path": "/searchJARPROBLEM.py", "length_bytes": 5231, "score": 3.5625, "int_score": 4, "content": "from search import *\n\n\nclass Jarra(Problem):\n\n def __init__(self, initial):\n\n Problem.__init__(self, initial)\n\n def actions(self, state):\n result = []\n if (state[0] < 4):\n result.append(\"LlenarPrimera\")\n if (state[1] < 3):\n result.append(\"LlenarSegunda\")\n if (state[0] != 0):\n result.append(\"vaciarPrimera\")\n if (state[1] < 3):\n result.append(\"VolcarPrimeraEnSegunda\")\n if (state[1] != 0):\n result.append(\"vaciarSegunda\")\n if (state[0] < 4):\n result.append(\"VolcarSegundaEnPrimera\")\n return result\n\n def result(self, state, action):\n newa = state[0]\n newb = state[1]\n if (action == \"LlenarPrimera\"):\n newa = 4\n elif (action == \"LlenarSegunda\"):\n newb = 3\n elif (action == \"vaciarPrimera\"):\n newa = 0\n elif (action == \"vaciarSegunda\"):\n newb = 0\n elif (action == \"VolcarPrimeraEnSegunda\"):\n\n t = min(3 - newb, newa)\n newb += t\n newa -= t\n\n elif (action == \"VolcarSegundaEnPrimera\"):\n t = min(4 - newa, newb)\n newa += t\n newb -= t\n print(\"recibimos las jarras asi {} y la accion {} , las devolvemos asi {}\".format(state, action, (newa, newb)))\n\n return (newa, newb)\n\n def goal_test(self, state):\n return state[0] == 2\n\n\nif __name__ == \"__main__\":\n # print(\"Jarra\")\n # jarraproblem = Jarra((0, 0))\n # #result = breadth_first_tree_search(jarraproblem)\n # #result = depth_limited_search(jarraproblem,6)\n # result = depth_limited_search(jarraproblem,200)\n # print(result.solution())\n # print(\"finish\")\n\n romania_map = UndirectedGraph(dict(\n Arad=dict(Zerind=75, Sibiu=140, Timisoara=118),\n Bucharest=dict(Urziceni=85, Pitesti=101, Giurgiu=90, Fagaras=211),\n Craiova=dict(Drobeta=120, Rimnicu=146, Pitesti=138),\n Drobeta=dict(Mehadia=75),\n Eforie=dict(Hirsova=86),\n Fagaras=dict(Sibiu=99),\n Hirsova=dict(Urziceni=98),\n Iasi=dict(Vaslui=92, Neamt=87),\n Lugoj=dict(Timisoara=111, Mehadia=70),\n Oradea=dict(Zerind=71, Sibiu=151),\n Pitesti=dict(Rimnicu=97),\n Rimnicu=dict(Sibiu=80),\n Urziceni=dict(Vaslui=142)))\n\n initialcity = 'Arad'\n finalcity = 'Bucharest'\n romania_problem = GraphProblem(initialcity, finalcity, romania_map)\n\n\n# print(\"El camino de {} a {} con depth first tree search es \".format(initialcity, finalcity))\n# result = breadth_first_graph_search(romania_problem)\n\n# print(result.solution())\n# print(\"El camino de {} a {} con depth first tree search es \".format(initialcity, finalcity))\n# result = uniform_cost_search(romania_problem)\n\n# print(result.solution())\n\nclass canibalesProblem(InstrumentedProblem):\n # state = (CanivalesLadoA,MisionerosLadoA,CanivaleLadoB,MisionerosLadoB)\n def __init__(self, initial):\n\n Problem.__init__(self, initial)\n def result(self, state, action):\n newa = state[0]\n newb = state[1]\n newc = state[2]\n newd = state[3]\n if action == \"unoYunoA-B\":\n newa += -1\n newb += -1\n newc += 1\n newd += 1\n if action == \"unoYunoB-A\":\n newa += 1\n newb += 1\n newc += -1\n newd += -1\n if action == \"2canibalesA-B\":\n newa += -2\n newc += 2\n if action == \"2misionerosA-B\":\n newb += -2\n newd += 2\n\n if action == \"2canibalesB-A\":\n newa += 2\n newc += -2\n\n if action == \"2misionerosB-a\":\n newb += 2\n newd += -2\n return(newa,newb,newc,newd)\n\n def invariant(self, state):\n if (state[0] > state[1] or state[2] > state[3]):\n return False\n return True\n\n def actions(self, state):\n possibleactions = []\n if (state[0] > 0 and state[1] > 0 and self.invariant(self.result(state,\"unoYunoA-B\"))):\n possibleactions.append(\"unoYunoA-B\")\n\n if (state[0] > 1 and self.invariant(self.result(state,\"2canibalesA-B\"))):\n possibleactions.append(\"2canibalesA-B\")\n\n if (state[1] > 1 and self.invariant(self.result(state,\"2misionerosA-B\"))):\n possibleactions.append(\"2misionerosA-B\")\n\n if (state[2] > 0 and state[3] > 0 and self.invariant(self.result(state,\"unoYunoB-A\"))):\n possibleactions.append(\"unoYunoB-A\")\n if (state[2] > 1 and self.invariant(self.result(state,\"2canibalesB-A\"))):\n possibleactions.append(\"2canibalesB-A\")\n if (state[3] > 1 and self.invariant(self.result(state,\"2misionerosB-A\"))):\n possibleactions.append(\"2misionerosB-A\")\n print(\"las posibles acciones para {} son: {}\".format(state,possibleactions))\n return possibleactions\n\n\n\n def goal_test(self, state):\n if state[2] == 3 and state[3] == 3:\n return True\n return False\n\n\ncanibal = canibalesProblem((3, 3, 0,0))\nresult=breadth_first_tree_search(canibal)\nprint(result.solution())\n#compare_searchers([canibal], \"problema de los canibales\")\n"} {"blob_id": "98210f8e02438d8040903dd525f17151aa8dbaf9", "repo_name": "simrit1/Sorting_Algorithm_Visualisation", "path": "/Graphing.py", "length_bytes": 3082, "score": 3.578125, "int_score": 4, "content": "import time\nfrom matplotlib import pyplot as plt\nfrom Start_Array import random_numbers, worst_case, worst_case_alt\nfrom Sorting_Algorithms import bubble_sort,merge_sort,insertion_sort,shell_sort\n\n\nn = list(range(10,1000,10)) #Running sorting algorithms for a range of array lengths and showing a graph of the times taken against array size\n\ntimes_bubble = []\ntimes_bubble_worst_case = []\ntimes_merge = []\ntimes_merge_worst_case = []\ntimes_insertion = []\ntimes_insertion_worst_case = []\ntimes_shell = []\ntimes_shell_worst_case = []\n\nfor x in range(len(n)): #Working out times taken\n start_bubble_random = time.time() #Bubble sort on random array\n bubble_sort(random_numbers(n[x]))\n time_bubble_random = time.time() - start_bubble_random\n\n start_bubble_worst_case = time.time() #Bubble sort on worst case array\n bubble_sort(worst_case(n[x]))\n time_bubble_worst_case = time.time() - start_bubble_worst_case\n\n start_merge_random = time.time() #Merge sort on random array\n merge_sort(random_numbers(n[x]))\n time_merge_random = time.time() - start_merge_random\n\n start_merge_worst_case = time.time() #Merge sort on worst case array\n merge_sort(worst_case_alt(n[x]))\n time_merge_worst_case = time.time() - start_merge_worst_case\n\n start_insertion_random = time.time() #Insertion sort on random array\n insertion_sort(random_numbers(n[x]))\n time_insertion_random = time.time() - start_insertion_random\n\n start_insertion_worst_case = time.time() #Insertion sort on worst case array\n insertion_sort(worst_case(n[x]))\n time_insertion_worst_case = time.time() - start_insertion_worst_case\n\n start_shell_random = time.time() #Shell sort on random array\n shell_sort(random_numbers(n[x]))\n time_shell_random = time.time() - start_shell_random\n\n start_shell_worst_case = time.time() #Shell sort on worst case array\n shell_sort(worst_case(n[x]))\n time_shell_worst_case = time.time() - start_shell_worst_case\n\n\n times_bubble.append(time_bubble_random) #Appending times to relevent lists\n times_bubble_worst_case.append(time_bubble_worst_case)\n times_merge.append(time_merge_random)\n times_merge_worst_case.append(time_merge_worst_case)\n times_insertion.append(time_insertion_random)\n times_insertion_worst_case.append(time_insertion_worst_case)\n times_shell.append(time_shell_random)\n times_shell_worst_case.append(time_shell_worst_case)\n\n\nplt.plot(n,times_bubble,label='Bubble Sort Random Run')\nplt.plot(n,times_bubble_worst_case,label='Bubble Sort Worst Case')\nplt.plot(n,times_merge,label='Merge Sort Random Run')\nplt.plot(n,times_merge_worst_case,label='Merge Sort Worst Case')\nplt.plot(n,times_insertion,label='Insertion Sort Random Run')\nplt.plot(n,times_insertion_worst_case,label='Insertion Sort Worst Case')\nplt.plot(n,times_shell,label='Shell Sort Random Run')\nplt.plot(n,times_shell_worst_case,label='Shell Sort Worst Case')\n\nplt.xlabel('Array Length')\nplt.ylabel('Time Taken /s')\nplt.title('Bubble Sort')\nplt.legend()\nplt.show()\n"} {"blob_id": "d44d3a36dbe79c1e5e3b972fb71911e623e2204b", "repo_name": "zkutasi/adventofcode-2018", "path": "/day05/1.py", "length_bytes": 1697, "score": 3.71875, "int_score": 4, "content": "#!/usr/bin/env python\n\nimport sys\n\ndef progress(s):\n sys.stdout.write(\"%s\\r\" % s)\n sys.stdout.flush()\n\ndef reacts(u1, u2):\n if u1 != u2 and u1.lower() == u2.lower():\n return True\n return False\n\nfirst = None\nsize = 0\nclass Elem(object):\n def __init__(self, unit, prev, next):\n self.unit = unit\n self.prev = prev\n if prev is not None:\n prev.next = self\n self.next = next\n if next is not None:\n next.prev = self\n\nwith open(sys.argv[1]) as f:\n for line in f.readlines():\n prev = None\n for c in line.strip():\n e = Elem(c, prev, None)\n prev = e\n size += 1\n if first is None:\n first = e\n #print \"Test the traversal\"\n #curr = first\n #size_test = 0\n #while curr.next is not None:\n # size_test += 1\n # print \"%s - %d\" % (curr.unit, size_test)\n # curr = curr.next\n print \"The size of the polymer is %d\" % size\n shrunk = True\n while shrunk:\n shrunk = False\n curr = first\n while curr.next is not None:\n if reacts(curr.unit, curr.next.unit):\n if curr.prev is None:\n #print \"We are at the front...\"\n curr = curr.next.next\n first = curr\n curr.prev = None\n elif curr.next.next is None:\n #print \"We are almost at the very end\"\n curr.prev.next = None\n curr = prev\n else:\n #print \"We are somewhere in the middle\"\n curr.prev.next = curr.next.next\n curr.next.next.prev = curr.prev\n curr = curr.next.next\n shrunk = True\n size -= 2\n progress(\"Size is %d...\" % size)\n else:\n curr = curr.next\n #print \"Step one ahead... %s\" % curr.unit\n\nprint \"Final size is %d\" % size\n"} {"blob_id": "76ba8ef80ed5bdb6c5e511beadb9001b1e661057", "repo_name": "risk1996/project-euler", "path": "/001 - 050/014 - Longest Collatz sequence.py", "length_bytes": 965, "score": 4.125, "int_score": 4, "content": "\"\"\"\nSolution to\nLongest Collatz sequence\nProblem 14\n\nThe following iterative sequence is defined for the set of positive integers:\nn \u2192 n/2 (n is even)\nn \u2192 3n + 1 (n is odd)\nUsing the rule above and starting with 13, we generate the following sequence:\n13 \u2192 40 \u2192 20 \u2192 10 \u2192 5 \u2192 16 \u2192 8 \u2192 4 \u2192 2 \u2192 1\nIt can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.\nWhich starting number, under one million, produces the longest chain?\nNOTE: Once the chain starts the terms are allowed to go above one million.\n\"\"\"\n\n\ndef collatz(n):\n num = n\n for i in range(1, 1_000_000):\n if num == 1:\n return i\n elif num % 2 == 0:\n num /= 2\n else:\n num = 3 * num + 1\n\n\nchain_lengths = [(collatz(x), x) for x in range(1, 1_000_000)]\nsol = max(chain_lengths)[1]\nprint(sol)\n"} {"blob_id": "66ae29ff4d9a1a98fa50ab7d16caf95cbf598371", "repo_name": "illuca/pat", "path": "/1020 Tree Traversals.py", "length_bytes": 680, "score": 3.578125, "int_score": 4, "content": "# \u5df2\u77e5\u4e2d\u5e8f\u548c\u5148\u5e8f, \u6c42\u5c42\u6b21\nclass Node:\n def __init__(self, data=None, level=None):\n self.level = level\n self.data = data\n\n\ndef dfs(root, start, end, level):\n global res\n if start > end:\n return\n i = start\n while i < end and inLst[i] != postLst[root]:\n i += 1\n res.append(Node(postLst[root], level))\n dfs(root-1-end+i, start, i-1, level+1)\n dfs(root-1, i+1, end, level+1)\n\n\nn = int(input())\n\npostLst = list(map(int, input().split()))\ninLst = list(map(int, input().split()))\n\nres = []\nlength = len(inLst)\ndfs(-1, 0, length-1, 0)\nres.sort(key=lambda x: x.level)\nprint(' '.join(list(map(str, [node.data for node in res]))))\n"} {"blob_id": "8a76971c48c57c308b1e6ac03c3886d4ca4c9283", "repo_name": "bencrabbe/parsing_as_LM", "path": "/rnng/discotree.py", "length_bytes": 14985, "score": 3.703125, "int_score": 4, "content": "import sys\nimport os\nimport os.path\n\nclass DiscoTree:\n \"\"\"\n That's a discontinuous phrase structure tree.\n With label, range (as a list of integers) and children.\n The I/O formats are compatible with van-cranenburgh's disco-dop.\n \"\"\"\n def __init__(self,label,children = None ,child_index= -1):\n \"\"\"\n A constructor to be used in a bottom-up fashion.\n Args :\n label (str): the node label\n children: (list): a list of DiscoTree nodes.\n child_index (int): the position of the child in the string\n \"\"\"\n self.label = label\n if children :\n assert(child_index == -1)\n \n self.children = children\n self.range = [ ]\n for child in self.children:\n self.range.extend(child.range)\n self.range.sort()\n self.order_left_corner(recursive=False)\n else:\n assert(child_index >= 0 and children is None)\n self.range = [child_index]\n self.children = [ ]\n \n def is_leaf(self):\n \"\"\"\n Returns :\n Bool. True if this node is a leaf, false otherwise\n \"\"\"\n return self.children == []\n \n def is_pos(self):\n \"\"\"\n Returns :\n Bool. True if this node is a pos tag, false otherwise\n \"\"\"\n return self.arity() == 1 and self.children[0].is_leaf()\n \n def arity(self):\n return len(self.children)\n \n def __eq__(self,other):\n \"\"\"\n Args:\n other (DiscoTree): the node with which to compare\n Returns:\n Bool. True if the two nodes share the same label and have the same range \n \"\"\"\n return self.label == other.label and self.range == other.range\n\n def __neq__(self,other):\n return not self.__eq__(other)\n\n def has_same_range(self,other_range):\n \"\"\"\n Says if a node has equal range to some range\n Args:\n other_range (list): a list, iterable of integers\n Returns:\n True if both ranges are equal, false otherwise\n \"\"\"\n return set(other_range) == set(self.range)\n\n def is_dominated_by(self,other_range):\n return set(self.range) <= set(other_range)\n \n def dominates(self,other_range,reflexive=True): \n \"\"\" \n Says if a range is dominated by this node or not.\n Args: \n other_range (list or set): a set of integers \n Returns:\n bool. True if the range is fully dominated by this node as determined by a set inclusion test\n \"\"\"\n return set(other_range) <= set(self.range) if reflexive else set(other_range) < set(self.range)\n \n def get_lc_ancestors(self,other_range,min_range =-1):\n \"\"\"\n Returns all the nodes in the tree whose range starts with the same\n left corner and that dominate this range. \n\n Args:\n other_range (iterable) : a list or a set of integers\n Returns:\n A list of DiscoTree nodes \n \"\"\"\n res = [ ]\n\n if min_range == -1:\n min_range = min(other_range) \n \n if self.left_corner() == min_range and self.dominates(other_range,reflexive=False): \n res = [ self ]\n \n for child in self.children:\n res.extend(child.get_lc_ancestors(other_range,min_range))\n \n return res\n \n def gap_degree(self):\n \"\"\"\n This computes the gap degree of this tree.\n Returns:\n (int) the gap degree of the subtree dominated by this node.\n \"\"\" \n if self.is_leaf():\n return 0\n \n local_gd = sum([jdx != idx+1 for idx,jdx in zip(self.range,self.range[1:])])\n return max(local_gd,max([child.gap_degree() for child in self.children]))\n \n def gap_list(self):\n \"\"\"\n This returns the list of gaps in the yield of this node.\n Returns:\n A list of couples (i,j) interpreted as a list of gaps\n \"\"\"\n return [(idx,jdx) for idx,jdx in zip(self.range,self.range[1:]) if jdx != idx+1 ]\n\n def left_corner(self):\n \"\"\"\n returns the left corner of this node\n \"\"\"\n return self.range[0]\n\n def right_corner(self):\n \"\"\"\n returns the right corner of this node\n \"\"\"\n return self.range[-1]\n \n def cover(self):\n \"\"\"\n Returns:\n a couple of int (i,j). This is the cover of the node (min(range),max(range)) \n \"\"\"\n return (self.left_corner(),self.right_corner())\n\n def order_left_corner(self,recursive=True):\n \"\"\"\n Convenience in-place method that provides an arbitrary order to the nodes.\n The nodes are ordered according to a left corner convention.\n A child whose left corner < the left corner of another child precedes the other child.\n \n KwArgs:\n recursive (bool): if true, applies the method recursively\n \"\"\"\n self.children.sort(key = lambda child: child.left_corner())\n if recursive:\n for child in self.children:\n child.order_left_corner(recursive)\n\n def covered_nodes(self,root):\n \"\"\"\n Gets the nodes covered by this node using a left corner\n ordering. \n Args:\n root (DiscoTree) : the overall global root of this DiscoTree.\n Returns:\n the list of nodes covered by this node sorted according to the left corner convention.\n \"\"\" \n MN = []\n for i,j in self.gap_list():\n MN.extend(root.max_nodes(i,j))\n cov_nodes = MN + self.children\n cov_nodes.sort(key = lambda c: c.left_corner())\n return cov_nodes\n \n def max_nodes(self,i,j):\n \"\"\"\n Finds the set of maximal nodes covering a gap(i,j)\n Args: \n i,j (int). The gap interval\n Returns:\n a list of DiscoTree. The list of maximal nodes filling this gap.\n \"\"\"\n res = []\n ri,rj = self.cover()\n if (ri <= i and rj > i) or ( ri < j and rj >= j ): \n for child in self.children:\n ci,cj = child.cover()\n if ci > i and cj < j:\n #print('MAX',child.label)\n res.append(child)\n #recursive additions\n for child in self.children:\n res.extend(child.max_nodes(i,j))\n return res\n\n #TRAVERSALS \n def tokens(self,global_root=None,max_index=-1):\n \"\"\"\n KwArgs:\n global_root (DiscoTree) : the global root of the tree. No need to care in most cases\n max_index (int) : the index up to which the input is covered so far. No need to care in most cases\n Returns:\n a list. A list of DiscoTree objects, the leaves of the tree\n \"\"\"\n if global_root is None:\n global_root = self\n \n if self.is_leaf():\n return [ self ]\n\n result = []\n for node in self.covered_nodes(global_root):\n if node.right_corner() > max_index:\n result.extend( node.tokens(global_root,max_index) )\n max_index = max(max_index,node.right_corner()) \n return result\n\n def pos_nodes(self,global_root=None,max_index=-1):\n \"\"\"\n Gets the part of speech nodes of this tree.\n Assumes that every token is dominated by a single part of\n speech.\n\n Args:\n global_root (DiscoTree) : the global root of the tree. No need to care in most cases\n max_index (int) : the index up to which the input is covered so far. No need to care in most cases\n \"\"\"\n if global_root is None:\n global_root = self\n \n if self.is_pos():\n return [ self ]\n\n result = [ ] \n for node in self.covered_nodes(global_root):\n if node.right_corner() > max_index:\n result.extend( node.pos_nodes(global_root,max_index) )\n max_index = max(max_index,node.right_corner()) \n return result\n\n def add_gold_tags(self,taglist):\n\n \"\"\"\n Inserts back the gold part of speech nodes of this tree.\n\n Args:\n taglist (list) : list of DiscoTree nodes\n global_root (DiscoTree) : the global root of the tree. No need to care in most cases\n max_index (int) : the index up to which the input is covered so far. No need to care in most cases\n \"\"\"\n new_children = [] \n for child in self.children:\n if child.is_leaf():\n new_children.append(taglist[ child.range[0] ])\n else:\n child.add_gold_tags(taglist)\n new_children.append(child)\n self.children = new_children\n \n def words(self):\n \"\"\"\n Returns:\n a list. A list of strings, the labels of the leaves of the tree \n \"\"\"\n toks = self.tokens()\n return [t.label for t in toks]\n\n def collect_nonterminals(self): \n \"\"\" \n Performs a traversal of the tree and returns the\n nonterminals labels according to this node ordering.\n\n Returns:\n a list. A list of strings, the labels of the leaves of the tree \n \"\"\"\n if self.is_leaf():\n return [ ]\n \n result = [ self.label ]\n for child in self.children:\n result.extend(child.collect_nonterminals())\n return result\n \n #TRANSFORMS\n def strip_tags(self):\n \"\"\"\n In place (destructive) removal of pos tags\n \"\"\"\n def gen_child(node):\n if len(node.children) == 1 and node.children[0].is_leaf():\n return node.children[0]\n return node\n \n self.children = [gen_child(child) for child in self.children]\n for child in self.children:\n child.strip_tags()\n \n def close_unaries(self,dummy_annotation='@'):\n \"\"\"\n In place (destructive) unary closure of unary branches\n \"\"\"\n if self.arity() == 1:\n current = self\n unary_labels = []\n while current.arity() == 1 and not current.children[0].is_leaf():\n unary_labels.append(current.label)\n current = current.children[0]\n unary_labels.append(current.label)\n self.label = dummy_annotation.join(unary_labels)\n self.children = current.children\n \n for child in self.children:\n child.close_unaries()\n\n def expand_unaries(self,dummy_annotation='@'):\n \"\"\"\n In place (destructive) expansion of unary symbols.\n \"\"\"\n if dummy_annotation in self.label:\n unary_chain = self.label.split(dummy_annotation) \n current_label = unary_chain.pop()\n current_children = self.children \n while unary_chain:\n c = DiscoTree(current_label,self.children)\n current_label = unary_chain.pop()\n current_children = [c]\n self.label = current_label\n self.children = current_children\n \n for child in self.children:\n child.expand_unaries()\n\n #EVALUATION\n def eval_couples(self):\n \"\"\"\n Extracts a list of evaluation couples from the tree,\n where each couple is (nonterminal,indexes of leaves in the yield of the nonterminal) \n Returns:\n A list of eval couples. \n \"\"\"\n #look at the practice in the disco community\n cples = [(self.label,set(self.range))]\n for child in self.children:\n cples.extend(child.eval_couples())\n return cples\n \n def compare(self,other):\n \"\"\"\n Compares this tree to another and computes precision,recall,fscore.\n Assumes self is the reference tree, other is the predicted tree.\n \n Args:\n param other: the predicted tree\n Returns\n A tuple of floats. (precision,recall,fscore)\n \"\"\"\n cplesA = self.eval_couples()\n cplesB = other.eval_couples()\n AcapB = [ c for c in cplesA if c in cplesB ]\n refN = len(cplesA)\n predN = len(cplesB)\n interN = len(AcapB)\n prec = interN/predN\n rec = interN/refN\n fsc = 2*prec*rec/(prec+rec)\n return prec,rec,fsc\n\n #INPUT/OUTPUT\n def __str__(self):\n \"\"\"\n Pretty prints the tree.\n Returns:\n A string. The pretty printing\n \"\"\"\n self.order_left_corner(recursive=False)\n \n if self.is_leaf():\n return '%d=%s'%(list(self.range)[0],self.label)\n \n return '(%s %s)'%(self.label,' '.join([str(child) for child in self.children]))\n\n @staticmethod\n def read_tree(input_str):\n \"\"\"\n Reads a one line s-expression using disco-dop format.\n This is a non robust function to syntax errors\n Args:\n Input_str (str): a disco s-expr string\n Returns:\n A DiscoTree object\n \"\"\"\n tokens = input_str.replace('(',' ( ').replace(')',' ) ').split()\n stack = [ ]\n for idx,tok in enumerate(tokens):\n if tok == '(':\n current = tokens[idx+1]\n stack.append(current)\n elif tok == ')':\n reduction = [ ]\n while type(stack[-1]) != str :\n reduction.append(stack.pop())\n root_label = stack.pop()\n reduction.reverse()\n stack.append( DiscoTree(root_label,children = reduction) )\n else:\n if tokens[idx-1] != '(':\n chunks = tok.split('=')\n idx,wform = (chunks[0],'='.join(chunks[1:])) if len(chunks) > 2 else (chunks[0],chunks[1])\n stack.append(DiscoTree(wform,child_index = int(idx)))\n \n assert(len(stack) == 1)\n root = stack[-1]\n return root\n\n \n\nif __name__ == \"__main__\":\n \n t = DiscoTree.read_tree('(U (X 1=Y 2=Z) (A 0=B 3=C 4=D))')\n static_oracle(t,t)\n print(t)\n \n t = DiscoTree.read_tree('(S (VP (VB 0=is) (JJ 2=rich)) (NP 1=John) (? 3=?))')\n print(t,'gap-degree',t.gap_degree())\n print(t.words())\n static_oracle(t,t)\n print()\n \n t2 = DiscoTree.read_tree(\"(ROOT (SBARQ (SQ (VP (WHADVP (WRB 0=Why)) (VB 4=cross) (NP (DT 5=the) (NN 6=road))) (VBD 1=did) (NP (DT 2=the) (NN 3=chicken))) (. 7=?)))\")\n print(t2,'gap_degree',t2.gap_degree())\n print(t2.words())\n static_oracle(t2,t2)\n print()\n \n t3 = DiscoTree.read_tree('(S (NP 0=John) (VP (VB 1=is) (JJ 2=rich)) (PONCT 3=.))')\n print(t3,'gap_degree',t3.gap_degree())\n print(t3.words(),t3.compare(t3))\n \n"} {"blob_id": "3f0380665e77c862c6cf9ad4cc64dc30b2a78909", "repo_name": "aucan/LeetCode-problems", "path": "/986.IntervalListIntersections.py", "length_bytes": 2393, "score": 3.8125, "int_score": 4, "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat May 23 21:54:45 2020\n\n@author: nenad\n\"\"\"\n\n\n\"\"\"\nProblem URL: https://leetcode.com/explore/challenge/card/may-leetcoding-challenge/537/week-4-may-22nd-may-28th/3338/\nProblem description: \nInterval List Intersections\nGiven two lists of closed intervals, each list of intervals is pairwise disjoint and in sorted order.\n\nReturn the intersection of these two interval lists.\n\n(Formally, a closed interval [a, b] (with a <= b) denotes the set of real numbers x with a <= x <= b. The intersection of two closed intervals is a set of real numbers that is either empty, or can be represented as a closed interval. For example, the intersection of [1, 3] and [2, 4] is [2, 3].)\n\n \n\nExample 1:\n\n\n\nInput: A = [[0,2],[5,10],[13,23],[24,25]], B = [[1,5],[8,12],[15,24],[25,26]]\nOutput: [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]\nReminder: The inputs and the desired output are lists of Interval objects, and not arrays or lists.\n \n\nNote:\n\n0 <= A.length < 1000\n0 <= B.length < 1000\n0 <= A[i].start, A[i].end, B[i].start, B[i].end < 10^9\nNOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.\n\"\"\"\n# Intersection example:\n# [1,3], [2, 5] -> take maximum of start (left values) and minimum of end (right values)\n# Pay attention: start value of intersection must be less or equal than end value\n# [20, 22], [13, 19] -> no intersection\n\n# Time: O(m+n), space: O(m+n)\nclass Solution:\n def intervalIntersection(self, A, B):\n result = []\n i, j = 0, 0\n while i < len(A) and j < len(B):\n minA, maxA = A[i]\n minB, maxB = B[j]\n # there is no interesection - take next interval from A\n if maxA < minB:\n i += 1\n continue \n else:\n start = max(minA, minB)\n end = min(maxA, maxB)\n # interval intersection condition\n if start <= end:\n result.append([start, end])\n # take next interval from A\n if maxA < maxB:\n i += 1\n # take next interval from B\n else:\n j += 1\n return result\n\n \nsol = Solution()\n\n# Test 1\nA = [[0,2],[5,10],[13,23],[24,25]]\nB = [[1,5],[8,12],[15,24],[25,26]]\nprint(sol.intervalIntersection(A, B))"} {"blob_id": "8a442807ebebaed03a8a6fb06f212cdad6ce21fd", "repo_name": "Timothy-py/100-PythonChallenges", "path": "/Q76.py", "length_bytes": 749, "score": 4.0, "int_score": 4, "content": "# Write an algorithm to determine if a number n is happy.\n# A happy number is a number defined by the following process:\n# Starting with any positive integer, replace the number by the sum of the squares of its digits.\n# Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.\n# Those numbers for which this process ends in 1 are happy. Return true if n is a happy number, and false if not.\n\n\ndef is_happy(n):\n seen = set()\n while n != 1:\n n = sum(int(d)**2 for d in str(n))\n if n in seen:\n return False\n seen.add(n)\n return True\n\n\nprint(is_happy(19)) # prints True\nprint(is_happy(7)) # prints True\nprint(is_happy(2)) # prints False\n"} {"blob_id": "9a6578d87eb5bf4bd2b566afb8bc28161c6acfd2", "repo_name": "anis-byanjankar/python-leetcode", "path": "/isomorphic.py", "length_bytes": 2186, "score": 3.75, "int_score": 4, "content": "# https://leetcode.com/problems/isomorphic-strings/\n#\n# Given two strings s and t, determine if they are isomorphic.\n#\n# Two strings are isomorphic if the characters in s can be replaced to get t.\n#\n# All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.\n#\n# For example,\n# Given \"egg\", \"add\", return true.\n#\n# Given \"foo\", \"bar\", return false.\n#\n# Given \"paper\", \"title\", return true.\n\nimport unittest\nclass Solution(object):\n def isIsomorphic(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: bool\n \"\"\"\n\n if len(s) != len(t):\n return False\n else:\n list_s = list(s)\n list_t = list(t)\n my_dict = {}\n for i in xrange(len(s)):\n if list_s[i] in my_dict:\n if my_dict[list_s[i]] == list_t[i]:\n continue\n else:\n return False\n else:\n my_dict[list_s[i]] = list_t[i]\n if len(set(my_dict.values())) pair_moon[i]:\r\n vel[j][i] -= 1\r\n elif moon[i] < pair_moon[i]:\r\n vel[j][i] += 1\r\n return vel\r\n\r\n\r\ndef new_position(pos, vel):\r\n \"\"\"Calculates the new position od the moons\"\"\"\r\n for i in range(4):\r\n for j in range(3):\r\n pos[i][j] += vel[i][j]\r\n\r\n return pos\r\n\r\n\r\ndef get_energy(pos, vel):\r\n \"\"\"Calculates the total energy in the system\"\"\"\r\n total = 0\r\n for i in range(4):\r\n pot, kin = 0, 0\r\n for j in range(3):\r\n pot += abs(pos[i][j])\r\n kin += abs(vel[i][j])\r\n total += pot*kin\r\n return total\r\n\r\n\r\ndef lcm(a, b, c):\r\n \"\"\"Calculates the least common multiple for 3 integers\"\"\"\r\n gcd2 = gcd(a, b)\r\n lcm2 = a*b // gcd2\r\n lcm3 = c*lcm2 // gcd(c, lcm2)\r\n return lcm3\r\n\r\n\r\nif __name__ == \"__main__\":\r\n f = open(\"./day 12/inputday12.txt\", \"r\")\r\n position = []\r\n velocity = [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]\r\n fil = f.readlines()\r\n for line in fil:\r\n pos = line.strip(\"<=>x\\n\").split(\",\")\r\n for i in range(3):\r\n pos[i] = int(pos[i].strip(\" y=z\"))\r\n position.append(pos)\r\n inc_pos = deepcopy(position)\r\n inc_vel = deepcopy(velocity)\r\n # 1st part of the challenge\r\n for step in range(1000):\r\n velocity = new_velocity(position, velocity)\r\n position = new_position(position, velocity)\r\n print(get_energy(position, velocity))\r\n\r\n ax = []\r\n \"\"\" For every axis (x,y,z) calculates the cycle for it to return\r\n to the initial state, and then the lcm of the 3 is the answer\"\"\"\r\n for i in range(3):\r\n count = 1\r\n axis = 0\r\n position = deepcopy(inc_pos)\r\n velocity = deepcopy(inc_vel)\r\n while True:\r\n velocity = new_velocity(position, velocity)\r\n position = new_position(position, velocity)\r\n count += 1\r\n for j in range(4):\r\n if position[j][i] == inc_pos[j][i]:\r\n axix += 1\r\n else:\r\n axix = 0\r\n break\r\n if axix == 4:\r\n break\r\n ax.append(count)\r\n # 2nd part result\r\n print(lcm(ax[0], ax[1], ax[2]))\r\n"} {"blob_id": "2725bf8148af60d95cdff9767f6267c23d3b072e", "repo_name": "tovine/TFE4141-project", "path": "/Project/monexp.py", "length_bytes": 1983, "score": 3.765625, "int_score": 4, "content": "#!/usr/bin/env python\n\nimport sys, re\n\n#Helper function - returns the value of the bit at position 'n' of the number 'a'\ndef getBitAt(a, n):\n\tif n >= 0 and (a & (1 << (n))) != 0:\n\t\treturn 1\n\telse:\n\t\treturn 0\n\n# Returns a*b mod n\ndef blakley(a,b,n):\n\tk=129 # 2^128 is a 129 bit number!\n\tprint('Blakley: ',hex(a),hex(b),hex(n))\n\tp=0\n\tfor i in range(0,k): \n p = p << 1\n if getBitAt(a,(k-1-i)):\n p = p + b\n\t\tif p>=n:\n\t\t\tp=p-n\n\t\tif p>=n:\n\t\t\tp=p-n\n#\tassert(p == a*b%n) # This line is useful to include when testing the blakley routine\n\treturn p\n\n\n# Returns u = a*b*r^-1 (mod n)\ndef monpro(a,b,n):\n\tprint('monpro: ',a,b,n)\n\tu=0\n\tk=128\n\tfor i in range(0,k):\n\t\tif getBitAt(a,i): #u=u+a[i]*b\n\t\t\tu = u + b\n\t\tif getBitAt(u,0):\n\t\t\tu=u+n\n\t\tu=u>>1\n\tif (u >= n):\n\t\tu = u - n\n\tprint('Final result:',hex(u))\n\treturn u\n\ndef modexp(m,e,n,r):\n k=128\n\tx_= blakley(2**128,0x1,n) # = R*mod(n)\n\tm_ = blakley(2**128,m,n) # r = 2^k = 2^128 always\n for i in range(k-1,-1,-1):\n\t\tx_=monpro(x_,x_,n)\n\t\tprint('x_: ',hex(x_))\n\t\t#if e[i]==1:\n\t\tif getBitAt(e,i):\n\t\t\tx_=monpro(m_,x_,n)\n\tx=monpro(x_,1,n)\n\treturn x\n\nprint(\"sys.argv length:\", len(sys.argv), sys.argv)\nif len(sys.argv) is 5:\n\tif sys.argv[1] == 'b':\n\t\tprint(blakley(int(sys.argv[2],0), int(sys.argv[3],0), int(sys.argv[4],0)))\n\telif sys.argv[1] == 'mp':\n\t\tprint(monpro(int(sys.argv[2],0), int(sys.argv[3],0), int(sys.argv[4],0)))\n\telif re.match(\"[0-9]*\", sys.argv[1]):\n\t\t# We can assume that all input are numeric - run modexp with the given arguments\n\t\tresult = modexp(int(sys.argv[1],0), int(sys.argv[2],0), int(sys.argv[3],0), int(sys.argv[4],0))\n\t\tprint(result, hex(result))\n\nelif len(sys.argv) is 4:\n\tif sys.argv[1] == 'gba':\n\t\tprint(bin(int(sys.argv[2],0)), getBitAt(int(sys.argv[2],0), int(sys.argv[3],0)))\n\nelse:\n\tprint(\"\"\"Available functions:\n\t'gba' - getBitAt(n,i), get bit i of the number n\n\t'b' - blakley(a,b,n)\n\t'mp' - monpro(a,b,n)\n\tdefault: modexp(m,e,n,r)\"\"\")\n"} {"blob_id": "7266fa816bb41312ffa2cfd2ea6483e204003a5b", "repo_name": "murphsp1/ProjectEuler_Python", "path": "/p9.py", "length_bytes": 772, "score": 3.5625, "int_score": 4, "content": "import sys\n\n\ndef main():\n possible_solutions = []\n for a in xrange(1,1000):\n for b in xrange(a,1000):\n left_side = 2000*(a+b)-2*a*b\n if left_side==1000**2:\n possible_solutions.append([a,b])\n print(possible_solutions)\n even_closer = []\n\n for ab in possible_solutions:\n for c in xrange(3,1000):\n a = ab[0]\n b = ab[1]\n if a+b+c==1000:\n even_closer.append([a,b,c])\n print(even_closer)\n for abc in even_closer:\n a = abc[0]\n b = abc[1]\n c = abc[2]\n if (a**2 + b**2) == c**2:\n print(a,b,c)\n print(a*b*c)\n break\n\n\n\nif __name__ == '__main__':\n #call function that we need\n\n\n sys.exit(main())\n\n\n"} {"blob_id": "941ae20e99ba7d133cd26ea6b92c795d6d21530e", "repo_name": "LeBron-Jian/BasicAlgorithmPractice", "path": "/\u5251\u6307offer/PythonVersion/30_\u5305\u542b min\u51fd\u6570\u7684\u6808.py", "length_bytes": 2500, "score": 4.03125, "int_score": 4, "content": "#_*_coding:utf-8_*_\n'''\n\u9898\u76ee\uff1a\n \u5251\u6307offer 30 \u5305\u542b min\u51fd\u6570\u7684\u6808\n\n \u5b9a\u4e49\u6808\u7684\u6570\u636e\u7ed3\u6784\uff0c\u8bf7\u5728\u8be5\u7c7b\u578b\u4e2d\u5b9e\u73b0\u4e00\u4e2a\u80fd\u591f\u5f97\u5230\u6808\u7684\u6700\u5c0f\u5143\u7d20\u7684 min \u51fd\u6570\u5728\u8be5\u6808\u4e2d\uff0c\n \u8c03\u7528 min, push\u4ee5pop\u7684\u65f6\u95f4\u590d\u6742\u5ea6\u90fd\u662fO(1)\n\n\u793a\u4f8b:\n MinStack minStack = new MinStack();\n minStack.push(-2);\n minStack.push(0);\n minStack.push(-3);\n minStack.min(); --> \u8fd4\u56de -3.\n minStack.pop();\n minStack.top(); --> \u8fd4\u56de 0.\n minStack.min(); --> \u8fd4\u56de -2.\n \u00a0\n\n\u63d0\u793a\uff1a\n \u5404\u51fd\u6570\u7684\u8c03\u7528\u603b\u6b21\u6570\u4e0d\u8d85\u8fc7 20000 \u6b21\n\n\n'''\nclass MinStack:\n '''\n \u666e\u901a\u6808\u7684push() \u548c pop() \u51fd\u6570\u7684\u590d\u6742\u5ea6\u4e3aO(1) \u800c\u83b7\u53d6\u6808\u6700\u5c0f\u503c min()\n \u51fd\u6570\u9700\u8981\u904d\u5386\u6574\u4e2a\u6808\uff0c\u590d\u6742\u5ea6\u4e3aO(n)\n\n \u96be\u70b9\uff1a \u5c06 min() \u51fd\u6570\u590d\u6742\u5ea6\u964d\u4e3aO(1)\uff0c\u53ef\u901a\u8fc7\u5efa\u7acb\u8f85\u52a9\u6808\u5b9e\u73b0\n\n \u590d\u6742\u5ea6\u5206\u6790\uff1a\n \u65f6\u95f4\u590d\u6742\u5ea6O(1)\n \u7a7a\u95f4\u590d\u6742\u5ea6O(n)\n\n '''\n\n def __init__(self):\n \"\"\"\n initialize your data structure here.\n \"\"\"\n self.main_stack = []\n self.aux_stack = []\n\n\n def push(self, x: int) -> None:\n '''\n push(x) \u7ec8\u70b9\u4e3a\u4fdd\u6301\u8f85\u52a9\u6808\u7684\u5143\u7d20\u662f\u975e\u4e25\u683c\u964d\u5e8f\n\n \u5c06x\u538b\u5165\u6808A\n \u82e51\u6808B\u4e3a\u7a7a \u62162 x \u5c0f\u4e8e\u7b49\u4e8e\u6808B\u7684\u6808\u9876\u5143\u7d20\uff0c\u5219\u5c06x \u538b\u5165\u6808B\n '''\n if len(self.main_stack) == 0:\n self.main_stack.append(x)\n self.aux_stack.append(x)\n else:\n self.main_stack.append(x) \n last_value = self.aux_stack[-1]\n if last_value > x:\n self.aux_stack.append(x)\n else:\n self.aux_stack.append(last_value) \n\n\n def pop(self) -> None:\n '''\n \u91cd\u70b9\u4e3a\u4fdd\u6301\u6808A\uff0cB\u5143\u7d20\u4e00\u81f4\u6027\n \u5373\u540c\u65f6\u4fdd\u6301\u6808A\uff0c\u6808B\u51fa\u6808\n '''\n if not self.main_stack:\n return None\n self.aux_stack.pop()\n self.main_stack.pop()\n\n\n def top(self) -> int:\n '''\n \u76f4\u63a5\u8fd4\u56de\u4e3b\u6808\u6216\u8005\u8f85\u6808\u7684\u6808\u9876\u5143\u7d20\n '''\n if not self.main_stack:\n return None\n return self.main_stack[-1]\n\n\n def min(self) -> int:\n '''\n \u76f4\u63a5\u8fd4\u56de\u8f85\u52a9\u6808\u7684\u6808\u9876\u5143\u7d20\n '''\n if not self.aux_stack:\n return None\n return self.aux_stack[-1]\n\n\n# Your MinStack object will be instantiated and called as such:\n# obj = MinStack()\n# obj.push(x)\n# obj.pop()\n# param_3 = obj.top()\n# param_4 = obj.min()\n"} {"blob_id": "ea8981bff499c7f108f655da6e36ed1b989a78a6", "repo_name": "clorenz7/corcore", "path": "/pycorcore/leetcode/bst_kth_small.py", "length_bytes": 2164, "score": 3.796875, "int_score": 4, "content": "\"\"\"\nGiven a binary search tree, write a function to find the kth smallest element in it.\n(1 \u2264 k \u2264 BST's total elements)\n\"\"\"\n\n# Basic idea:\n# (1) Do a DFS, prioritizing left.\n# (2) keep a counter of the number of nodes you have \"exited\"\n# (3) We \"exit\" after checking left, before going right.\n# (3) The kth one you exit is the node.\n\n# Alternately, could do k min value searches, and k-1 deletes.\n\nfrom collections import defaultdict\n\n\ndef kth_smallest(root, k=1):\n \"\"\"\n assume root node has .left, .right, .parent, ,key fields.\n \"\"\"\n\n node_status = defaultdict(lambda: 'unvisited')\n\n count = 0\n stack = [root] # A list is a stack.\n\n while len(stack) != 0:\n do_increment = False\n current_node = stack[-1] # ie peek\n\n node_status[current_node] = 'visited'\n\n if current_node.left is not None:\n\n left_status = node_status[current_node.left]\n if left_status == 'exited':\n stack.pop()\n do_increment = True\n\n elif left_status == 'unvisited':\n stack.append(current_node.left)\n continue\n else:\n stack.pop()\n do_increment = True\n\n if current_node.right is not None:\n stack.append(current_node.right)\n\n if do_increment:\n node_status[current_node] = 'exited'\n count += 1\n if count == k:\n return current_node.key\n\n raise IndexError(\"Tree is too small! Only found: {} nodes\".format(count))\n\n\nclass Node(object):\n def __init__(self, key, parent=None, left=None, right=None):\n self.parent = parent\n self.left = left\n self.right = right\n self.key = key\n\n\ndef test_kth():\n nodes = [Node(i) for i in range(10)]\n\n nodes[6].left = nodes[2]\n nodes[2].left = nodes[1]\n nodes[4].left = nodes[3]\n nodes[8].left = nodes[7]\n\n nodes[2].right = nodes[4]\n nodes[4].right = nodes[5]\n nodes[6].right = nodes[8]\n nodes[8].right = nodes[9]\n\n root = nodes[6]\n\n for k in range(9):\n key = kth_smallest(root, k+1)\n print(key)\n\nif __name__ == \"__main__\":\n test_kth()\n\n\n"} {"blob_id": "820ef3c2dcbe3f1470c61a196344b151e193a4cd", "repo_name": "Ahmed--Mohsen/leetcode", "path": "/count_complete_tree_nodes.py", "length_bytes": 1106, "score": 3.890625, "int_score": 4, "content": "\"\"\"\n\nGiven a complete binary tree, count the number of nodes.\n\nDefinition of a complete binary tree from Wikipedia:\nIn a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.\n\n\"\"\"\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n\t\n\t# @param {TreeNode} root\n\t# @return {integer}\n\tdef countNodes(self, root):\n\t\t\n\t\t# base case\n\t\tif root == None:\treturn 0\n\t\t\n\t\t# max height from left\n\t\theight_left = 0\n\t\tleft = root\n\t\twhile left:\n\t\t\theight_left += 1\n\t\t\tleft = left.left\n\t\t\t\n\t\t# max hight from right\n\t\theight_right = 0\n\t\tright = root\n\t\twhile right:\n\t\t\theight_right += 1\n\t\t\tright = right.right\n\t\t\t\n\t\t# check if root holding a perfect tree ... (2^h - 1) nodes\n\t\tif height_left == height_right:\n\t\t\treturn pow(2, height_left) - 1\n\t\t\n\t\t# not perfect tree case \n\t\treturn 1 + self.countNodes(root.left) + self.countNodes(root.right)"} {"blob_id": "8efc8bc7d3ba185ad73d2f11eb56dfce9d185724", "repo_name": "frankpiva/leetcode", "path": "/2020/06/25.py", "length_bytes": 1549, "score": 4.0625, "int_score": 4, "content": "\"\"\"\nFind the Duplicate Number\n\nGiven an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.\n\nExample 1:\n\nInput: [1,3,4,2,2]\nOutput: 2\n\nExample 2:\n\nInput: [3,1,3,4,2]\nOutput: 3\n\nNote:\n\n You must not modify the array (assume the array is read only).\n You must use only constant, O(1) extra space.\n Your runtime complexity should be less than O(n2).\n There is only one duplicate number in the array, but it could be repeated more than once.\n\"\"\"\"\n\n# naive solution, violates memory constraint\nclass Solution(object):\n def findDuplicate(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n dictionary = {}\n for n in nums:\n if n in dictionary:\n return n\n else:\n dictionary[n] = True\n\n# tortoise and hare solution\nclass Solution(object):\n def findDuplicate(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if len(numbers) < 1: return None\n fast = nums[nums[nums[0]]]\n slow = nums[nums[0]]\n \n while fast != slow: # find the collision\n fast = nums[nums[fast]]\n slow = nums[slow]\n \n slow = nums[0] # reset slow pointer\n \n while fast != slow: # find the duplicate\n fast = nums[fast]\n slow = nums[slow]\n \n return fast"} {"blob_id": "f8b089acea025923e8f4ab12ce45c5a76c4890e6", "repo_name": "yanntrividic/quarto-game", "path": "/src/quarto/players/agents.py", "length_bytes": 6083, "score": 3.734375, "int_score": 4, "content": "'''\nCreated on Mar 21, 2021\n\n@author: yann\n'''\n\nfrom random import randint\n\nfrom ..constants import (SCOLS, SROWS)\nfrom .minimax import minimax\nfrom .player import Player\nfrom .utils import get_not_losing_moves, get_winning_moves, get_coor_selected_piece\n\n\nclass AI_level1(Player):\n '''\n classdocs\n '''\n\n def __init__(self, name):\n '''\n Constructor\n '''\n self.__name__ = name\n\n def select(self, game, row, col):\n '''\n '''\n selected_piece = None\n\n if game.pick:\n # \u00a0At this point, we have to pick a piece from the storage board\n while True:\n rand_row = randint(0, SROWS - 1)\n rand_col = randint(0, SCOLS - 1)\n if game.storage_board.get_piece(rand_row, rand_col) != 0:\n break\n game.selected_piece = game.storage_board.get_piece(rand_row, rand_col)\n game.valid_moves = game.game_board.get_valid_moves()\n selected_piece = (rand_col, rand_row)\n\n else:\n # And in this case we have to move the piece to the game board\n rand_move = get_random_move(game)\n game.move(rand_move[0], rand_move[1])\n game.selected_piece = None\n game.valid_moves = []\n\n game.end_turn(selected_piece)\n\n return True\n\n\nclass AI_level2(Player):\n '''\n This AI uses a very naive algorithm that allows it to verify if the piece that was given to it can allow it to win,\n and which won't pick a piece if it allows the opponent to immediately win (unless there is no other choice).\n '''\n\n def __init__(self, name):\n '''\n Constructor\n '''\n self.__name__ = name\n\n def select(self, game, row, col):\n '''\n '''\n selected_piece = None\n winning_moves = []\n not_losing_moves = []\n\n if game.pick:\n # \u00a0At this point, we have to pick a piece from the storage board\n not_losing_moves = get_not_losing_moves(game)\n if not not_losing_moves:\n print(\"Oh no...\")\n\n while True:\n rand_move = get_random_move(game) if not not_losing_moves else not_losing_moves[0] # not random\n if game.storage_board.get_piece(rand_move[0], rand_move[1]) != 0:\n break\n\n game.selected_piece = game.storage_board.get_piece(rand_move[0], rand_move[1])\n game.valid_moves = game.game_board.get_valid_moves()\n selected_piece = (rand_move[1], rand_move[0])\n\n else:\n # And in this case we have to move the piece to the game board\n winning_moves = get_winning_moves(game)\n\n if winning_moves:\n row, col = winning_moves[0]\n game.move(row, col)\n\n else:\n rand_move = get_random_move(game, True)\n game.move(rand_move[0], rand_move[1])\n\n game.valid_moves = []\n\n game.end_turn(selected_piece)\n\n return True\n\n\ndef get_random_move(game, verbose=False):\n '''Returns a random move\n '''\n if game.pick:\n move = game.storage_board.get_valid_moves()[randint(0, len(game.storage_board.get_valid_moves()) - 1)]\n else:\n move = game.valid_moves[randint(0, len(game.valid_moves) - 1)]\n if verbose:\n print(move)\n return move\n\n\nclass AI_level3(Player):\n '''\n This AI uses the minmax algorithm.\n '''\n\n def __init__(self, name):\n '''\n Constructor\n '''\n self.__name__ = name\n\n # (depth, nb of turns left)\n self.DEPTH_1_UNTIL = (1, 14) # \u00a0during the two first rounds we just check the first layer\n self.DEPTH_2_UNTIL = (2, 9)\n self.DEPTH_3_UNTIL = (3, 5)\n self.DEPTH_4_UNTIL = (4, 0)\n\n def select(self, game, row, col):\n '''\n This select method is a bit different from the past ones as we don't give control back to the game after the\n piece is placed, we do the placing and the picking at once\n '''\n\n self.update_depth(game)\n\n # before picking the first piece\n if len(game.game_board.get_valid_moves()) == SCOLS * SROWS and game.pick:\n move = get_random_move(game)\n print(move)\n # game.selected_piece = game.storage_board.get_piece(move[0], move[1])\n game.valid_moves = game.game_board.get_valid_moves()\n game.end_turn(game.selected_piece)\n return True\n\n game_state = (game.game_board, game.storage_board, get_coor_selected_piece(game.storage_board, game.selected_piece))\n result = minimax(game_state, self.depth, True)\n\n if result[1]: # if none, that means there is no piece left\n game.game_board, game.storage_board, selected_piece_coor = result[1]\n # \u00a0the position played and the picked piece are both returned at the same time\n print(game.game_board, game.storage_board, \"\\n\", selected_piece_coor)\n\n game.end_turn(None)\n\n game.selected_piece = game.storage_board.get_piece(selected_piece_coor[0], selected_piece_coor[1])\n game.valid_moves = game.game_board.get_valid_moves()\n\n if not game.winner(): # \u00a0when there is a winner, no need to swap turns\n selected_piece = (selected_piece_coor[1], selected_piece_coor[0])\n game.end_turn(selected_piece)\n\n return True\n\n def update_depth(self, game):\n '''\n Updates the depth attribute depending on how far into the game we are.\n '''\n nb_turns = len(game.game_board.get_valid_moves())\n\n print(\"nb_turns =\", nb_turns)\n\n if nb_turns > self.DEPTH_1_UNTIL[1]:\n self.depth = self.DEPTH_1_UNTIL[0]\n elif nb_turns > self.DEPTH_2_UNTIL[1]:\n self.depth = self.DEPTH_2_UNTIL[0]\n elif nb_turns > self.DEPTH_3_UNTIL[1]:\n self.depth = self.DEPTH_3_UNTIL[0]\n elif nb_turns > self.DEPTH_4_UNTIL[1]:\n self.depth = self.DEPTH_4_UNTIL[0]\n\n print(\"depth =\", self.depth)\n"} {"blob_id": "1636c2c42b4587826b8054ccdae838ed57263558", "repo_name": "Tofu-Gang/advent_of_code_2020", "path": "/day_01/day_01.py", "length_bytes": 3400, "score": 4.1875, "int_score": 4, "content": "__author__ = \"Tofu Gang\"\n__email__ = \"tofugangsw@gmail.com\"\n\nfrom itertools import combinations\nfrom functools import reduce\n\n\"\"\"\n--- Day 1: Report Repair ---\n\nAfter saving Christmas five years in a row, you've decided to take a vacation at \na nice resort on a tropical island. Surely, Christmas will go on without you.\n\nThe tropical island has its own currency and is entirely cash-only. The gold \ncoins used there have a little picture of a starfish; the locals just call them \nstars. None of the currency exchanges seem to have heard of them, but somehow, \nyou'll need to find fifty of these coins by the time you arrive so you can pay \nthe deposit on your room.\n\nTo save your vacation, you need to get all fifty stars by December 25th.\n\nCollect stars by solving puzzles. Two puzzles will be made available on each day \nin the Advent calendar; the second puzzle is unlocked when you complete the \nfirst. Each puzzle grants one star. Good luck!\n\"\"\"\n\n################################################################################\n\ndef puzzle_1() -> None:\n \"\"\"\n --- Part One ---\n\n Before you leave, the Elves in accounting just need you to fix your expense\n report (your puzzle input); apparently, something isn't quite adding up.\n\n Specifically, they need you to find the two entries that sum to 2020 and\n then multiply those two numbers together.\n\n For example, suppose your expense report contained the following:\n\n 1721\n 979\n 366\n 299\n 675\n 1456\n\n In this list, the two entries that sum to 2020 are 1721 and 299. Multiplying\n them together produces 1721 * 299 = 514579, so the correct answer is 514579.\n\n Of course, your expense report is much larger. Find the two entries that sum\n to 2020; what do you get if you multiply them together?\n\n The answer should be 444019.\n \"\"\"\n\n print(_get_product(\"day_01/input.txt\", 2))\n\n################################################################################\n\ndef puzzle_2() -> None:\n \"\"\"\n --- Part Two ---\n\n The Elves in accounting are thankful for your help; one of them even offers\n you a starfish coin they had left over from a past vacation. They offer you\n a second one if you can find three numbers in your expense report that meet\n the same criteria.\n\n Using the above example again, the three entries that sum to 2020 are 979,\n 366, and 675. Multiplying them together produces the answer, 241861950.\n\n In your expense report, what is the product of the three entries that sum to\n 2020?\n\n The answer should be 29212176.\n \"\"\"\n\n print(_get_product(\"day_01/input.txt\", 3))\n\n################################################################################\n\ndef _get_product(file_path: str, count: int) -> int:\n \"\"\"\n Loads numbers from the input file, then finds specified count of numbers\n which sum is 2020. Returns their product.\n\n :param file_path: input file path\n :param count: count of the numbers to make the resulting product\n :return: puzzle solution\n \"\"\"\n\n with open(file_path, 'r') as f:\n return reduce(\n lambda x, y: x * y,\n [combination\n for combination in combinations(\n [int(line.strip())\n for line in f.readlines()], count)\n if sum(combination) == 2020][0])\n\n################################################################################\n"} {"blob_id": "e71919114c5911bf215e6d66bcaf2e0215f08593", "repo_name": "salujaharkirat/ds-algo", "path": "/company/walmart/trees/balanced_binary_tree.py", "length_bytes": 713, "score": 3.875, "int_score": 4, "content": "\"\"\"\nhttps://leetcode.com/problems/balanced-binary-tree/\n\"\"\"\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def isBalanced(self, root: TreeNode) -> bool:\n self.is_balanced = True\n\n def traverse(root):\n if root is None:\n return 0\n\n l_height = traverse(root.left)\n r_height = traverse(root.right)\n\n if abs(r_height - l_height) > 1:\n self.is_balanced = False\n\n return max(l_height, r_height) + 1\n\n traverse(root)\n return self.is_balanced\n"} {"blob_id": "dfceec72ef83a60ac0f00f4aadb1adc359602ee6", "repo_name": "tahitian/algorithm010", "path": "/Week03/build_tree.py", "length_bytes": 1613, "score": 3.671875, "int_score": 4, "content": "from typing import List, Union\n\n\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 buildTree(self, preorder: List[int], inorder: List[int]) -> Union[TreeNode, None]:\n \"\"\"\n \u9012\u5f52\u89e3\u6cd5\uff1a\u4ece\u524d\u5e8f\u5217\u8868\u4e2d\u83b7\u53d6\u7b2c\u4e00\u4e2a\u5143\u7d20\uff0c\u8be5\u5143\u7d20\u662f\u6839\u7ed3\u70b9\n \u7136\u540e\u5728\u4e2d\u5e8f\u5e8f\u5217\u4e2d\u627e\u5230\u8be5\u5143\u7d20\uff0c\u5143\u7d20\u5de6\u4fa7\u7684 n \u4e2a\u5143\u7d20\u6784\u6210\u4e86\u6839\u7ed3\u70b9\u7684\u5de6\u5b50\u6811\n \u524d\u5e8f\u5e8f\u5217\u6839\u7ed3\u70b9\u5143\u7d20\u4e4b\u540e\u7684 n \u4e2a\u5143\u7d20\u4e5f\u6784\u6210\u4e86\u5de6\u5b50\u6811\uff0c\u5728\u4e24\u4e2a\u5de6\u5b50\u6811\u7684\u5e8f\u5217\u4e0a\u9012\u5f52\n \u540c\u7406\u5728\u4e24\u4e2a\u53f3\u5b50\u6811\u7684\u5e8f\u5217\u4e0a\u9012\u5f52\n \u65f6\u95f4\u590d\u6742\u5ea6\uff1a\u6bcf\u4e00\u8f6e\u9012\u5f52\u7684\u65f6\u95f4\u590d\u6742\u5ea6\u5728\u4e8e inorder.index()\uff0c\u4e5f\u5c31\u662f\u9012\u5f52\u7684\u5b50\u6811\u5e8f\u5217\u7684\u957f\u5ea6\n \u4ece\u6811\u5f62\u56fe\u6765\u770b\uff0c\u6bcf\u4e00\u5c42\u7684\u9012\u5f52\u7684\u65f6\u95f4\u590d\u6742\u5ea6\u4e4b\u548c\u662f\u8be5\u5c42\u5206\u6563\u51fa\u7684\u6240\u6709\u5b50\u6811\u5e8f\u5217\u7684\u957f\u5ea6\u4e4b\u548c\uff0c\u4e5f\u5c31\u662f\u603b\u5e8f\u5217\u7684\u957f\u5ea6 O(n)\n \u4e00\u5171\u6709\u5e73\u5747 O(logn) \u5c42\u9012\u5f52\uff0c\u6240\u4ee5\u603b\u7684\u65f6\u95f4\u590d\u6742\u5ea6\u662f O(nlogn)\n \u7a7a\u95f4\u590d\u6742\u5ea6\uff1a\u6bcf\u4e00\u5c42\u9012\u5f52\u5927\u6982\u4f7f\u7528\u5207\u7247\u590d\u5236\u4e00\u534a\u7684\u5e8f\u5217\u4e0a\u5c42\u5e8f\u5217\u957f\u5ea6\uff0c\u56e0\u6b64\u603b\u7684\u7a7a\u95f4\u590d\u6742\u5ea6\u662f O(n)\n \u6539\u7528 start\u3001end \u800c\u4e0d\u662f\u4f7f\u7528\u5207\u7247\u6765\u83b7\u53d6\u5b50\u6811\u5e8f\u5217\u7684\u8bdd\uff0c\u7a7a\u95f4\u590d\u6742\u5ea6\u53ef\u4ee5\u964d\u4e3a O(logn)\n \"\"\"\n if not preorder:\n return None\n root_val = preorder[0]\n i = inorder.index(root_val)\n root = TreeNode(root_val)\n root.left = self.buildTree(preorder[1:i+1], inorder[:i])\n root.right = self.buildTree(preorder[i+1:], inorder[i+1:])\n return root"} {"blob_id": "8125bd3b41290c2e8494dc375329d57cd622248c", "repo_name": "stedestro/classification", "path": "/classification.py", "length_bytes": 1932, "score": 4.0625, "int_score": 4, "content": "import math\n\ndef _euclidean_distance(p1, p2):\n '''\n Calculate the Euclidean disstance between two points\n\n Arguments:\n p1,p2: Point in list [x,y,z] or tuple format (x,y,z)\n\n Return\n (float) Distance\n '''\n dim = len(p1)\n if dim != len(p2):\n raise Exception(\"Points dimension must match\")\n val = 0\n for i in range(0,dim):\n val += math.pow(p1[i] - p2[i], 2)\n return math.sqrt(val)\n\ndef knn(training_data, test_data, k, returns_data=False):\n '''\n Calculate the k closest neighbours of a point. Classification is done by\n checking which class of data is more reprensented\n\n Arguments:\n training_data (List[List[]]) : The first level contains the different\n classes to test against, the second level contains an arbitrary\n number of points. The points are in tuple or list format\n (e.g. (x,y,z) or [x,y,z])\n test_data (point) : Point in list or tuple format (see above)\n k (int) : number of neighbours used to classify test_data\n returns_data (bool) : if True, add distances to the function's returns\n otherwise returns the index of calculated class\n\n Return:\n (int) index of calculated class\n (list) if returns_data is set to True,\n returns [(int)index of calculated[[(int)class, (float)distance, (point)],..]]\n '''\n nbc = len(training_data) # number of classes\n nn = [] # list containing all distances\n\n for cl in range(0,nbc): #for each different classes\n for data in training_data[cl]:\n nn.append([cl,_euclidean_distance(test_data, data),data])\n\n nn.sort(key=lambda x: x[1])\n sum_class = [0]*nbc\n for i in range(0,k): # calculate which class is more represented\n sum_class[nn[i][0]] += 1\n if returns_data:\n return [sum_class.index(max(sum_class)),nn]\n else:\n return sum_class.index(max(sum_class))\n"} {"blob_id": "243f6d3cbc14c2b371ce3677a24795d46e3942f0", "repo_name": "sankeerth/Algorithms", "path": "/String/python/leetcode/shortest_palindrome.py", "length_bytes": 1570, "score": 3.84375, "int_score": 4, "content": "\"\"\"\n214. Shortest Palindrome\n\nGiven a string S, you are allowed to convert it to a palindrome by adding characters in front of it.\nFind and return the shortest palindrome you can find by performing this transformation.\n\nExample 1:\nInput: s = \"aacecaaa\"\nOutput: \"aaacecaaa\"\n\nExample 2:\nInput: s = \"abcd\"\nOutput: \"dcbabcd\"\n\nConstraints:\n0 <= s.length <= 5 * 104\ns consists of lowercase English letters only.\n\"\"\"\n\n\nclass Solution:\n # Leetcode solution using KMP table. See discuss for explanation.\n def shortestPalindrome(self, s: str) -> str:\n res = [0]\n def prefix(s):\n nonlocal res\n border = 0\n for i in range(1, len(s)):\n while border > 0 and s[i] != s[border]:\n border = res[border - 1]\n border = border + 1 if s[i] == s[border] else 0\n res.append(border)\n prefix(s + '#' + s[::-1])\n return s[res[-1]:][::-1] + s\n\n\nsol = Solution()\nprint(sol.shortestPalindrome(\"abadc\"))\nprint(sol.shortestPalindrome(\"aba\"))\nprint(sol.shortestPalindrome(\"aaa\"))\nprint(sol.shortestPalindrome(\"abcd\"))\nprint(sol.shortestPalindrome(\"aacecaaa\"))\n\n\n\"\"\"\nMy Solution:\n\nclass Solution:\n def shortestPalindrome(self, s: str) -> str:\n def is_palindrome(string):\n return string == string[::-1]\n \n append_front = \"\"\n for i in range(len(s), -1, -1):\n if is_palindrome(s[:i]):\n append_front = s[i:][::-1]\n break\n \n result = append_front + s\n return result\n\"\"\"\n"} {"blob_id": "6f44f3c734ac4ecabd658e38fa9bb0bb7b9f4d85", "repo_name": "anubhavrawal/hasing-test", "path": "/code/pseudorand.py", "length_bytes": 5029, "score": 3.578125, "int_score": 4, "content": "import more_itertools as mit\nfrom random import randint as rndGen\n\nfrom mid_value import *\n\n#-------------Constant declaration------------\nHASH_TABLE_ELEMENTS = 199\n\n#------------------------------Probing list Generator------------------------------\ndef random_permute_generator(iterable, n=10):\n \"\"\"Yield a random permuation of an iterable n times.\"\"\"\n for _ in range(n):\n yield mit.random_permutation(iterable)\n\nl = list(random_permute_generator(range(1,HASH_TABLE_ELEMENTS), n=200))\nrandSelection = rndGen(0, 199)\npsudo_list = list(l[randSelection])\npsudo_list.insert(0,0)\n#----------------------------------------------------------------------------------\n\n#Closed Hasing using Pseudo Random Probing method\nclass PseudoRandomHashTable:\n def __init__(self, size, hash_func_num ='H1'):\n self.size = size\n self.keys = [None] * self.size\n self.values = [None] * self.size\n self.hash_func_num = hash_func_num\n\n def __str__(self):\n result = ''\n #print(self.keys)\n count =0\n for slot in range(len(self.keys)):\n if self.keys[slot] != None:\n result += self.keys[slot] +' ' + str(self.values[slot].Strength) +' \\n'\n if count ==5:\n return result\n count +=1\n\n return result\n \n #Using inbuild hash algorithm with modulus for finding the location within the table\n #Input Parameters: self(OpenHashTable) -> The Class's defult parameters \n # key(string) -> The key to be hashed into the table\n # \n #Returns: An index for the given key\n def hashing_function(self, key):\n return hash(key) % self.size\n\n #Using mid-squared hash function for finding the index then using mod to fit it within the table\n #Input Parameters: self(OpenHashTable) -> The Class's defult parameters \n # key(string) -> The key to be hashed into the table\n # \n #Returns: mid -> An index for the given key\n def hashing_function2(self, key):\n val = hash(key)\n val_sq = abs(val*val)\n mid = int(middle_three_digits(val_sq,self.size))\n return mid\n\n #Using folding on a string, summed 4 bytes at a time\n #Input Parameters: self(OpenHashTable) -> The Class's defult parameters \n # key(string) -> The key to be hashed into the table\n # \n #Returns: An index for the given key\n def hashing_function3(self, key):\n sum_num = 0 \n mul = 1\n for i in range(len(key)):\n if i % 4 ==0: \n mul = 1 \n else:\n mul * 256\n sum_num += ord(key[i]) * mul\n \n return int(abs(sum_num) % self.size)\n \n def get_slot(self, key):\n if self.hash_func_num ==\"H1\":\n slot = self.hashing_function(key)\n elif self.hash_func_num ==\"H2\":\n slot = self.hashing_function2(key)\n elif self.hash_func_num ==\"H3\":\n slot = self.hashing_function3(key)\n\n i=1\n while self.keys[slot]:\n if slot >= self.size:\n slot = slot - self.size \n \n slot = slot + psudo_list[i]\n \n if slot >= self.size:\n slot = slot - self.size \n i+=1\n return slot\n \n #Inserts value into the hash table\n #Input Parameters: self (OpenHashTable) -> The Class's defult parameters \n # key (string) -> The key to be hashed into the table\n # value (Generic) -> The value for key to be hashed into the table\n # \n #Returns: Nothing\n def set(self, key, value):\n slot = self.get_slot(key)\n self.keys[slot] = key\n self.values[slot] = value\n\n #Returns the value for the given key from the hash table\n #Input Parameters: self (OpenHashTable) -> The Class's defult parameters \n # key (string) -> The key to be hashed into the table\n # \n #Returns: Nothing \n def get(self, key):\n if self.hash_func_num ==\"H1\":\n slot = self.hashing_function(key)\n elif self.hash_func_num ==\"H2\":\n slot = self.hashing_function2(key)\n elif self.hash_func_num ==\"H3\":\n slot = self.hashing_function3(key)\n return_str = ''\n slot_loc = []\n strngth_mem = []\n i=0\n while self.keys[slot] and i= self.size:\n slot = slot - self.size \n i+=1\n \n slot_loc = list(dict.fromkeys(slot_loc))\n\n for loc in slot_loc:\n strngth_mem.append(self.values[loc].Strength)\n\n if len(slot_loc) != 0:\n return_str = \"slots: \" + str(slot_loc) + \"Strengths:\" + str(strngth_mem)\n else:\n return_str = \"NotFound\"\n\n return return_str"} {"blob_id": "3a6afb4865aecc970f3f7da751454b047d8e21bb", "repo_name": "AndrewNik/python_course", "path": "/less9/task2.py", "length_bytes": 2077, "score": 3.640625, "int_score": 4, "content": "# 2. \u0417\u0430\u043a\u043e\u0434\u0438\u0440\u0443\u0439\u0442\u0435 \u043b\u044e\u0431\u0443\u044e \u0441\u0442\u0440\u043e\u043a\u0443 \u043f\u043e \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u0443 \u0425\u0430\u0444\u0444\u043c\u0430\u043d\u0430.\n\nimport heapq\nfrom collections import Counter\nfrom collections import namedtuple\n\n\nclass Node(namedtuple(\"Node\", [\"left\", \"right\"])): # \u043a\u043b\u0430\u0441\u0441 \u0434\u043b\u044f \u0432\u0435\u0442\u0432\u0435\u0439 \u0434\u0435\u0440\u0435\u0432\u0430 - \u0432\u043d\u0443\u0442\u0440\u0435\u043d\u043d\u0438\u0445 \u0443\u0437\u043b\u043e\u0432; \u0443 \u043d\u0438\u0445 \u0435\u0441\u0442\u044c \u043f\u043e\u0442\u043e\u043c\u043a\u0438\n\tdef walk(self, code, acc):\n\t\tself.left.walk(code, acc + \"0\") # \u043f\u043e\u0439\u0442\u0438 \u0432 \u043b\u0435\u0432\u043e\u0433\u043e \u043f\u043e\u0442\u043e\u043c\u043a\u0430, \u0434\u043e\u0431\u0430\u0432\u0438\u0432 \u043a \u043f\u0440\u0435\u0444\u0438\u043a\u0441\u0443 \"0\"\n\t\tself.right.walk(code, acc + \"1\") # \u0437\u0430\u0442\u0435\u043c \u043f\u043e\u0439\u0442\u0438 \u0432 \u043f\u0440\u0430\u0432\u043e\u0433\u043e \u043f\u043e\u0442\u043e\u043c\u043a\u0430, \u0434\u043e\u0431\u0430\u0432\u0438\u0432 \u043a \u043f\u0440\u0435\u0444\u0438\u043a\u0441\u0443 \"1\"\n\n\nclass Leaf(namedtuple(\"Leaf\", [\"char\"])): # \u043a\u043b\u0430\u0441\u0441 \u0434\u043b\u044f \u043b\u0438\u0441\u0442\u044c\u0435\u0432 \u0434\u0435\u0440\u0435\u0432\u0430, \u0443 \u043d\u0435\u0433\u043e \u043d\u0435\u0442 \u043f\u043e\u0442\u043e\u043c\u043a\u043e\u0432, \u043d\u043e \u0435\u0441\u0442\u044c \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 \u0441\u0438\u043c\u0432\u043e\u043b\u0430\n\tdef walk(self, code, acc):\n\t\tcode[self.char] = acc or \"0\" # \u0435\u0441\u043b\u0438 \u0441\u0442\u0440\u043e\u043a\u0430 \u0434\u043b\u0438\u043d\u043e\u0439 1 \u0442\u043e acc = \"\", \u0434\u043b\u044f \u044d\u0442\u043e\u0433\u043e \u0441\u043b\u0443\u0447\u0430\u044f \u0443\u0441\u0442\u0430\u043d\u043e\u0432\u0438\u043c \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 acc = \"0\"\n\n\ndef huffman_encode(s):\n\th = []\n\tfor ch, freq in Counter(s).items():\n\t\th.append((freq, len(h), Leaf(ch)))\n\theapq.heapify(h)\n\tcount = len(h)\n\twhile len(h) > 1:\n\t\tfreq1, _count1, left = heapq.heappop(h) # \u0432\u044b\u0442\u0430\u0449\u0438\u043c \u044d\u043b\u0435\u043c\u0435\u043d\u0442 \u0441 \u043c\u0438\u043d\u0438\u043c\u0430\u043b\u044c\u043d\u043e\u0439 \u0447\u0430\u0441\u0442\u043e\u0442\u043e\u0439 - \u043b\u0435\u0432\u044b\u0439 \u0443\u0437\u0435\u043b\n\t\tfreq2, _count2, right = heapq.heappop(h) # \u0432\u044b\u0442\u0430\u0449\u0438\u043c \u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0438\u0439 \u044d\u043b\u0435\u043c\u0435\u043d\u0442 \u0441 \u043c\u0438\u043d\u0438\u043c\u0430\u043b\u044c\u043d\u043e\u0439 \u0447\u0430\u0441\u0442\u043e\u0442\u043e\u0439 - \u043f\u0440\u0430\u0432\u044b\u0439 \u0443\u0437\u0435\u043b\n\t\theapq.heappush(h, (freq1 + freq2, count, Node(left, right)))\n\t\tcount += 1\n\tcode = {} # \u0438\u043d\u0438\u0446\u0438\u0430\u043b\u0438\u0437\u0438\u0440\u0443\u0435\u043c \u0441\u043b\u043e\u0432\u0430\u0440\u044c \u043a\u043e\u0434\u043e\u0432 \u0441\u0438\u043c\u0432\u043e\u043b\u043e\u0432\n\tif h:\n\t\t[(_freq, _count, root)] = h\n\t\troot.walk(code, \"\")\n\treturn code\n\n\ns = input('\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u0441\u0442\u0440\u043e\u043a\u0443 \u0434\u043b\u044f \u043a\u043e\u0434\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f: ')\ncode = huffman_encode(s) # \u043a\u043e\u0434\u0438\u0440\u0443\u0435\u043c \u0441\u0442\u0440\u043e\u043a\u0443\nencoded = \"\".join(code[ch] for ch in s)\nfor ch in sorted(code):\n\tprint(\"{}: {}\".format(ch, code[ch])) # \u0432\u044b\u0432\u0435\u0434\u0435\u043c \u0441\u0438\u043c\u0432\u043e\u043b \u0438 \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0443\u044e\u0449\u0438\u0439 \u0435\u043c\u0443 \u043a\u043e\u0434\nprint(encoded) # \u0432\u044b\u0432\u0435\u0434\u0435\u043c \u0437\u0430\u043a\u043e\u0434\u0438\u0440\u043e\u0432\u0430\u043d\u043d\u0443\u044e \u0441\u0442\u0440\u043e\u043a\u0443\n"} {"blob_id": "c04b1d4517881691ff78b896d80f355141deb15b", "repo_name": "smspillaz/word-benchmarks", "path": "/tests/outlier.py", "length_bytes": 6082, "score": 3.53125, "int_score": 4, "content": "#!/usr/bin/env python\n\"\"\"outlier.py\n\nTest word vectors based on how well they can detect outliers.\n\nOutlier detection is based on the compactness score of\neach word, c(w) = 1/(n(n - 1)) * \\sum_{w_i \\in [W + w]} * \\sum_{w_j \\in [W + w], w_j != w_i} sim(w_i, w_j).\nWe then get the compactness score of each word, including the known outlier\nrank them all by their compactness score (higher has more similarity). The\nintuitive understanding of this is that we are taking the union of the outlier\nand the cluster, then for each term in that cluster, computing the accumulated\nintra-cluster similarity score. In principle, the outlier should have\nthe lowest score.\n\nThe scoring for outlier detection is based on (rank / n), eg, we get\nthe highest score if the outlier word has the lowest rank.\n\"\"\"\n\nimport argparse\nimport csv\nimport json\nimport os\nimport re\nimport sys\n\nimport numpy as np\n\nfrom collections import namedtuple\nfrom gensim.models import KeyedVectors\n\nfrom sklearn.metrics.pairwise import cosine_similarity\n\nfrom tqdm.auto import tqdm\n\nfrom util import make_vec, make_tokenizer\n\n\nDataset = namedtuple(\"Dataset\", \"outliers cluster\")\n\nDATASETS = {\n \"8-8-8.csv\": Dataset(2, 3),\n \"wikisem500.csv\": Dataset(2, 3),\n}\n\n\ndef filter_invalid(wordset):\n return [x for x in wordset if len(x)]\n\n\ndef load_dataset(name, path):\n with open(path) as f:\n csv_data = csv.reader(f)\n\n _ = next(csv_data)\n metadata = DATASETS[name]\n\n for row in csv_data:\n # Work around invalid action.\n #\n # The string of replace's is a poor-mans hack to work around the\n # fact that re won't let you do a negative lookbehind on a backslash\n # even if you escape it.\n outliers = json.loads(re.sub(\"(?<=[\\[\\s,])'|'(?=[\\]\\s,])\", \"\\\"\", row[metadata.outliers].strip()))\n cluster = json.loads(re.sub(\"(?<=[\\[\\s,])'|'(?=[\\]\\s,])\", \"\\\"\", row[metadata.cluster].strip()))\n\n yield filter_invalid(outliers), filter_invalid(cluster)\n\n\ndef vectorize_word(word, model, tokenizer):\n \"\"\"Vectorize the word.\n\n First try to get the vectors directly, then if that fails, split\n it on _ and \" \" to get the subword vectors. If that fails for any\n part of the word, throw an exception.\n \"\"\"\n tfunc = tokenizer.tokenize if tokenizer else lambda x: [x]\n if tokenizer:\n return make_vec(model, tfunc(word))\n\n if word in model.vocab:\n return model[word]\n\n subwords = re.split(r\"[_\\s]+\", word)\n\n for subword in subwords:\n if not subword in model.vocab:\n raise KeyError\n\n return np.mean(np.stack([\n model[subword] for subword in subwords\n ]), axis=0)\n\n\ndef process_cluster(words, model, tokenizer):\n for word in words:\n try:\n yield vectorize_word(word, model, tokenizer)\n except KeyError:\n pass\n\n\ndef simple_cosine_similarity(left, right):\n return cosine_similarity(np.array([left]), np.array([right]))[0]\n\n\ndef score_outliers(model, vectorized_outliers, vectorized_cluster):\n # Set with the outlier times set without it\n k = (len(vectorized_cluster) + 1) * (len(vectorized_cluster))\n\n # For each outlier in our set of ourliers\n for outlier in vectorized_outliers:\n cluster_with_outlier = np.concatenate([vectorized_cluster, np.array([outlier])])\n # Per-element scores (outlier is last in the list)\n p_scores = np.array([\n np.sum([\n simple_cosine_similarity(left_element, right_element)\n for j, right_element in enumerate(cluster_with_outlier)\n if i != j\n ])\n for i, left_element in enumerate(cluster_with_outlier)\n ]) / k\n\n # Now get the ranking of our outlier on the p-scores.\n yield list(reversed(np.argsort(p_scores)))[-1]\n\n\ndef score_cluster(model, outliers, cluster, tokenizer):\n vectorized_outliers = np.array(list(process_cluster(outliers, model, tokenizer)))\n vectorized_cluster = np.array(list(process_cluster(cluster, model, tokenizer)))\n\n if not len(vectorized_outliers) or not len(vectorized_cluster):\n return None\n\n positions = np.array(list(score_outliers(model,\n vectorized_outliers,\n vectorized_cluster)))\n return np.mean(positions) / len(vectorized_cluster)\n\n\n\n\ndef score_dataset(model, dataset, tokenizer):\n \"\"\"Get score for one dataset for a given KeyedVectors model.\"\"\"\n cluster_scores = list(filter(lambda x: x is not None, [\n score_cluster(model, outliers, cluster, tokenizer)\n for outliers, cluster in tqdm(dataset, desc=\"Processing dataset\")\n ]))\n return np.mean(cluster_scores) if cluster_scores else 0\n\n\ndef score_model(model, datasets, tokenizer):\n \"\"\"Get scores for all datasets.\"\"\"\n\n for dataset_name in tqdm(sorted(datasets.keys()), desc=\"Processing Datasets\"):\n yield score_dataset(model, datasets[dataset_name], tokenizer)\n\n\ndef load_model(name):\n \"\"\"Load a model.\"\"\"\n return KeyedVectors.load(name).wv\n\n\ndef main():\n \"\"\"Entry point.\"\"\"\n parser = argparse.ArgumentParser(\"\"\"Outlier detection score checker.\"\"\")\n parser.add_argument(\"models\", nargs=\"+\")\n parser.add_argument(\"--benchmarks\", nargs=\"+\", default=list(DATASETS.keys()))\n parser.add_argument(\"--data-dir\", type=str, help=\"Path to data\")\n parser.add_argument(\"--tokenizer\", type=str, help=\"Tokenizer to use\")\n args = parser.parse_args()\n\n models = {\n os.path.basename(n): load_model(n) for n in args.models\n }\n\n datasets = {\n n: list(load_dataset(n, os.path.join(args.data_dir, n))) for n in args.benchmarks\n }\n\n output = csv.writer(sys.stdout)\n output.writerow(['model'] + sorted(datasets.keys()))\n tokenizer = make_tokenizer(args.tokenizer)\n for model_name in tqdm(sorted(models.keys()), desc=\"Processing Models\"):\n output.writerow([model_name] + list(score_model(models[model_name], datasets, tokenizer)))\n\n\nif __name__ == \"__main__\":\n main()\n"} {"blob_id": "e74ddfcc4b04789ce051adee50598c592547d7fb", "repo_name": "congyingTech/Basic-Algorithm", "path": "/medium/hot100/2-add-two-numbers.py", "length_bytes": 2341, "score": 4.25, "int_score": 4, "content": "\"\"\"\n\u7ed9\u4f60\u4e24\u4e2a\u00a0\u975e\u7a7a \u7684\u94fe\u8868\uff0c\u8868\u793a\u4e24\u4e2a\u975e\u8d1f\u7684\u6574\u6570\u3002\u5b83\u4eec\u6bcf\u4f4d\u6570\u5b57\u90fd\u662f\u6309\u7167\u00a0\u9006\u5e8f\u00a0\u7684\u65b9\u5f0f\u5b58\u50a8\u7684\uff0c\u5e76\u4e14\u6bcf\u4e2a\u8282\u70b9\u53ea\u80fd\u5b58\u50a8\u00a0\u4e00\u4f4d\u00a0\u6570\u5b57\u3002\n\n\u8bf7\u4f60\u5c06\u4e24\u4e2a\u6570\u76f8\u52a0\uff0c\u5e76\u4ee5\u76f8\u540c\u5f62\u5f0f\u8fd4\u56de\u4e00\u4e2a\u8868\u793a\u548c\u7684\u94fe\u8868\u3002\n\n\u4f60\u53ef\u4ee5\u5047\u8bbe\u9664\u4e86\u6570\u5b57 0 \u4e4b\u5916\uff0c\u8fd9\u4e24\u4e2a\u6570\u90fd\u4e0d\u4f1a\u4ee5 0\u00a0\u5f00\u5934\u3002\n\u8f93\u5165\uff1al1 = [2,4,3], l2 = [5,6,4]\n\u8f93\u51fa\uff1a[7,0,8]\n\u89e3\u91ca\uff1a342 + 465 = 807.\n\n\u6765\u6e90\uff1a\u529b\u6263\uff08LeetCode\uff09\n\u94fe\u63a5\uff1ahttps://leetcode-cn.com/problems/add-two-numbers\n\n\u89e3\u9898\u601d\u8def\uff1a\n\u6bcf\u4e2a\u6570\u4f4d\u90fd\u662f\u9006\u5e8f\u7684\uff0c\u6240\u4ee5\u53ef\u4ee5\u4ece\u5934\u904d\u5386\u4e24\u4e2a\u94fe\u8868\uff0c\u628a\u4e24\u4e2a\u94fe\u8868\u7684\u503c\u76f8\u52a0\n\"\"\"\n\n# Definition for singly-linked list.\n\n\nclass ListNode(object):\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n\nclass Solution(object):\n def addTwoNumbers(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n p1 = l1\n p2 = l2\n res_Node = ListNode()\n head_res = res_Node\n temp = 0\n while p1 or p2 or temp:\n if p1 and not p2:\n res_val = p1.val + temp\n elif not p1 and p2:\n res_val = p2.val + temp\n elif p1 and p2:\n res_val = p1.val + p2.val + temp\n elif not p1 and not p2 and temp:\n res_val = temp\n else:\n break\n temp = 0\n\n if res_val < 10:\n res = ListNode(res_val)\n else:\n res = ListNode(res_val % 10)\n temp = res_val // 10\n head_res.next = res\n head_res = head_res.next\n\n if p1 and p1.next:\n p1 = p1.next\n else:\n p1 = None\n\n if p2 and p2.next:\n p2 = p2.next\n else:\n p2 = None\n res = res_Node.next\n\n return res\n\n\nif __name__ == \"__main__\":\n s = Solution()\n l1 = [9, 9, 9, 9, 9, 9, 9]\n l2 = [9, 9, 9, 9]\n l1_node = ListNode(l1[0])\n p1 = l1_node\n l2_node = ListNode(l2[0])\n p2 = l2_node\n for i in range(1, len(l1)):\n p1.next = ListNode(l1[i])\n p1 = p1.next\n for i in range(1, len(l2)):\n p2.next = ListNode(l2[i])\n p2 = p2.next\n s.addTwoNumbers(l1_node, l2_node)\n"} {"blob_id": "9ef498ac5e042ece5b28263f5490c39fb0bd3aed", "repo_name": "August-us/exam", "path": "/leetcode/\u53cc\u5468\u8d5b/5457. \u548c\u4e3a\u5947\u6570\u7684\u5b50\u6570\u7ec4\u6570\u76ee.py", "length_bytes": 1576, "score": 3.515625, "int_score": 4, "content": "from typing import List\nfrom math import comb\n\n'''\n\u7ed9\u4f60\u4e00\u4e2a\u6574\u6570\u6570\u7ec4\u00a0arr\u00a0\u3002\u8bf7\u4f60\u8fd4\u56de\u548c\u4e3a \u5947\u6570\u00a0\u7684\u5b50\u6570\u7ec4\u6570\u76ee\u3002\n\n\u7531\u4e8e\u7b54\u6848\u53ef\u80fd\u4f1a\u5f88\u5927\uff0c\u8bf7\u4f60\u5c06\u7ed3\u679c\u5bf9\u00a010^9 + 7\u00a0\u53d6\u4f59\u540e\u8fd4\u56de\u3002\n\n\u00a0\n\n\u793a\u4f8b 1\uff1a\n\n\u8f93\u5165\uff1aarr = [1,3,5]\n\u8f93\u51fa\uff1a4\n\u89e3\u91ca\uff1a\u6240\u6709\u7684\u5b50\u6570\u7ec4\u4e3a [[1],[1,3],[1,3,5],[3],[3,5],[5]] \u3002\n\u6240\u6709\u5b50\u6570\u7ec4\u7684\u548c\u4e3a [1,4,9,3,8,5].\n\u5947\u6570\u548c\u5305\u62ec [1,9,3,5] \uff0c\u6240\u4ee5\u7b54\u6848\u4e3a 4 \u3002\n\u793a\u4f8b 2 \uff1a\n\n\u8f93\u5165\uff1aarr = [2,4,6]\n\u8f93\u51fa\uff1a0\n\u89e3\u91ca\uff1a\u6240\u6709\u5b50\u6570\u7ec4\u4e3a [[2],[2,4],[2,4,6],[4],[4,6],[6]] \u3002\n\u6240\u6709\u5b50\u6570\u7ec4\u548c\u4e3a [2,6,12,4,10,6] \u3002\n\u6240\u6709\u5b50\u6570\u7ec4\u548c\u90fd\u662f\u5076\u6570\uff0c\u6240\u4ee5\u7b54\u6848\u4e3a 0 \u3002\n\u793a\u4f8b 3\uff1a\n\n\u8f93\u5165\uff1aarr = [1,2,3,4,5,6,7]\n\u8f93\u51fa\uff1a16\n\u793a\u4f8b 4\uff1a\n\n\u8f93\u5165\uff1aarr = [100,100,99,99]\n\u8f93\u51fa\uff1a4\n\u793a\u4f8b 5\uff1a\n\n\u8f93\u5165\uff1aarr = [7]\n\u8f93\u51fa\uff1a1\n'''\nclass Solution:\n def numOfSubarrays(self, arr: List[int]) -> int:\n even, odd = 0, 0\n mod = int(1E9 + 7)\n for i in arr:\n if i & 1:\n odd += 1\n else:\n even += 1\n oddComb = 0\n evenComb = 1 << odd\n for i in range(1, odd + 1, 2):\n oddComb = int(oddComb + comb(odd, i)) % mod\n\n return oddComb * evenComb % mod\n\n def numOfSubarrays(self, arr: List[int]) -> int:\n res, even, odd = 0, 0, 0\n mod = int(1E9 + 7)\n for i in arr:\n even = (even + 1) % mod\n if i & 1:\n even, odd = odd, even\n res = (res + odd) % mod\n return res\n\n\nprint(Solution().numOfSubarrays([100, 100, 99, 99]))\nprint(int(10E9 + 7))\n"} {"blob_id": "06a68c6dfa85faffaca8219483e49793b0f4f30f", "repo_name": "ilkerkesen/euler", "path": "/source/026.py", "length_bytes": 805, "score": 3.625, "int_score": 4, "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\ndef get_recurring(num):\n numer = 1\n denom = num\n remainders = dict()\n \n i = 0\n while True:\n if denom > numer:\n numer *= 10\n while denom > numer:\n numer *= 10\n i += 1\n\n numer = numer % denom\n i += 1\n\n if remainders.has_key(numer):\n return i - remainders.get(numer)\n elif numer == 0:\n return -1\n\n remainders[numer] = i\n\n return i - remainders.get(numer)\n\n\ndef main():\n max_recurring = 0\n num = 0\n\n for i in range(11, 1001, 2):\n recurring = get_recurring(i)\n if recurring > max_recurring:\n num = i\n max_recurring = recurring\n print num\n\n\nif __name__ == \"__main__\":\n main()\n"} {"blob_id": "b8d37c7228f87d6f6107fd8c244964d527261632", "repo_name": "LSSTC-DSFP/LSSTC-DSFP-Sessions", "path": "/Sessions/Session10/Day5/model_selection/.totallynothiddensolutions/exponentialmodel.py", "length_bytes": 1833, "score": 3.734375, "int_score": 4, "content": "class ExponentialModel(Model):\n \"\"\"\n Simple exponential model for mis-centering.\n \"\"\"\n def __init__(self):\n # Define any hyperparameters for the a1 prior here.\n # E.g., for uniform, something like \"self.min_a1 = value\" and \"self.max_a1 = value\"\n # More sophisticatedly, you could make these values arguments of __init__.\n self.min_a1 = 0.0\n self.max_a1 = 1000.0\n # The next line finishes initialization by calling the parent class' __init__\n Model.__init__(self)\n \n def log_prior(self, a1):\n \"\"\"\n Evaluate the log prior PDF P(a1|H)\n \"\"\"\n if a1 <= self.min_a1 or a1 > self.max_a1:\n return -np.inf\n return -np.log(self.max_a1 - self.min_a1)\n\n def draw_samples_from_prior(self, N):\n \"\"\"\n Return N samples of a1 from the prior PDF P(a1|H)\n \"\"\"\n return st.uniform.rvs(loc=self.min_a1, scale=self.max_a1-self.min_a1, size=N)\n\n def log_likelihood(self, a1):\n \"\"\"\n Evaluate the log of the likelihood function L(a1) = P(y|a1,H)\n \"\"\"\n return np.sum(st.expon.logpdf(y, scale=a1))\n \n def sampling_distribution(self, yy, a1):\n \"\"\"\n Evaluate the sampling distribution P(yy|a,H) at a point in data space yy given parameter value a1\n We expect a vector input yy, and return the corresponding probabilities.\n \n Note: This is useful for making plots of \"the model\" overlaid on the histogram of the data\n \"\"\"\n return st.expon.pdf(yy, scale=a1)\n \n def generate_replica_dataset(self, a1):\n \"\"\"\n Draw a replica data set y_rep from the sampling distribution P(y_rep|a1,H).\n y_rep should have the same length as the true data set.\n \"\"\"\n return st.expon.rvs(size=len(y), scale=a1)\n"} {"blob_id": "890bf39517fdf0d258b83321415fb5c7d8fe75b0", "repo_name": "16030IT028/Daily_coding_challenge", "path": "/InterviewBit/007_find_duplicate_in_array.py", "length_bytes": 783, "score": 3.625, "int_score": 4, "content": "\"\"\"\nhttps://www.interviewbit.com/problems/find-duplicate-in-array/\n\nFind Duplicate in Array\nAsked in: \nAmazon\nVMWare\nRiverbed\n\nGiven a read only array of n + 1 integers between 1 and n, find one number that repeats in linear time using less than O(n) space and traversing the stream sequentially O(1) times.\n\nSample Input:\n\n[3 4 1 4 1]\nSample Output:\n\n1\nIf there are multiple possible answers ( like in the sample case above ), output any one.\n\nIf there is no duplicate, output -1\"\"\"\n\nclass Solution:\n # @param A : tuple of integers\n # @return an integer\n def repeatedNumber(self, A):\n temp = [0] * (max(A)+1)\n for i in A:\n temp[i] += 1\n \n for j in range(len(A)):\n if temp[j] > 1:\n return j\n return -1"} {"blob_id": "c29a14460e0ccd435819c088a60c7a4bb336b3aa", "repo_name": "Soares/graveyard", "path": "/django-utilities/utilities/decorators.py", "length_bytes": 4133, "score": 3.6875, "int_score": 4, "content": "from functools import update_wrapper, partial\n\ndef with_fn(decorator):\n \"\"\"\n Allows a decorator to take mode arguments.\n The first argument is the function to decorate, which defaults to None.\n If the decorator is called without the function, it partially evaluates\n itself with the keyword arguments and waits for the function to decorate.\n Check it out:\n\n >>> @with_fn\n ... def test(fn, name='Just'):\n ... return name\n ...\n >>> @test\n ... def a(): return\n ...\n >>> @test(name='another')\n ... def b(): return\n ...\n >>> @test(name='python hacker')\n ... def c(): return\n ...\n >>> ' '.join((a, b, c))\n 'Just another python hacker'\n \"\"\"\n def real_decorator(fn=None, *args, **kwargs):\n if fn is None:\n return partial(real_decorator, *args, **kwargs)\n return decorator(fn, *args, **kwargs)\n update_wrapper(real_decorator, decorator)\n return real_decorator\n\n\n@with_fn\ndef cached_on_one(fn=None, cache_name=None):\n \"\"\"\n Use on a property or classmethod. The function will only ever be called\n once. The first time the property is called, the result will be saved.\n The saved value will be used from then on.\n\n The value will be stored in the attribute on the first parameter\n (convetionally 'self' for properties, 'cls' for classmethods) named by\n @cache_name, which defaults to an underscore and the name of the function.\n\n If cache_name is given and fn is not (i.e. you decorate with\n \"cache_on_one(cache_name='name')\" then this function will wait patiently\n for something to decorate.\n\n >>> class A(object):\n ... @cached_on_one\n ... def difficult(self):\n ... print 'doing difficult work...'\n ... return 1\n ...\n >>> a = A()\n >>> a.difficult()\n doing difficult work...\n 1\n >>> a.difficult()\n 1\n >>> a._difficult\n 1\n >>> class A(object):\n ... @cached_on_one(cache_name='a')\n ... def difficult(self):\n ... print 'doing difficult work...'\n ... return 1\n ...\n >>> a = A()\n >>> a.difficult()\n doing difficult work...\n 1\n >>> a.difficult()\n 1\n >>> a.a\n 1\n \"\"\"\n cache_name = cache_name or '_%s' % fn.__name__\n def realfn(one):\n if not hasattr(one, cache_name):\n setattr(one, cache_name, fn(one))\n return getattr(one, cache_name)\n update_wrapper(realfn, fn)\n return realfn\n\n\n@with_fn\ndef cached_property(fn=None, cache_name=None):\n \"\"\"\n Just like cached_on_one, but applies 'property' to the resulting function.\n \"\"\"\n return property(cached_on_one(fn, cache_name))\n\n\n@with_fn\ndef cached_classmethod(fn=None, cache_name=None):\n \"\"\"\n Just like cached_on_one, but applies 'classmethod' to the resulting function.\n \"\"\"\n return classmethod(cached_on_one(fn, cache_name))\n\n\n@with_fn\ndef decorator(doubledec=None, after=()):\n \"\"\"\n Turns a function of (fn, *args, **kwargs) into a decorator that\n decorates function, waits for *args and **kwargs, and then applies\n the decorator.\n\n Use this when you have a decorator that does no preparation but merely\n creates an inner funtion and immediately returns it.\n\n @after is a list of decorators that allows you to preform modifications on\n the decorated function once instead of each time it is called, which would\n otherwise be impossible.\n\n >>> @decorator\n ... def add_one_to_first_arg(fn, a):\n ... return fn(a+1)\n ...\n >>> @add_one_to_first_arg\n ... def addone(x):\n ... return x\n ...\n >>> addone(2)\n 3\n\n And here's how the after thing works:\n\n >>> @decorator(after=[add_one_to_first_arg])\n ... def add_two_to_first_arg(fn, a):\n ... return fn(a+1)\n ...\n >>> @add_two_to_first_arg\n ... def addtwo(x):\n ... return x\n ...\n >>> addtwo(2)\n 4\n \"\"\"\n def real_decorator(fn):\n fn = reduce(lambda fn, dec: dec(fn), after, fn)\n return lambda *args, **kwargs: doubledec(fn, *args, **kwargs)\n update_wrapper(real_decorator, doubledec)\n return real_decorator\n"} {"blob_id": "9d4ddaea82c5213d1825f5291299c09cc55505f2", "repo_name": "prabhatcodes/Python-Problems", "path": "/Leetcode/3sum-closest.py", "length_bytes": 1341, "score": 3.8125, "int_score": 4, "content": "# Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.\n#\n#\n#\n# Example 1:\n#\n# Input: nums = [-1,2,1,-4], target = 1\n# Output: 2\n# Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).\n#\n#\n# Constraints:\n#\n# 3 <= nums.length <= 10^3\n# -10^3 <= nums[i] <= 10^3\n# -10^4 <= target <= 10^4\nclass Solution:\n def threeSumClosest(self, nums: List[int], target: int) -> int:\n nums.sort()\n n = len(nums)\n\n res = nums[0] + nums[1] + nums[2]\n mindiff = abs(res - target)\n\n for i in range(0, n - 2):\n\n left = i + 1\n right = n - 1\n\n while left < right:\n\n temp = nums[i] + nums[left] + nums[right]\n diff = abs(temp - target)\n\n if temp == target:\n return temp\n\n elif temp > target:\n if diff < mindiff:\n res = temp\n mindiff = diff\n right -= 1\n\n else:\n if diff < mindiff:\n res = temp\n mindiff = diff\n left += 1\n\n return res\n"} {"blob_id": "8b114f902788b683bf3fdfaaba48ad79cb03934a", "repo_name": "rarch/codeeval", "path": "/med/decode.py", "length_bytes": 933, "score": 3.96875, "int_score": 4, "content": "#!/usr/bin/env python\n\nimport sys\n\n# from string import uppercase as uppers\n# encoding = dict([(c,str(i+1)) for i,c in enumerate(uppers)])\n\ndef countDecodings(myStr):\n # only length 1 or 0, so theres only one option\n if len(myStr) == 1 or len(myStr) == 0: return 1\n count = 0 # no measured options\n numChars = 1\n\n while True:\n chars = myStr[0:numChars]\n # if run out of chars or val exceeds 26, then fails\n if len(chars)!=numChars or int(chars)>26:break\n # if it works then recurse on subsequent letters\n count = count + countDecodings(myStr[numChars:])\n numChars = numChars + 1 # try adding a character\n return count\n\ntest_cases = open(sys.argv[1], 'r')\nfor test in test_cases:\n # ignore test if it is an empty line\n if not test.rstrip(): continue\n # 'test' represents the test case, do something with it\n print countDecodings(test.strip())\n\ntest_cases.close()"} {"blob_id": "f89e8588c6aaaef5d480a613feab190690268e25", "repo_name": "MitsurugiMeiya/Leetcoding", "path": "/leetcode/Array/118. \u5e15\u65af\u5361\u4e09\u89d2.py", "length_bytes": 954, "score": 3.59375, "int_score": 4, "content": "\"\"\"\n\u6bd4\u5982\u8bf4\uff0c\u7ed9\u4f60\u7684\u6570\u5b57\u662f 5\uff0c\u4f60\u8981\u8fd4\u56de\u5e15\u65af\u5361\u4e09\u89d2\u5f62\u7684\u524d 5 \u884c\u3002\n\n [1],\n [1,1],\n [1,2,1],\n [1,3,3,1],\n [1,4,6,4,1]\n\"\"\"\nclass Solution(object):\n def generate(self, numRows):\n \"\"\"\n :type numRows: int\n :rtype: List[List[int]]\n \"\"\"\n\n if not numRows or numRows == 0:\n return []\n\n res = []\n\n\n for i in range(numRows):\n # i\u662f\u6bcf\u4e00\u5c42\u7684\u4e2a\u6570\uff0c\u56e0\u4e3ai\u662f\u4ece0 ~ numrow-1, \u6240\u4ee5\u5728\u4e0b\u9762\u8981\u8fdb\u884c\u8bbe\u7f6e\n temp = [1 for _ in range(i + 1)]\n\n # j\u662f\u64cd\u4f5c\u7684\u5f53\u524d\u5143\u7d20\n # j \u5e94\u8be5\u4ece [1, jjjj, 1] \u7b2c\u4e00\u4e2a\u6570\u5b57\uff0c\u548c\u6700\u540e\u4e00\u4e2a\u6570\u5b57\u4e2d\u95f4\u64cd\u4f5c\n for j in range(1, len(temp) - 1):\n temp[j] = res[i - 1][j - 1] + res[i - 1][j]\n\n res.append(temp)\n\n return res\n\n\"\"\"\nhttps://algocasts.io/episodes/jwmBr5m8\nTime: O(n^2), Space: O(1)\n\u8fd9\u9898\u4e3b\u8981\u662f\u8fb9\u8fb9\u89d2\u89d2\u7684\u5730\u65b9\u6bd4\u8f83\u591a\n\"\"\""} {"blob_id": "efd2f12aa8c7ab9bc45d150e747852c70010529f", "repo_name": "dcragusa/LeetCode", "path": "/1-99/70-79/70.py", "length_bytes": 2026, "score": 4.28125, "int_score": 4, "content": "\"\"\"\nYou are climbing a staircase with n steps. Each time you can either climb 1 or 2 steps.\nIn how many distinct ways can you climb to the top?\nNote: Given n will be a positive integer.\n\nExample 1:\nInput: 2, Output: 2\nExplanation: There are two ways to climb to the top.\n1. 1 step + 1 step\n2. 2 steps\n\nExample 2:\nInput: 3, Output: 3\nExplanation: There are three ways to climb to the top.\n1. 1 step + 1 step + 1 step\n2. 1 step + 2 steps\n3. 2 steps + 1 step\n\"\"\"\n\n\"\"\"\nWe can either set up the base cases for 1 and 2 steps, then recur downwards, adding and memoizing as we go.\nAlternatively, we can realise that this is the number of unique permutations of a multiset of varying quantities \nof 1s and 2s. For example, for n=6 we must find the unique permutations of the multisets {1, 1, 1, 1, 1, 1}, \n{2, 1, 1, 1, 1}, {2, 2, 1, 1}, and {2, 2, 2}. The number of unique permutations of a multiset is, as we examined in \nproblem 62, the multinomial coefficient (n_a + n_b + ... )! / n_a! * n_b! * ... Therefore we just have to calculate \nthe multinomial coefficients of the multisets with the number of 2s varying from 0 to n // 2.\n\"\"\"\n\nfrom math import factorial\nfrom functools import lru_cache\n\n\n@lru_cache()\ndef climb_stairs_slow(n):\n if n == 1:\n return 1\n elif n == 2:\n return 2\n else:\n return climb_stairs_slow(n-1) + climb_stairs_slow(n-2)\n\n\ndef climb_stairs_fast(n):\n combinations = 1\n twos = 1\n while twos * 2 <= n:\n ones = n - 2*twos\n combinations += factorial(twos + ones) // (factorial(twos) * factorial(ones))\n twos += 1\n return combinations\n\n\nassert climb_stairs_slow(2) == climb_stairs_fast(2) == 2\nassert climb_stairs_slow(3) == climb_stairs_fast(3) == 3\nassert climb_stairs_slow(4) == climb_stairs_fast(4) == 5\nassert climb_stairs_slow(5) == climb_stairs_fast(5) == 8\nassert climb_stairs_slow(6) == climb_stairs_fast(6) == 13\nassert climb_stairs_slow(10) == climb_stairs_fast(10) == 89\nassert climb_stairs_slow(38) == climb_stairs_fast(38) == 63245986\n"} {"blob_id": "2cc16a80aad9d97e83c50a2b543995492f9c3b85", "repo_name": "dhermes/project-euler", "path": "/python/complete/no009.py", "length_bytes": 555, "score": 3.859375, "int_score": 4, "content": "#!/usr/bin/env python\n\n# There exists exactly one Pythagorean triplet for which\n# a + b + c = 1000. Find the product abc.\n\nimport operator\n\nfrom python.decorators import euler_timer\n\n\ndef first_triplet(total):\n for a in range(1, total - 1):\n for b in range(1, total - a):\n c = total - a - b\n if a ** 2 + b ** 2 == c ** 2:\n return [a, b, c]\n\n return []\n\n\ndef main(verbose=False):\n return reduce(operator.mul, first_triplet(1000))\n\nif __name__ == '__main__':\n print euler_timer(9)(main)(verbose=True)\n"} {"blob_id": "8a7a4d5be8010b2198b3fc212d2660a98edfb977", "repo_name": "evanrushton/project-euler", "path": "/primeFactorGraph.py", "length_bytes": 6255, "score": 3.796875, "int_score": 4, "content": "from primeSieve import *\n# import math\nimport random\nimport time\nimport matplotlib.pyplot as plt\nimport numpy as np\n# GLOBAL VARS\nprimes = []\ninteger = 0\n# Arrays to store (int, time) pairs for each algorithm\nbrute_div = []\nbrute_no_div = []\nrecurse_set_div = []\nrecurse_set_no_div = []\nrecurse_list_div = []\nrecurse_list_no_div = []\n\n# Input: integer n\n# Process: for each digit: Add last digit and divide by 10\n# Output: integer sum\ndef sumOfDigits(n):\n result = 0 # initialize sum\n while n:\n result += n % 10 # add each digit\n n = n / 10 # shorten by one digit\n return result\n \n# Input: integer n\n# Process: for each enumerated digit: mod2(index): odds: add; or: evens: subtract\n# Output: alternating integer sum (Odd digits - Even digits)\ndef alternatingSumOfDigits(n):\n result = 0\n st = str(n)\n for i in xrange(len(st)):\n dg = int(st[i])\n if dg % 2 == 1:\n result += dg\n else:\n result -= dg\n return result\n \n# Input: integer n\n# Process: Check if divisible by 2, 3, 5, 7, 11, 13\n# Output: array [ result, divisor ] \ndef checkDivisibility(n):\n unit_digit = n % 10 # get last digit = unit_digit\n if unit_digit % 2 == 0: return [n / 2, 2] # 2: check unit_digit % 2 == 0\n if unit_digit % 5 == 0: return [n / 5, 5] # 5: check unit_digit % 5 == 0 \n ch_sum = sumOfDigits(n) # get char sum = ch_sum\n if ch_sum % 3 == 0: return [n / 3, 3] # 3: check ch_sum % 3 == 0\n rest_of_digits = n / 10 # get rest_of_digits = n / 10 \n if abs(2 * unit_digit - rest_of_digits) % 7 == 0: return [n / 7, 7] # 7\n if (4 * unit_digit + rest_of_digits) % 13 == 0: return [n / 13, 13] # 13\n if alternatingSumOfDigits(n) % 11 == 0: return [n / 11, 11] # 11\n return [n, 0] # Not divisible by 2, 3, 5, 7, 13, or 11\n\n# 1 Create list of prime factors, using divisibility rules\ndef primeFactors_Divis(num):\n factors = []\n # Include divisibility rules\n divisible = checkDivisibility(num)\n while divisible[1]: \n factors.append(divisible[1])\n num = divisible[0]\n divisible = checkDivisibility(num)\n # Check for other prime factors \n for prime in primes:\n while num % prime == 0:\n factors.append(prime)\n num = num / prime\n if isPrime(num):\n factors.append(num)\n return factors\n\n# 2 Create list of prime factors, without using divisibility rules\ndef primeFactors_No_Divis(num):\n factors = []\n # Check for prime factors \n for prime in primes:\n while num % prime == 0:\n factors.append(prime)\n num = num / prime\n if isPrime(num):\n factors.append(num)\n return factors\n\n# 3 Return list of prime factors with repeats - use divisibility\ndef factorList_Divis(p, lst, n): # default p is 2, lst is [] \n # Include divisibility rules\n divisible = checkDivisibility(n)\n while divisible[1]: \n lst.append(divisible[1])\n n = divisible[0]\n divisible = checkDivisibility(n)\n # Base Case: n is prime - add to list and return list\n if isPrime(n) or n == 1:\n if n > 1: lst.append(n)\n return lst\n # Recursively check for the next prime\n else:\n for prime in primes: #primeSieve(p, int(round(n ** 0.5) + 1)):\n if n % prime == 0:\n lst.append(prime)\n p = prime\n return factorList_Divis(p, lst, n / prime)\n\n# 4 Return list of prime factors with repeats, without divisibilty rules\ndef factorList_No_Divis(p, lst, n): # default p is 2, lst is [] \n # Base Case: n is prime - add to list and return list\n if isPrime(n) or n == 1:\n if n > 1: lst.append(n)\n return lst\n # Recursively check for the next prime\n else:\n for prime in primes: #primeSieve(p, int(round(n ** 0.5) + 1)):\n if n % prime == 0:\n lst.append(prime)\n p = prime\n return factorList_No_Divis(p, lst, n / prime)\n\n# 5 Return list of prime factors without repeats, with divisibility rules\ndef factorSet_Divis(p, st, n): # default p is 2, st is set()\n # Include divisibility rules\n divisible = checkDivisibility(n)\n while divisible[1]: \n st.add(divisible[1])\n n = divisible[0]\n divisible = checkDivisibility(n)\n # Base Case: n is prime - add to list and return list\n if isPrime(n):\n st.add(n)\n return st\n # Recursively check for the next prime\n else:\n for prime in primes: #primeSieve(p, int(round(n ** 0.5) + 1)):\n if n % prime == 0:\n st.add(prime)\n p = prime\n return factorSet_Divis(p, st, n / prime)\n\n# 6 Return list of prime factors without repeats, without divisibility rules\ndef factorSet_No_Divis(p, st, n): # default p is 2, st is set()\n # Base Case 1: n is prime - add to list and return list\n if isPrime(n) or n == 1:\n if n > 1: st.add(n)\n return st\n # Recursively check for the next prime\n else:\n for prime in primes: #primeSieve(p, int(round(n ** 0.5) + 1)):\n if n % prime == 0:\n st.add(prime)\n p = prime\n return factorSet_No_Divis(p, st, n / prime)\n\n # Test\nfor i in range(200):\n integer = random.randint(4000, 50000000)\n lim = int(math.sqrt(integer))\n primes = primeSieve(2, lim + 1)\n t1 = time.time()\n algo1 = primeFactors_Divis(integer)\n t2 = time.time()\n brute_div.append([integer, t2 - t1])\n algo2 = primeFactors_No_Divis(integer)\n t3 = time.time()\n brute_no_div.append([integer, t3 - t2])\n algo3 = factorList_Divis(2, [], integer)\n t4 = time.time()\n recurse_list_div.append([integer, t4 - t3])\n algo4 = factorList_No_Divis(2, [], integer)\n t5 = time.time()\n recurse_list_no_div.append([integer, t5 - t4])\n algo5 = factorSet_Divis(2, set(), integer)\n t6 = time.time()\n recurse_set_div.append([integer, t6 - t5]) \n algo6 = factorSet_No_Divis(2, set(), integer)\n t7 = time.time()\n recurse_set_no_div.append([integer, t7 - t6]) \n\n print 'Factors of %d \\n' % (integer), algo1, algo2, algo3, algo4, algo5, algo6\n plt.plot(brute_div[i][0], brute_div[i][1], 'r+', brute_no_div[i][0], brute_no_div[i][1], 'rs', recurse_list_div[i][0], recurse_list_div[i][1], 'g+', recurse_list_no_div[i][0], recurse_list_no_div[i][1], 'gs', recurse_set_div[i][0], recurse_set_div[i][1], 'b+', recurse_set_no_div[i][0], recurse_set_no_div[i][1], 'bs')\n # print brute_div, '\\n', brute_no_div, '\\n', recurse_set_div, '\\n', recurse_set_no_div, '\\n', recurse_list_div, '\\n', recurse_list_no_div\n# red dashes, blue squares and green triangles\n\nplt.show()\n"} {"blob_id": "d332075dfa33c7fe222c8d7fcceb3f8223b5d1cf", "repo_name": "dsbowen/smoother", "path": "/smoother/smoother.py", "length_bytes": 2777, "score": 3.578125, "int_score": 4, "content": "\"\"\"# Smoother\"\"\"\n\nfrom .distribution import Distribution\n\nimport numpy as np\nfrom scipy.stats import entropy\nfrom scipy.optimize import Bounds, LinearConstraint, minimize\n\nimport json\nimport math\nfrom random import random\n\nclass Smoother(Distribution):\n \"\"\"\n The smoother computes a distribution by maximizing an objective function\n (i.e. a smoothness function) given constraints.\n\n Attributes\n ----------\n x : np.array\n A linearly spaced (`self.num`,) array of points between the lower and \n upper bounds of the distribution.\n\n f_x : np.array\n The probability density function of `self.x`.\n\n F_x : np.array\n The cumulative distribution function of `self.x`.\n \"\"\" \n def fit(\n self, lb, ub, constraints, \n objective=lambda self: self.entropy(), num=50\n ):\n \"\"\"\n Parameters\n ----------\n lb : scalar\n Lower bound of the distribution.\n\n ub : scalar\n Upper bound of the distribution.\n\n constraints : list of callables\n Constraints take in a `Smoother` and return a float. Lower values\n indicate that the constraints are satisfied.\n\n objective : callable, default=lambda self: self.entropy()\n The objective or smoothing function. The objective function takes \n a `Smoother` and returns a float. This objective function is\n maximized subject to constraints. By default, it maximizes \n entropy.\n\n num : int, default=50\n Number of points on the distribution used for approximation.\n\n Returns\n -------\n self\n \"\"\"\n self.x = np.linspace(lb, ub, num=num)\n self._f_x = np.ones(num) / (ub-lb)\n self._constraints = constraints\n self._objective = objective\n bounds = Bounds([0]*num, [np.inf]*num)\n integral_cons = LinearConstraint(1/num * np.ones((1, num)), [1], [1])\n minimize(\n self._loss, \n self._f_x, \n constraints=[integral_cons], \n bounds=bounds,\n options={'disp': False}\n )\n del self._constraints, self._objective\n return self\n\n def _loss(self, f_x=None):\n \"\"\"\n Parameters\n ----------\n f_x : np.array or None, default=None\n Resets `self._f_x`; users should avoid passing this parameter.\n\n Returns\n -------\n loss : float\n Loss is the negative of the objective function plus loss from\n constraints.\n \"\"\"\n self._f_x = self._f_x if f_x is None else f_x\n constraint_loss = sum([constraint(self) for constraint in self._constraints])\n return -self._objective(self) + constraint_loss"} {"blob_id": "958e8293912a6df866ea3b8821948db8dc3540e4", "repo_name": "Kevin-Rush/CodingInterviewPrep", "path": "/Python/TreeORBST.py", "length_bytes": 712, "score": 4.25, "int_score": 4, "content": "'''\n6. Determine if a binary tree is a binary search tree\nGiven a Binary Tree, figure out whether it\u2019s a Binary Search Tree. In a binary search tree, each \nnode\u2019s key value is smaller than the key value of all nodes in the right subtree, and is greater than \nthe key values of all nodes in the left subtree. Below is an example of a binary tree that is a valid BST.\n'''\n\ndef is_bst_rec(root, min_val, max_val):\n if root == None:\n return True\n\n if root.data < min_val or root.data > max_val:\n return False\n \n return is_bst_rec(root.left, min_val, root.data) and is_bst_rec (root.right, root.data, max_val)\n\ndef is_bst(root):\n return is_bst_rec(root, -sys.maxsize-1, sys.maxsize)\n\n#tested in browser"} {"blob_id": "7307922e06308c47ed202e52c9aa779a2a491160", "repo_name": "kazhirota7/Graph-based-wSTLNN", "path": "/wGSTLNN/wGSTLNN/DistanceCalc.py", "length_bytes": 455, "score": 3.53125, "int_score": 4, "content": "from math import sin, cos, sqrt, atan2, radians\n\n\ndef latLongDist(lat1, long1, lat2, long2):\n # approximate radius of earth in km\n R = 6373.0\n\n lat1 = radians(lat1)\n long1 = radians(long1)\n lat2 = radians(lat2)\n long2 = radians(long2)\n\n dlong = long2 - long1\n dlat = lat2 - lat1\n\n a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlong / 2)**2\n c = 2 * atan2(sqrt(a), sqrt(1 - a))\n\n distance = R * c\n\n return distance"} {"blob_id": "fc0fead013f280f0b09620d1fda34bcf5f67bcc2", "repo_name": "chenhuang/leetcode", "path": "/generateParenthesis.py", "length_bytes": 2303, "score": 4.0, "int_score": 4, "content": "#! /usr/bin/env python\n\n'''\nGenerate Parentheses \n\nGiven n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.\n\nFor example, given n = 3, a solution set is:\n\n\"((()))\", \"(()())\", \"(())()\", \"()(())\", \"()()()\"\n\nhttps://oj.leetcode.com/problems/generate-parentheses/\n'''\n\nclass Solution:\n # @param an integer\n # @return a list of string\n def generateParenthesis(self, n):\n self.output = []\n print self.generateParenthesisRec_2(0,0,n,\"\")\n #self.generateParenthesisRec_1(0,0,n,\"\")\n return self.output\n\n def generateParenthesisRec_1(self,left_num,right_num,total_num,string):\n if left_num == total_num and right_num == total_num:\n self.output.append(string)\n else:\n if left_num < total_num:\n self.generateParenthesisRec_1(left_num+1,right_num,total_num,string+\"(\")\n if right_num < left_num:\n self.generateParenthesisRec_1(left_num,right_num+1,total_num,string+\")\")\n\n def generateParenthesisRec(self,left_num,right_num,total_num,string):\n if left_num == total_num and right_num == total_num:\n self.output.append(string)\n else:\n for i in range(left_num+1, total_num+1):\n lefts = ''\n for j in range(i-left_num):\n lefts += '('\n self.generateParenthesisRec(i, right_num, total_num, string+lefts)\n for i in range(right_num+1, left_num+1):\n rights = ''\n for j in range(i-right_num):\n rights += ')'\n self.generateParenthesisRec(left_num,i,total_num,string+rights)\n \n def generateParenthesisRec_2(self, left_num, right_num, total_num, string):\n output = []\n if left_num == total_num and right_num == total_num:\n output.append(string)\n else:\n if left_num < total_num:\n output.extend(self.generateParenthesisRec_2(left_num+1,right_num,total_num, string+\"(\"))\n if left_num > right_num:\n output.extend(self.generateParenthesisRec_2(left_num,right_num+1,total_num,string+\")\"))\n\n return output\n\nif __name__ == \"__main__\":\n s = Solution()\n print s.generateParenthesis(3)\n \n"} {"blob_id": "3236f07ea6ae2d19f9fbaf3b219e9d6c64f1d9d8", "repo_name": "jtambe/Python", "path": "/PyFibonacci.py", "length_bytes": 956, "score": 4.21875, "int_score": 4, "content": "\n\n\n#fibonacci series using dynamic programming\n# O(n)\ndef fibonacci(length):\n\n #create array of length\n values = [0]*length\n values[0] = 0\n values[1] = 1\n for i in range(2,length):\n values[i] = values[i-1]+ values[i-2]\n print(values)\n\ndef fiboRecursive(n):\n if n == 0:\n return 0\n elif n == 1:\n return 1\n else:\n return fiboRecursive(n-1)+ fiboRecursive(n-2)\n\n\ndef fibonacciShort(n):\n # dual assignment\n a, b = 0, 1\n for i in range(n):\n # print horizontally\n # print(a, end = \" \")\n a, b = b, a+b\n return b\n\n# Generator style\ndef fibonacciGenrator(n):\n a,b = 0,1\n print(\"\")\n for i in range(n):\n yield a\n a,b = b, a+b\n\n\n\ndef main():\n #fibonacci(10)\n\n #print(fiboRecursive(9))\n\n print(fibonacciShort(8181))\n\n # for eachYieldResult in fibonacciGenrator(10):\n # print(eachYieldResult, end=\" \")\n\n\nif __name__ == '__main__':\n main()"} {"blob_id": "c3837390ad3e8119a5e24d0572aa5a28a94e3b85", "repo_name": "hs634/algorithms", "path": "/python/arrays/search_rotated_array.py", "length_bytes": 1213, "score": 3.65625, "int_score": 4, "content": "__author__ = 'harsh'\n\ndef bin_search(sequence, left, right, key):\n if not sequence:\n return -1\n if left >= right:\n return -1\n mid = left + (right - left)/2\n if sequence[mid] == key:\n return mid\n else:\n if sequence[left] < sequence[mid]:\n if sequence[left] <= key < sequence[mid]:\n return bin_search(sequence, left, mid, key)\n else:\n return bin_search(sequence, mid+1, right, key)\n else:\n if sequence[mid] < key <= sequence[right]:\n return bin_search(sequence, mid+1, right, key)\n else:\n return bin_search(sequence, left, mid, key)\n\n\ndef find_rotation_point(sequence):\n l, r = 0, len(sequence) - 1\n if not sequence:\n return -1\n while sequence[l] > sequence[r]:\n mid = l + ((r-l)/2)\n if sequence[mid] > sequence[r]:\n l = mid + 1\n else:\n r = mid\n return l\n\n\ndef main():\n sequence = [7,8,9,33, 1, 2]\n key = 5\n index = bin_search(sequence, 0, len(sequence)-1, key)\n print str(key) + \" found at \" + str(index)\n print \"rotation index found at \" + str(find_rotation_point(sequence))\n\nmain()"} {"blob_id": "0381026e5a58d2e5ee586c7917742850fb567382", "repo_name": "ws2823147532/algorithm008-class01", "path": "/Week_02/[111]\u4e8c\u53c9\u6811\u7684\u6700\u5c0f\u6df1\u5ea6.py", "length_bytes": 1415, "score": 3.875, "int_score": 4, "content": "# \u7ed9\u5b9a\u4e00\u4e2a\u4e8c\u53c9\u6811\uff0c\u627e\u51fa\u5176\u6700\u5927\u6df1\u5ea6\u3002\n#\n# \u4e8c\u53c9\u6811\u7684\u6df1\u5ea6\u4e3a\u6839\u8282\u70b9\u5230\u6700\u8fdc\u53f6\u5b50\u8282\u70b9\u7684\u6700\u957f\u8def\u5f84\u4e0a\u7684\u8282\u70b9\u6570\u3002\n#\n# \u8bf4\u660e: \u53f6\u5b50\u8282\u70b9\u662f\u6307\u6ca1\u6709\u5b50\u8282\u70b9\u7684\u8282\u70b9\u3002\n#\n# \u793a\u4f8b\uff1a\n# \u7ed9\u5b9a\u4e8c\u53c9\u6811 [3,9,20,null,null,15,7]\uff0c\n#\n# 3\n# / \\\n# 9 20\n# / \\\n# 15 7\n#\n# \u8fd4\u56de\u5b83\u7684\u6700\u5927\u6df1\u5ea6 3 \u3002\n# Related Topics \u6811 \u6df1\u5ea6\u4f18\u5148\u641c\u7d22\n\n\n# leetcode submit region begin(Prohibit modification and deletion)\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\nclass Solution:\n def maxDepth(self, root: TreeNode) -> int:\n \"\"\"\n BFS\u65b9\u5f0f\n \u6309\u7167\u5c42\u6b21\u904d\u5386\uff0c\u904d\u5386\u5b8c\u4e00\u5c42\uff0c\u6df1\u5ea6\u52a01\n :param root:\n :return:\n \"\"\"\n if not root: return 0\n depth = 1\n from queue import Queue\n queue = Queue()\n queue.put((1, root))\n while not queue.empty():\n depth, node = queue.get()\n if node.left:\n queue.put((depth + 1, node.left))\n if node.right:\n queue.put((depth + 1, node.right))\n return depth\n\n def maxDepth1(self, root: TreeNode) -> int:\n if not root: return 0\n return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1\n\n# leetcode submit region end(Prohibit modification and deletion)\n"} {"blob_id": "0b7d06e83d9a32417b0ef408ffcc340960bf268b", "repo_name": "onestarshang/leetcode", "path": "/convert-a-number-to-hexadecimal.py", "length_bytes": 1277, "score": 4.625, "int_score": 5, "content": "# coding: utf-8\n\n'''\nhttps://leetcode.com/problems/convert-a-number-to-hexadecimal/\n\nGiven an integer, write an algorithm to convert it to hexadecimal. For negative integer, two\u2019s complement method is used.\n\nNote:\n\nAll letters in hexadecimal (a-f) must be in lowercase.\nThe hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero character '0'; otherwise, the first character in the hexadecimal string will not be the zero character.\nThe given number is guaranteed to fit within the range of a 32-bit signed integer.\nYou must not use any method provided by the library which converts/formats the number to hex directly.\n\nExample 1:\nInput:\n26\nOutput:\n\"1a\"\n\nExample 2:\nInput:\n-1\nOutput:\n\"ffffffff\"\n'''\n\nclass Solution(object):\n def toHex(self, num):\n \"\"\"\n :type num: int\n :rtype: str\n \"\"\"\n if num == 0:\n return '0'\n if num < 0:\n num += 1 << 32\n digits = '0123456789abcdef'\n base = len(digits)\n r = ''\n while num:\n r = digits[num % base] + r\n num /= base\n return r\n\n\nif __name__ == '__main__':\n f = Solution().toHex\n assert f(0) == '0'\n assert f(26) == '1a'\n assert f(-1) == 'ffffffff'\n"} {"blob_id": "aa5483e124907b374410de77cff466226135528d", "repo_name": "detiuaveiro/cd2021-final-97880_100055", "path": "/slave.py", "length_bytes": 16058, "score": 3.53125, "int_score": 4, "content": "#Definitely not a botnet\nfrom const import *\nimport base64\nimport socket\nimport struct\nimport selectors\nimport time\nimport string\nimport pickle\nimport copy\nimport datetime\n\nBASE62 = string.ascii_lowercase+string.ascii_uppercase+string.digits\n\ndef encode(num, alphabet):\n \"\"\"Encode a positive number into Base X and return the string.1\n Arguments:\n - `num`: The number to encode\n - `alphabet`: The alphabet to use for encoding\n \"\"\"\n if num == 0:\n return alphabet[0]\n arr = []\n arr_append = arr.append # Extract bound-method for faster access.\n _divmod = divmod # Access to locals is faster.\n base = len(alphabet)\n while num:\n num, rem = _divmod(num, base)\n arr_append(alphabet[rem])\n arr.reverse()\n return ''.join(arr)\n\n\ndef decode(password, alphabet=BASE62):\n \"\"\"Decode a Base X encoded password into the number\n\n Arguments:\n - `password`: The encoded password\n - `alphabet`: The alphabet to use for decoding\n \"\"\"\n base = len(alphabet)\n strlen = len(password)\n num = 0\n\n idx = 0\n for char in password:\n power = (strlen - (idx + 1))\n num += alphabet.index(char) * (base ** power)\n idx += 1\n return num\n\n# Source: https://stackoverflow.com/questions/1119722/base-62-conversion\n# Why are we using this: encoding our passwords as base62 enables us to use an integer to refer to any of the possible combinations\n# of alphanumeric characters - this way, we do not need to generate all the possible passwords and store them in memory to then access\n# via array index, but just get a random int number (in a range of course, that hasnt been used by peers) and then decode it into a\n# password\n# ======================================================================================================================================================================================\n\n# UTILITY FUNCTIONS:\n\ndef getPWfromIDX(idx, size: int = PASSWORD_SIZE):\n #print(\"size:\",size)\n if 0 > idx or idx >= (62**size):\n print(\"Idx not in range!\")\n return \"a\"\n str = encode(idx, BASE62)\n if len(str) < size:\n diff = size - len(str)\n for i in range(diff):\n str = BASE62[0] + str\n return str\n\ndef overlaps(r1 : list, r2 : list):\n if r1[0] <= r2[1] and r1[1] >= r2[0]: return True\n else: return False\n\ndef mergeList(listt):\n '''Smoothes out the Verified array, removing duplicates and merging adjacent arrays'''\n listt.sort()\n changed = True\n while changed:\n changed = False\n for i in range(1,len(listt)):\n if overlaps(listt[i],listt[i-1]):\n maxR = max(listt[i][1],listt[i-1][1])\n newRange = [listt[i-1][0], maxR]\n del listt[i-1]\n del listt[i-1]\n listt.append(newRange)\n changed = True\n listt.sort()\n break\n elif listt[i-1][1]+1 == listt[i][0]:\n newRange = [listt[i-1][0], listt[i][1]]\n del listt[i-1]\n del listt[i-1]\n listt.append(newRange)\n changed = True\n listt.sort()\n break\n listt.sort()\n return listt\n\ndef invertRangeList(listt):\n listt = mergeList(listt)\n MAX = 62**PASSWORD_SIZE\n if len(listt) == 0: return [0, MAX]\n elif len(listt) == 1:\n if listt[0][0] == 0: return [[listt[0][1]+1, MAX]]\n elif listt[0][1] == MAX: return [[0, listt[0][0]-1]]\n else: return[[0,listt[0][0]-1],[listt[0][1]+1,MAX]]\n else:\n newlistt = []\n for i in range(len(listt)):\n if i == 0:\n if listt[i][0] == 0: continue\n else: newlistt.append([0, listt[i][0]-1])\n else:\n newlistt.append([listt[i-1][1]+1,listt[i][0]-1])\n if i == len(listt)-1: \n if not listt[i][1] == MAX:\n newlistt.append([listt[i][1]+1,MAX]) \n return newlistt\n\ndef compareAddr(myAddr : str, theirAddr : str):\n myFields = myAddr.split(\".\")\n theirFields = theirAddr.split(\".\")\n for i in range(4):\n myF = int(myFields[i])\n theirF = int(theirFields[i])\n if myF == theirF: continue\n elif myF > theirF: return 1\n else: return -1\n return 0 \n\ndef contains(r1 : list, r2 : list):\n if r1[0]<=r2[0] and r2[1]<=r1[1]:\n return True\n return False\n\ndef arraySum(rangeArray : list):\n rangeArray = mergeList(rangeArray)\n sum = 0\n for range in rangeArray:\n sum += range[1]-range[0]\n return sum\n\nclass zerg:\n def __init__(self, name: str = \"\"):\n\n # --Init Variables n stuff we'll need----\n self.sel = selectors.DefaultSelector()\n self.name = name\n self.found = False\n\n # --Things for communication with victim server (HTTP,TCP)---\n self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.HOST = \"172.17.0.2\" # \"host.docker.internal\"\n self.PORT = 8000\n\n # ---Things for communication with brood (Multicast via udp)--\n self.mCastSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n self.mCastSock.settimeout(0.2)\n self.MCAST_TTL = struct.pack('b', 1)\n self.MCAST_GRP ='224.3.29.71' # what we put here\n self.MCAST_PORT = 10000\n\n server_address = ('', 10000)\n self.mCastSock.bind(server_address)\n group = socket.inet_aton(self.MCAST_GRP)\n mreq = struct.pack('4sL', group, socket.INADDR_ANY)\n self.mCastSock.setsockopt(\n socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)\n self.mCastSock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 0)\n # Listen for socket activity\n self.sel.register(self.mCastSock, selectors.EVENT_READ, self.recvMCAST)\n\n self.range = [0,30*PASSWORD_SIZE-1]\n self.current = self.range[0]-1\n self.verified = []\n self.peers = {}\n\n self.latest_pws = list()\n self.lastTry=0\n self.connect()\n\n hostname = socket.gethostname()\n self.address = socket.gethostbyname(hostname)\n print(\"I AM:\",self.address)\n\n def isVerified(self, num : int):\n '''See if password has been tested before'''\n for i in range(len(self.verified)):\n if self.verified[i][0] >= num >= self.verified[i][1]: return True\n return False\n \n def isRangeVerified(self):\n '''See if range of passwords have been tested before'''\n for i in range(len(self.verified)):\n if contains(self.verified[i],self.range):\n return True\n return False\n\n def updateVerified(self):\n '''Smoothes out the Verified array, removing duplicates and merging adjacent arrays'''\n self.verified = mergeList(self.verified)\n\n def addToVerified(self, num):\n '''Insert a new num into verified - it'll be merged later'''\n self.verified.append([num, num])\n self.updateVerified() # merges the mess we've created\n\n def selectNewRange(self):\n # firstly, tries to find any space not occupied by another slave\n self.updateVerified()\n allOccupied = copy.deepcopy(self.verified)\n for peer in self.peers.keys():\n allOccupied.append(self.peers[peer][1])\n allOccupied = mergeList(allOccupied)\n if allOccupied[0][1]-allOccupied[0][0] != 62**PASSWORD_SIZE:\n # a space without an active slave exists! -> immediately occupies the biggest space like this\n invert = invertRangeList(allOccupied)\n betterIDX = -1\n betterRNG = 62**PASSWORD_SIZE+1\n for i in range(len(invert)):\n RNG = invert[i][1]-invert[i][0]\n if RNG < betterRNG:\n betterRNG = RNG\n betterIDX = i\n\n if betterRNG > 30*PASSWORD_SIZE:\n return [invert[betterIDX][0],invert[betterIDX][0]+30*PASSWORD_SIZE-1]\n else:\n return invert[betterIDX]\n else:\n # all spaces are occupied by slaves or already checked -> choses the peer with the biggest workload, and divides it\n betterPeer = -1\n betterRNG = 0\n for peer in self.peers.keys():\n RNG = self.peers[peer][1][1]-self.peers[peer][1][0]\n if RNG > betterRNG:\n betterRNG = RNG\n betterPeer = peer\n low = int((self.peers[betterPeer][1][1] - self.peers[betterPeer][1][0])/2)\n return [low,self.peers[betterPeer][1][1]]\n\n def sayImHere(self): \n '''Get a imhere message''' # General Kenobi\n msg = {\n 'command': 'imhere',\n 'verified': self.verified, # twitter famous\n 'range': self.range,\n }\n encodedMSG = pickle.dumps(msg)\n \n # Send the ImHere message to peers (via Multicast)\n self.mCastSock.setsockopt(\n socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, self.MCAST_TTL)\n self.mCastSock.sendto(encodedMSG, (self.MCAST_GRP, self.MCAST_PORT))\n\n def sayFoundPW(self):\n '''Get a foundpw message''' # Win\n msg = {\n 'command': 'foundpw',\n 'pw': self.pw\n }\n encodedMSG = pickle.dumps(msg)\n\n self.mCastSock.setsockopt(\n socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, self.MCAST_TTL)\n self.mCastSock.sendto(encodedMSG, (self.MCAST_GRP, self.MCAST_PORT))\n \n \n def sendMCAST(self, msg):\n '''Send a message to our peers'''\n self.mCastSock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, self.MCAST_TTL)\n self.mCastSock.sendto(msg, (self.MCAST_GRP, self.MCAST_PORT))\n while True:\n try:\n data, server = self.mcastSock.recvfrom(1024)\n except socket.timeout:\n break\n else:\n if server not in self.peers.keys(): # New peer, add them to our contact book\n self.peers[server]=[-1,[0,0]]\n\n\n def recvMCAST(self):\n '''Receive messages from our peers (and process them)'''\n try:\n data, server = self.mCastSock.recvfrom(1024)\n except socket.timeout:\n return\n else:\n recvMSG = pickle.loads(data) \n if server in self.peers:\n self.peers[server]=[time.time(),self.peers[server][1]] # last seen at: now\n else:\n self.peers[server]=[time.time(),[0,0]] # New peer\n if recvMSG['command']=='imhere':\n # Sort out stored ranges and verified pwds\n peerRange = recvMSG['range']\n self.peers[server][1] = peerRange\n peerVerified = recvMSG['verified']\n\n for range in peerVerified:\n self.verified.append(range)\n self.updateVerified()\n\n if overlaps(self.range,peerRange):\n #There's a range overlap!\n if compareAddr(self.address,server[0]) > 0:\n #I need to adjust my range if my ip is lower than the peer\n self.range = self.selectNewRange()\n self.current = self.range[0]-1\n else:\n pass\n else:\n pass\n elif recvMSG['command']=='foundpw':\n print(\"Password found:\",recvMSG[\"pw\"]+\"!\",\"Shutting down...\")\n print(\"# PASSWORDS TESTED:\", arraySum(self.verified))\n exit(0) # Shutting down...\n return\n\n def connect(self):\n \"\"\"Connect to chat server and setup stdin flags.\"\"\"\n self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.s.connect((self.HOST, self.PORT))\n\n def try_pw(self, pw: str):\n \"\"\"Creates the AuthHeader with the created pw\"\"\" \n ID = \"root\"\n\n authHead = ID+\":\"+pw\n authHeadB64 = base64.b64encode(authHead.encode()).decode()\n\n httpHeader = f'''GET / HTTP/1.1\\nHost: localhost\\nAuthorization: Basic {authHeadB64}\\r\\n\\r\\n''' \n\n msg = httpHeader\n self.send_msg(msg)\n\n def send_msg(self, msg):\n \"\"\"Sends ONE (1) message to VICTIM\"\"\" \n encoded_msg = str(msg).encode(\"utf-8\")\n self.s.send(encoded_msg)\n self.server_response()\n\n def victory(self):\n '''Receive the success.jpg picture'''\n picture_raw=b\"\"\n pic_part=b\"\"\n incoming_parts=b\"\"\n while True:\n while not b\"\\r\\n\" in incoming_parts:\n incoming_parts = incoming_parts+self.s.recv(1) # Byte a Byte enche a galinha o papo\n if incoming_parts == b\"\":\n #print(\"Picture received!\")\n with open(\"success.jpg\", \"wb\") as img:\n img.write(picture_raw)\n #print(\"BOOBA\",self.verified)\n print(\"# PASSWORDS TESTED:\", arraySum(self.verified))\n\n return\n size=incoming_parts.split(b\"\\r\\n\")[0] # Remove pesky chunked line separators\n size=int(size,16)\n incoming_parts = (self.s.recv(int(size)+2)) # +2 to account for the line separators\n incoming_parts=incoming_parts[:-2] # these are not the bytes you're looking for\n\n picture_raw=picture_raw+incoming_parts\n incoming_parts=b\"\"\n\n\n def server_response(self):\n \"\"\"Receives ONE (1) http response\"\"\"\n incoming = \"\"\n incoming_raw=b\"\"\n while not \"\\r\\n\\r\\n\" in incoming:\n incoming_parts = self.s.recv(500)\n incoming_raw=incoming_raw+incoming_parts\n incoming = incoming_raw.decode(\"ascii\")\n\n if '200' in incoming.split(\"\\r\\n\\r\\n\")[0]: # Success!\n self.found = True\n self.pw = getPWfromIDX(self.current, PASSWORD_SIZE)\n print(\"GOT IT!\\nwas it \"+self.pw+\"?\")\n self.sayFoundPW()\n self.victory() # Process the picture\n\n def loop(self):\n '''Main Loop'''\n while not self.found: \n if self.isRangeVerified(): # Range is overlapping\n self.range = self.selectNewRange()\n self.current = self.range[0]-1\n if time.time()>self.lastTry + COOLDOWN_TIME/1000: # If Cooldown Time has passed since last try\n #print(\"all your base are belong to us\") # nice ref :D\n #print(time.ctime(time.time()),\": MY RANGE =\",self.range)\n toTest = []\n full = False\n for i in range(MIN_TRIES): # get next MIN_TRIES passwords from ids\n self.current += 1\n if self.current > self.range[1]:\n full = True\n break\n if self.isVerified(self.current): continue\n self.try_pw(getPWfromIDX(self.current, PASSWORD_SIZE))\n #print(\"TRIED:\",self.current)\n self.addToVerified(self.current)\n if self.found:\n return getPWfromIDX(self.current, PASSWORD_SIZE)\n self.lastTry = time.time()\n self.sayImHere()\n if full:\n self.range = self.selectNewRange()\n self.current = self.range[0]-1\n pass\n for peer in self.peers.keys():\n if self.peers[peer][0] < time.time() - 5 and time.time() - 15!=0 :\n self.peers.pop(peer)\n break\n toDo = self.sel.select(0)\n for event, data in toDo:\n callback = event.data\n msg = callback()\n\nslave = zerg(\"Brood1\")\nslave.loop()\n"} {"blob_id": "09f365379157822059b2f26f9c418f10bfb4404b", "repo_name": "xvrlad/Python-Stuff", "path": "/A2.py", "length_bytes": 9598, "score": 3.59375, "int_score": 4, "content": "#q1\r\ndef highest_value_word(word1, word2, ordinal_position=1):\r\n index_position = ordinal_position - 1\r\n if word1 == word2:\r\n return 0\r\n elif index_position == len(word1) or index_position == len(word2):\r\n return ordinal_position if index_position == len(word1) else -ordinal_position\r\n elif ord(word1[index_position]) > ord(word2[index_position]):\r\n return -ordinal_position\r\n elif ord(word1[index_position]) < ord(word2[index_position]):\r\n return ordinal_position\r\n return highest_value_word(word1, word2, ordinal_position + 1)\r\n\r\n#q2\r\nclass UndoRedo:\r\n def __init__(self):\r\n self.__back = Stack()\r\n self.__forward = Stack()\r\n self.__current = None\r\n\r\n def get_prev(self):\r\n if self.__back.is_empty():\r\n return None\r\n self.__forward.push(self.__current)\r\n popped_element = self.__back.pop()\r\n self.__current = popped_element\r\n return popped_element\r\n\r\n def get_next(self):\r\n if self.__forward.is_empty():\r\n return None\r\n self.__back.push(self.__current)\r\n popped_element = self.__forward.pop()\r\n self.__current = popped_element\r\n return popped_element\r\n\r\n def add_item(self, data):\r\n self.__back.push(self.__current)\r\n self.__current = data\r\n self.__forward = Stack()\r\n\r\n#q3\r\ndef selection_order(items, interval):\r\n item_queue = Queue()\r\n for elements in items:\r\n item_queue.enqueue(elements)\r\n return_list = []\r\n dequeue_counter = 0\r\n while len(return_list) != len(items):\r\n dequeue_item = item_queue.dequeue()\r\n dequeue_counter += 1\r\n if dequeue_counter % interval == 0:\r\n return_list.append(dequeue_item)\r\n elif dequeue_counter % interval != 0:\r\n item_queue.enqueue(dequeue_item)\r\n return return_list\r\n\r\n#q4\r\nclass Node:\r\n\r\n def __init__(self, data, next=None):\r\n\r\n self.__data = data\r\n\r\n self.__next = next\r\n\r\n def get_data(self):\r\n\r\n return self.__data\r\n\r\n def get_next(self):\r\n\r\n return self.__next\r\n\r\n def set_data(self, new_data):\r\n\r\n self.__data = new_data\r\n\r\n def set_next(self, new_next):\r\n self.__next = new_next\r\n\r\n def __str__(self):\r\n\r\n return str(self.__data)\r\nclass QueueAsLinkedList:\r\n def __init__(self):\r\n self.__head = None\r\n self.__tail = None\r\n self.__count = 0\r\n def size(self):\r\n return self.__count\r\n def enqueue(self, item):\r\n if self.__head is None:\r\n self.__head = Node(item)\r\n elif self.__tail is None:\r\n self.__tail = Node(item)\r\n self.__head.set_next(self.__tail)\r\n else:\r\n self.__tail.set_next(Node(item))\r\n self.__tail = self.__tail.get_next()\r\n self.__count += 1\r\n def dequeue(self):\r\n if self.__head is None:\r\n return None\r\n current_head = self.__head.get_data()\r\n self.__head = self.__head.get_next()\r\n self.__count -= 1\r\n return current_head\r\n def peek(self):\r\n if self.__head is None:\r\n return None\r\n return self.__head.get_data()\r\n def is_empty(self):\r\n if self.__count == 0:\r\n return True\r\n return False\r\n\r\n#q5\r\ndef hash_string_weighted_folding(string_to_hash, modulus):\r\n sum = 0\r\n for character_index in range(len(string_to_hash)):\r\n sum += (ord(string_to_hash[character_index]) * (256 ** (character_index % 4)))\r\n return sum % modulus\r\n\r\n#q6\r\ndef max_value_length(tree):\r\n if tree is None:\r\n return 0\r\n return max(len(str(tree.get_data())), max_value_length(tree.get_left()),\r\n max_value_length(tree.get_right()))\r\n\r\nclass BinaryTree:\r\n def __init__(self, data, left=None, right=None):\r\n self.__data = data\r\n self.__left = left\r\n self.__right = right\r\n def insert_left(self, new_data):\r\n if self.__left == None:\r\n self.__left = BinaryTree(new_data)\r\n else:\r\n tree = BinaryTree(new_data, left=self.__left)\r\n self.__left = tree\r\n def insert_right(self, new_data):\r\n if self.__right == None:\r\n self.__right = BinaryTree(new_data)\r\n else:\r\n tree = BinaryTree(new_data, right=self.__right)\r\n self.__right = tree\r\n def get_left(self):\r\n return self.__left\r\n def get_right(self):\r\n return self.__right\r\n def set_data(self, data):\r\n self.__data = data\r\n def get_data(self):\r\n return self.__data\r\n def set_left(self, left):\r\n self.__left = left\r\n def set_right(self, right):\r\n self.__right = right\r\n\r\ndef add_all(a_list, index):\r\n if index == len(a_list) - 1:\r\n return BinaryTree(a_list[index])\r\n new_binary_tree = BinaryTree(a_list[index])\r\n left_child_index = 2 * index + 1\r\n if left_child_index < len(a_list):\r\n new_binary_tree.set_left(add_all(a_list, left_child_index))\r\n right_child_index = 2 * index + 2\r\n if right_child_index < len(a_list):\r\n new_binary_tree.set_right(add_all(a_list, right_child_index))\r\n return new_binary_tree\r\n\r\ndef convert_tree_to_list(b_tree):\r\n if b_tree is None:\r\n return None\r\n new_list = [b_tree.get_data(), convert_tree_to_list(b_tree.get_left()), convert_tree_to_list(b_tree.get_right())]\r\n return new_list\r\n\r\n#q7\r\ndef reverse_sort_order(tree):\r\n tree_nodes = get_tree_preorder(tree)\r\n tree_nodes.sort()\r\n tree_nodes.reverse()\r\n return tree_nodes\r\n\r\n#q8\r\ndef get_bst_list_order(tree):\r\n if tree is None:\r\n return []\r\n new_queue = Queue()\r\n return_list = []\r\n new_queue.enqueue(tree)\r\n while not new_queue.is_empty():\r\n current = new_queue.peek()\r\n return_list.append(new_queue.dequeue().get_data())\r\n if current.get_left() is not None:\r\n new_queue.enqueue(current.get_left())\r\n if current.get_right() is not None:\r\n new_queue.enqueue(current.get_right())\r\n return return_list\r\n\r\nclass BinarySearchTree:\r\n def __init__(self, data, left=None, right=None):\r\n self.__data = data\r\n self.__left = left\r\n self.__right = right\r\n def insert_left(self, new_data):\r\n if self.__left == None:\r\n self.__left = BinarySearchTree(new_data)\r\n else:\r\n t = BinarySearchTree(new_data, left=self.__left)\r\n self.__left = t\r\n def insert_right(self, new_data):\r\n if self.__right == None:\r\n self.__right = BinarySearchTree(new_data)\r\n else:\r\n t = BinarySearchTree(new_data, right=self.__right)\r\n self.__right = t\r\n def get_left(self):\r\n return self.__left\r\n def get_right(self):\r\n return self.__right\r\n def set_left(self, left):\r\n self.__left = left\r\n def set_right(self, right):\r\n self.__right = right\r\n def set_data(self, data):\r\n self.__data = data\r\n def get_data(self):\r\n return self.__data\r\n\r\n def __contains__(self, value):\r\n if value == self.get_data():\r\n return True\r\n elif value < self.get_data():\r\n return self.get_left().__contains__(value) if self.get_left() is not None else False\r\n elif value > self.get_data():\r\n return self.get_right().__contains__(value) if self.get_right() is not None else False\r\n\r\n def search(self, value):\r\n if value == self.get_data():\r\n return self\r\n elif value < self.get_data():\r\n return self.get_left().search(value) if self.get_left() is not None else None\r\n elif value > self.get_data():\r\n return self.get_right().search(value) if self.get_right() is not None else None\r\n\r\n def insert(self, value):\r\n if value == self.get_data():\r\n return #checks if the value is already in the tree\r\n elif value < self.get_data():\r\n if self.get_left() is None:\r\n self.set_left(BinarySearchTree(value)) #creates a link\r\n else:\r\n self.get_left().insert(value)\r\n else:\r\n if self.get_right() is None:\r\n self.set_right(BinarySearchTree(value))\r\n else:\r\n self.get_right().insert(value)\r\n\r\nclass Queue:\r\n def __init__(self):\r\n self.__items = []\r\n\r\n def is_empty(self):\r\n return self.__items == []\r\n\r\n def enqueue(self, item):\r\n self.__items.insert(0,item)\r\n\r\n def dequeue(self):\r\n if len(self.__items) == 0:\r\n raise IndexError(\"ERROR: The queue is empty!\")\r\n return self.__items.pop()\r\n\r\n def size(self):\r\n return len(self.__items)\r\n\r\n def peek(self):\r\n if len(self.__items) == 0:\r\n raise IndexError(\"ERROR: The queue is empty!\")\r\n return self.__items[len(self.__items)-1]\r\n\r\n def __str__(self):\r\n self.__items.reverse()\r\n return f\"Queue: {self.__items}\"\r\n\r\n def __len__(self):\r\n return self.size()\r\n\r\n def clear(self):\r\n self.__items = []\r\n\r\n def enqueue_list(self, a_list):\r\n for element in a_list:\r\n self.enqueue(element)\r\n\r\n def multi_dequeue(self, number):\r\n if number > self.size():\r\n return False\r\n for pops in range(number):\r\n self.dequeue()\r\n return True\r\n\r\ndef main():\r\n new_bt = add_all([\"Hoiho\", \"Kaki\", \"Takahe\", \"Ruru\", \"Moa\", \"Piwaiwaka\"], 0)\r\n print(convert_tree_to_list(new_bt))\r\n print(max_value_length(new_bt))\r\n return\r\n\r\nmain()"} {"blob_id": "d49b13658eb912dc8db5f3d3d4931a32c4623177", "repo_name": "crazykunal/Leetcode-best-DSA-Questions", "path": "/src/Reorder List.py", "length_bytes": 1482, "score": 3.890625, "int_score": 4, "content": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def reorderList(self, head: ListNode) -> None:\n \"\"\"\n Do not return anything, modify head in-place instead.\n \"\"\"\n if not head:\n return None\n slow=head\n fast=head\n while(fast and fast.next):\n slow=slow.next\n fast=fast.next.next\n mid=slow\n prev=None\n cur=mid\n while cur:\n temp=cur.next\n cur.next=prev \n prev=cur\n cur=temp\n head_of_second_rev = prev\n first=head \n second=head_of_second_rev\n while second.next:\n next_hop = first.next\n first.next = second\n first = next_hop\n next_hop = second.next\n second.next = first\n second = next_hop\n \n \n \n# if not head or not head.next:\n# return\n \n# slow, fast = head, head\n# while fast and fast.next:\n# slow = slow.next\n# fast = fast.next.next\n \n# prev, slow.next, slow = None, None, slow.next\n# while slow:\n# prev, prev.next, slow = slow, prev, slow.next\n\n# slow = head\n# while prev:\n# slow.next, slow = prev, slow.next\n# prev.next, prev = slow, prev.next\n \n"} {"blob_id": "1149115a35e4aaedf25126c08a080013fd0c8ffc", "repo_name": "PythonProgrammieren/Programmieraufgabe", "path": "/Programmieraufgabe_02.py", "length_bytes": 1520, "score": 3.75, "int_score": 4, "content": "\r\n\r\n# Python Programmieraufgabe 02\r\n# \r\n# Programmieraufgabe:\r\n#-----------------------------\r\n# Man hat als Input einen Array von Integer. Schreibe eine Funktion welche einen neuen Array von Integer zur\u00fcck gibt. \r\n# Die einzelnen Elemente des Arrays sollen das Produkt von allen Zahlen des ursp\u00fcnglichen Arrays sein, augenommen der \r\n# Zahl welche am selben Index ist.\r\n# \r\n# Zum Beispiel, f\u00fcr den Input [1, 2, 3, 4, 5] w\u00e4re das Ergebnis [120, 60, 40, 30, 24]. \r\n# F\u00fcr den Input [3, 2, 1] w\u00e4re das Ergebnis [2, 3, 6].\r\n#\r\n# Zusatz: Ist es m\u00f6glich ohne Division zu l\u00f6sen?\r\n#\r\n# author: python-programmieren.com\r\n\r\n\r\n\r\n# Solution with Division\r\ndef productArray_01(input_array):\r\n N = len(input_array)\r\n\r\n output_array = N*[1]\r\n\r\n prod = 1\r\n for i in range(N):\r\n prod *= input_array[i]\r\n\r\n for i in range(N):\r\n output_array[i] = int(prod/input_array[i])\r\n\r\n return output_array\r\n\r\n\r\n# Solution without Division\r\ndef productArray_02(input_array):\r\n N = len(input_array)\r\n\r\n output_array = N*[1] \r\n left_side = N*[1]\r\n right_side = N*[1] \r\n \r\n for i in range(1, N):\r\n left_side[i] = input_array[i-1]*left_side[i-1]\r\n\r\n for i in range(N - 2, -1, -1):\r\n right_side[i] = input_array[i+1]*right_side[i+1]\r\n\r\n for i in range(N):\r\n output_array[i] = left_side[i] * right_side[i]\r\n\r\n return output_array\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n array = [1, 2, 3, 4, 5]\r\n\r\n print(productArray_01(array))\r\n print(productArray_02(array))\r\n\r\n\r\n\r\n\r\n"} {"blob_id": "96c6d360087689a90867c53712f9e8b2e99c8ccc", "repo_name": "chionglai/euler", "path": "/q071.py", "length_bytes": 1210, "score": 3.96875, "int_score": 4, "content": "#!/usr/bin/env python\n\nimport time\n\n\"\"\"\nAlgorithm:\nThere is a pattern here. The explanation will be based on the\nexample given in the problem. We want to find what is numerator\nof the proper fraction directly left to 3/7. Notice that from\nthe example given, the fraction left to 3/7 is 2/5, i.e.\n\n..., 2/5, 3/7, ...\n\nAs d is increased, new proper fraction added to the left of\n3/7 will be in the following pattern\n\na^(num)_1 + d^(num) * n\n-----------------------\na^(den)_1 + d^(den) * n\n\nLet's call the 3/7 the pivot. Hence, from the problem given,\na^(num)_1 and a^(num)_1 is the numerator and denominator\ndirectly left to the pivot. d^(num) and d^(den) is the\nnumerator and denominator of the pivot. Then, the algorithm,\nwhich is O(1) in both memory and computational, will be:\n1. Solve a^(den)_1 + d^(den) * n <= d for n.\n2. Use the n obtained in 1 to calculate for\n a^(num)_1 + d^(num) * n\n\"\"\"\n\nd = 1e6\nd_num = 3\nd_den = 7\na_num_1 = 2\na_den_1 = 5\n\ntic = time.time()\n\nn = (d - a_den_1) // d_den\n\nnumerator = a_num_1 + d_num * n\n\nres = numerator\ntoc = time.time()\n\ndenominator = a_den_1 + d_den * n\n\nprint \"Result = %d, in %f s\" % (res, toc - tic)\nprint \"The fraction is %d / %d\" % (numerator, denominator)\n"} {"blob_id": "e2694bfaa7427edeaf896da2f12f8f95391dee78", "repo_name": "HLNN/leetcode", "path": "/src/1117-as-far-from-land-as-possible/as-far-from-land-as-possible.py", "length_bytes": 1565, "score": 3.671875, "int_score": 4, "content": "# Given an n x n grid\u00a0containing only values 0 and 1, where\u00a00 represents water\u00a0and 1 represents land, find a water cell such that its distance to the nearest land cell is maximized, and return the distance.\u00a0If no land or water exists in the grid, return -1.\n#\n# The distance used in this problem is the Manhattan distance:\u00a0the distance between two cells (x0, y0) and (x1, y1) is |x0 - x1| + |y0 - y1|.\n#\n# \u00a0\n# Example 1:\n#\n#\n# Input: grid = [[1,0,1],[0,0,0],[1,0,1]]\n# Output: 2\n# Explanation: The cell (1, 1) is as far as possible from all the land with distance 2.\n#\n#\n# Example 2:\n#\n#\n# Input: grid = [[1,0,0],[0,0,0],[0,0,0]]\n# Output: 4\n# Explanation: The cell (2, 2) is as far as possible from all the land with distance 4.\n#\n#\n# \u00a0\n# Constraints:\n#\n#\n# \tn == grid.length\n# \tn == grid[i].length\n# \t1 <= n\u00a0<= 100\n# \tgrid[i][j]\u00a0is 0 or 1\n#\n#\n\n\nclass Solution:\n def maxDistance(self, grid: List[List[int]]) -> int:\n d = ((1, 0), (-1, 0), (0, 1), (0, -1))\n n = len(grid)\n land = [(i, j) for i, j in product(range(n), range(n)) if grid[i][j] == 1]\n if len(land) == 0 or len(land) == n * n:\n return -1\n seen = set(land)\n q = deque([(i, j, 0) for i, j in land])\n \n dis = 0\n while q:\n i, j, dis = q.popleft()\n for di, dj in d:\n ii, jj = i + di, j + dj\n if (ii, jj) not in seen and 0 <= ii < n and 0 <= jj < n:\n seen.add((ii, jj))\n q.append((ii, jj, dis + 1))\n \n return dis\n \n"} {"blob_id": "068820b9c9347dfb293037833193501a875cdab9", "repo_name": "rsharanesh2002/EE2703-Applied-Programming-Lab-IITM", "path": "/End-Semester/EE19B116.py", "length_bytes": 5555, "score": 3.765625, "int_score": 4, "content": "'''\nEE2703 Applied Programming Lab\nSubmission for End-Semester Examination\nName: Sharanesh R\nRoll Numer: EE19B116\n'''\n\n# Importing all functions from pylab\nfrom pylab import *\n\n# Defining constants\nN = 100 # Number of sections on the loop\na = 10 # Radius of the wire Looping\n\nx=linspace(-1,1,3) # x grid is -1,0,1\ny=linspace(-1,1,3) # y grid is -1,0,1\nz=linspace(1,1000,1000) # defining 1000 points along the z-axis\nX,Y,Z=meshgrid(x,y,z) # defining meshgrid to access the coordinates\n\nr = zeros((3,3,1000,3)) # Matrix that spans over the entire volume of observation\n# Stacking up the meshgrid coordinates \nr[:,:,:,0] = X \nr[:,:,:,1] = Y\nr[:,:,:,2] = Z\n\nphi = linspace(0,2*pi,N+1)[:-1] # The angular points on the loop\nr_ = a*(c_[cos(phi),sin(phi),zeros(N)]) # These are the coordinates of the points on the loop\n# Corresponds to the rl' vector given in the code\n\n# Visualising the points on the closed wire loop\nfigure('Figure-0') # Starting a new figure\nscatter(r_[:,0],r_[:,1],color='red') # Making scatter plot of all the points\nxlabel(r\"x $\\rightarrow$\")\nylabel(r\"y $\\rightarrow$\")\ntitle('Scatter plot of loop wire elements')\ngrid()\nshow()\n\n# Defining the Current elements as given in the question (multiple of cos(phi))\n## For Symmetric current flow case (given question)\nI = 4*pi*(c_[-1*cos(phi)*sin(phi),cos(phi)*cos(phi),zeros(N)])\n\n## For Anti-symmetric current flow case\n# I = 4*pi*(c_[-1*abs(cos(phi))*sin(phi),abs(cos(phi))*cos(phi),zeros(N)])\n\n## For static current flow case (static in current and time)\n# I = 4*pi*(c_[-1*sin(phi),cos(phi),zeros(N)])\n\n# Visualising the current elements at the points on the closed wire loop\nfigure('Figure-1') # Starting a new figure\nquiver(r_[:,0],r_[:,1],I[:,0],I[:,1],color='blue',label='current') # Making a quizer plot of current elements\nxlabel(r\"x $\\rightarrow$\")\nylabel(r\"y $\\rightarrow$\")\ntitle('Quiver plot of current in the wire elements on X-Y plane')\nlegend()\ngrid()\nshow()\n\n# dl is defined as the length infinitesmal small loop element, it's along the axial angle direction,\n# magnitude of it is the small step angle multiplied by radius\ndl = (2*pi*10/100)*c_[-sin(phi),cos(phi),zeros(N)]\ndl_x=dl[:,0].reshape((100,))\ndl_y=dl[:,1].reshape((100,))\n\n# Defining 'A' vector that stores the magnetic field at all the points in volume of observation\nA = zeros((3,3,1000,2),dtype='complex128') \n\n# Defining the calc(l) function that computes the norm and returns the summation term for each value of 'l'\ndef calc(l):\n\tRl = norm(r-r_[l],axis=-1) # Computing the norm\n\t### Vector Potential for symmetric and non-static \n\tA_x_ = (cos(phi[l])*exp(-0.1j*Rl)*dl_x[l]/Rl) # Computing the magnetic potential along x-axis\n\tA_y_ = (cos(phi[l])*exp(-0.1j*Rl)*dl_y[l]/Rl) # Computing the magnetic potential along y-axis\n\n\t### Vector Potential for symmetric and static in time\n\t# A_x_ = (cos(phi[l])*dl_x[l]/Rl) # Computing the magnetic potential along x-axis\n\t# A_y_ = (cos(phi[l])*dl_y[l]/Rl) # Computing the magnetic potential along y-axis\n\n\t### Vector Potential for anti-symmetric and non-static \n\t# A_x_ = (abs(cos(phi[l]))*exp(-0.1j*Rl)*dl_x[l]/Rl) # Computing the magnetic potential along x-axis\n\t# A_y_ = (abs(cos(phi[l]))*exp(-0.1j*Rl)*dl_y[l]/Rl) # Computing the magnetic potential along y-axis\n\n\t### Vector Potential for anti-symmetric and static in time\n\t# A_x_ = (abs(cos(phi[l]))*dl_x[l]/Rl) # Computing the magnetic potential along x-axis\n\t# A_y_ = (abs(cos(phi[l]))*dl_y[l]/Rl) # Computing the magnetic potential along y-axis\n\n\t### Vector Potential static in both time and space\n\t# A_x_ = (dl_x[l]/Rl) # Computing the magnetic potential along x-axis\n\t# A_y_ = (dl_y[l]/Rl) # Computing the magnetic potential along y-axis\n\n\treturn Rl, A_x_, A_y_\n\n# Looping through all the loop points and finding the total magnetic potential\nfor i in range(N):\n\tRl, A_x, A_y = calc(i)\n\tA[:,:,:,0] += A_x\n\tA[:,:,:,1] += A_y\n\n# Computing 'B' magnetic field as an approximated sum using the magnetic potentials around the neighbouring points\nB = (A[1,2,:,1]-A[2,1,:,0]-A[1,0,:,1]+A[0,1,:,0])/4\n\n# Visualising the variation of magnetic field along the z-axis\nfigure('Figure-2') # Starting a new figure\nloglog(z,abs(B),color='blue',label=r'$Magnetic field |B_z(z)|$')\nxlabel(r\"z $\\rightarrow$\")\nylabel(r\"$|B_z(z)| \\rightarrow$\")\ntitle(\"Log-log plot of magnetic field along z-axis\")\nlegend()\ngrid()\nshow()\n\nfigure('Figure-3') # Starting a new figure\nplot(z,abs(B),color='blue',label=r'$Magnetic field |B_z(z)|$')\nxlabel(r\"z $\\rightarrow$\")\nylabel(r\"$|B_z(z)| \\rightarrow$\")\ntitle(\"Magnetic field along z-axis\")\nlegend()\ngrid()\nshow()\n\n# Performing the Least squares Estimation and seeking the coefficients\n# Fitting B = c*(z^b)\nb,log_c = lstsq(c_[log(z),ones(1000)],log(abs(B)),rcond=None)[0]\nprint(\"Estimated Coefficient 'b': \",b)\nprint(\"Estimated Coefficient 'c': \",exp(log_c))\n\n# Log-log plot of the actual and estimated magnetic fields\nfigure('Figure-4') # Starting a new figure\nloglog(z,abs(B),label='Actual',color='green')\nloglog(z,exp(log_c)*(z**b),label='Estimated using fit',color='red')\nxlabel(r\"z $\\rightarrow$\")\nylabel(r\"$|B_z(z)| \\rightarrow$\")\t\ntitle(r\"Comparison of Actual and Estimated Magnetic field $|B_z(z)|$ (Log-log)\")\nlegend()\ngrid()\nshow()\n\n# Linear scale plot of the actual and estimated magnetic fields\nfigure('Figure-5') # Starting a new figure\nplot(z,abs(B),label='Actual',color='green')\nplot(z,exp(log_c)*(z**b),label='Estimated using fit',color='red')\nxlabel(r\"z $\\rightarrow$\")\nylabel(r\"$|B_z(z)| \\rightarrow$\")\ntitle(r\"Actual and Estimated Magnetic field $|B_z(z)|$\")\nlegend()\ngrid()\nshow()"} {"blob_id": "d3272c30383d880bcc6d279173b93fd8e27250ef", "repo_name": "bhi5hmaraj/APRG-2020", "path": "/Assignment 2/rbtree.py", "length_bytes": 6361, "score": 3.765625, "int_score": 4, "content": "# This is an implementation of a Red Black tree from CLRS\n\nglobal RED, BLACK\n\nRED = 0\nBLACK = 1\n\nclass Node:\n\n # 0 - red , 1 - black \n def __init__(self, val, left=None, right=None, parent=None, size=1, color=RED):\n self.val = val\n self.left = left\n self.right = right\n self.parent = parent\n self.size = size\n self.color = color\n\n\nclass RedBlackTree():\n\n global NIL, DEBUG\n\n DEBUG = False\n NIL = Node(val=-1, color=BLACK, size=0)\n\n\n def check(curr):\n if curr != NIL:\n assert curr.size == 1 + curr.left.size + curr.right.size\n l = RedBlackTree.check(curr.left)\n r = RedBlackTree.check(curr.right)\n assert l == r\n return l + (1 if curr.color == BLACK else 0)\n else:\n return 0\n\n\n def check_tree(self):\n print(\"Checking ... \")\n assert self.root.color == BLACK, \"Root isn't black\"\n assert RedBlackTree.check(self.root)\n print(\"Looks fine !\")\n\n def print_tree(self):\n print('\\n'.join(RedBlackTree.pretty_print(\"\", True, [], self.root)))\n # RedBlackTree.inorder_print(self.root)\n\n def pretty_print(prefix, isTail, sb, root):\n if root == NIL:\n return [\"Tree is empty\"]\n\n if root.right != NIL:\n RedBlackTree.pretty_print(prefix + (\"| \" if isTail else \" \"), False, sb, root.right)\n\n # sb.append(prefix + \"|-- \" + str(root.val) + \" (p = {}, c = {}, sz = {})\".format(root.parent.val, root.color, root.size))\n sb.append(prefix + \"|-- \" + str(root.val))\n if root.left != NIL:\n RedBlackTree.pretty_print(prefix + (\"| \" if not isTail else \" \"), True, sb, root.left)\n\n return sb\n\n def update_size(node):\n node.size = 1 + node.left.size + node.right.size\n\n def count_less_than(curr, x):\n if curr == NIL:\n return 0\n elif x <= curr.val:\n return RedBlackTree.count_less_than(curr.left, x)\n else:\n return 1 + curr.left.size + RedBlackTree.count_less_than(curr.right, x)\n\n def get_count_in_range(self, l, r):\n return RedBlackTree.count_less_than(self.root, r + 1) - RedBlackTree.count_less_than(self.root, l)\n\n def fixup(self, curr):\n while curr.parent.color == RED:\n\n if DEBUG : print(curr.val, \"inside fix\")\n \n if curr.parent == curr.parent.parent.left:\n y = curr.parent.parent.right # uncle of curr\n if y.color == RED:\n curr.parent.color = BLACK\n y.color = BLACK\n curr.parent.parent.color = RED\n curr = curr.parent.parent\n else:\n if curr == curr.parent.right: # uncle is not red and curr is right child\n curr = curr.parent\n self.left_rotate(curr)\n\n curr.parent.color = BLACK\n curr.parent.parent.color = RED\n self.right_rotate(curr.parent.parent)\n else:\n y = curr.parent.parent.left\n if y.color == RED:\n curr.parent.color = BLACK\n y.color = BLACK\n curr.parent.parent.color = RED\n curr = curr.parent.parent\n else:\n if curr == curr.parent.left:\n curr = curr.parent\n self.right_rotate(curr)\n\n curr.parent.color = BLACK\n curr.parent.parent.color = RED\n self.left_rotate(curr.parent.parent)\n\n self.root.color = BLACK\n\n def b_height(curr):\n h = 0\n curr = curr.left\n while curr != NIL:\n h += 1 if curr.color == BLACK else 0\n curr = curr.left # leftist ! \n\n return h\n\n def get_height(self):\n return RedBlackTree.b_height(self.root)\n\n def insert(self, x):\n # self.root = RedBlackTree.insert_(self, self.root, x)\n\n # self.root.parent = NIL\n y = NIL\n curr = self.root\n while curr != NIL:\n y = curr\n if curr.val == x:\n return\n curr = curr.left if x < curr.val else curr.right\n\n new_node = Node(val=x, left=NIL, right=NIL)\n new_node.parent = y\n if y == NIL:\n self.root = new_node\n elif new_node.val < y.val:\n y.left = new_node\n else:\n y.right = new_node\n\n curr = new_node.parent\n while curr != NIL:\n RedBlackTree.update_size(curr)\n curr = curr.parent\n\n self.fixup(new_node) \n if DEBUG: \n print(new_node.val)\n self.print_tree()\n print(\"Height \", self.get_height())\n self.check_tree()\n\n # Need to update b_height, cnt and all other fields !\n\n\n\n def left_rotate(self, x):\n y = x.right\n x.right = y.left\n if y.left != NIL:\n y.left.parent = x\n y.parent = x.parent\n\n if x.parent == NIL:\n self.root = y\n elif x == x.parent.left:\n x.parent.left = y\n else:\n x.parent.right = y\n\n y.left = x\n x.parent = y\n RedBlackTree.update_size(x)\n RedBlackTree.update_size(y)\n\n def right_rotate(self, y):\n x = y.left\n y.left = x.right\n if x.right != NIL:\n x.right.parent = y\n x.parent = y.parent\n\n if y.parent == NIL:\n self.root = x\n elif y == y.parent.right:\n y.parent.right = x\n else:\n y.parent.left = x\n\n x.right = y\n y.parent = x\n RedBlackTree.update_size(y)\n RedBlackTree.update_size(x)\n\n\n\n def __init__(self, root=None):\n self.root = NIL\n\n\n\n\n# rbtree = RedBlackTree()\n# for i in range(20):\n# rbtree.insert(i)\n\n# rbtree.print_tree()\n# l = 10\n# r = 15\n\n# print(\"count in range %d to %d\" % (l, r), rbtree.get_count_in_range(l, r))\n\ndef solve():\n\n rbtree = RedBlackTree()\n q = int(input())\n for _ in range(q):\n line = input().split()\n if line[0] == '+':\n rbtree.insert(int(line[1]))\n else:\n l, r = map(int, line[1:])\n print(rbtree.get_count_in_range(l, r))\n\n"} {"blob_id": "3119dbb1a52d2bd98d76308c6a7affe321b9745a", "repo_name": "workprinond/Anti-Alignment", "path": "/anti_alignment/distance_metrics/levenshtein.py", "length_bytes": 2395, "score": 3.84375, "int_score": 4, "content": "from anti_alignment.distance_metrics.distance_interface import DistanceMetricInterface\n\n\"\"\"\nThis is a straightforward implementation of a well-known algorithm, and thus\nprobably shouldn't be covered by copyright to begin with. But in case it is,\nthe author (Magnus Lie Hetland) has, to the extent possible under law,\ndedicated all copyright and related and neighboring rights to this software\nto the public domain worldwide, by distributing it under the CC0 license,\nversion 1.0. This software is distributed without any warranty. For more\ninformation, see \n\nDuring our research, we obtained this file in the stackoverflow post:\nhttps://stackoverflow.com/questions/6709693/calculating-the-similarity-of-two-lists\nWe just deleted the main method\n\n\"\"\"\n\nclass Levenshtein_Distance(DistanceMetricInterface):\n def get_distance(self, a, b):\n \"\"\"\n counts how many replacements, deletions and insertions of symbols between two strings.\n\n Levenshtein\u2019s distance (or edit distance) which In our case its needed to obtain \u03b3 projected to labeled\n transitions starting from \u03c3. calculating (replace/add/delete) at the same cost of 1.\n for instance the word 'ababababab' and 'bababababa' are at distance 2 from each other.\n on the other hand if it was hamming distance it would be at distance 10 for the same example.\n further use the output, will be divided by the length of the greatest(len(\u03b3), len(\u03c3))\n\n :param str a: trace or anti-alignment you want to compare as a list of strings\n :param str b: trace or anti-alignment you want to compare a to, also as a list of strings\n :return: returns distance between the provided lists, cost 1 for each operation (replace/add/delete)\n :rtype: int\n \"\"\"\n n, m = len(a), len(b)\n if n > m:\n # Make sure n <= m, to use O(min(n,m)) space\n a, b = b, a\n n, m = m, n\n\n current = range(n + 1)\n for i in range(1, m + 1):\n previous, current = current, [i] + [0] * n\n for j in range(1, n + 1):\n add, delete = previous[j] + 1, current[j - 1] + 1\n change = previous[j - 1]\n if a[j - 1] != b[i - 1]:\n change = change + 1\n current[j] = min(add, delete, change)\n\n return current[n]\n"} {"blob_id": "94232a242e1063785d915fd8679f5a388e830aad", "repo_name": "linannn/LeetCode_Solution", "path": "/606.\u6839\u636e\u4e8c\u53c9\u6811\u521b\u5efa\u5b57\u7b26\u4e32.py", "length_bytes": 1545, "score": 3.609375, "int_score": 4, "content": "#\n# @lc app=leetcode.cn id=606 lang=python3\n#\n# [606] \u6839\u636e\u4e8c\u53c9\u6811\u521b\u5efa\u5b57\u7b26\u4e32\n#\n\n# @lc code=start\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\n\nclass Solution:\n # \u9012\u5f52\n # def tree2str(self, t: TreeNode) -> str:\n # return self.tree(t)\n\n # def tree(self, t: TreeNode) -> str:\n # if not t:\n # return ''\n # res = '{}'.format(t.val)\n # if not t.left and not t.right:\n # return res\n # res += '('\n # res += self.tree(t.left)\n # res += ')'\n # if t.right:\n # res += '('\n # res += self.tree(t.right)\n # res += ')'\n # return res\n def tree2str(self, t: TreeNode) -> str:\n stack = []\n stack.append(t)\n res = ''\n while stack:\n node = stack.pop()\n if node == None:\n continue\n if isinstance(node, TreeNode):\n if not node.left and not node.right:\n stack.append(node.val)\n continue\n if node.right:\n stack.append(')')\n stack.append(node.right)\n stack.append('(')\n\n stack.append(')')\n stack.append(node.left)\n stack.append('(')\n stack.append(node.val)\n else:\n res += '{}'.format(node)\n return res\n\n\n# @lc code=end\n"} {"blob_id": "513d5b2638ebd35a417e04b036f56eae91bec100", "repo_name": "yqxd/LEETCODE", "path": "/42TrappingRainWater.py", "length_bytes": 977, "score": 4.0625, "int_score": 4, "content": "'''\nGiven n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.\n\n\nThe above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!\n\nExample:\n\nInput: [0,1,0,2,1,0,1,3,2,1,2,1]\nOutput: 6\n'''\n\n\nclass Solution(object):\n def trap(self, height):\n \"\"\"\n :type height: List[int]\n :rtype: int\n \"\"\"\n if len(height) <= 2:\n return 0\n if height[0] > height[-1]:\n height.reverse()\n index = 1\n num = 0\n while index < len(height):\n if height[index] >= height[0]:\n return num + self.trap(height[index:])\n else:\n num += height[0] - height[index]\n index += 1\n\n\nA = Solution()\nprint(A.trap([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]))\n"} {"blob_id": "d33e3491731c5b096cdc0d0c68af500c1ff54555", "repo_name": "jankristoffercheng/CSC713M", "path": "/05 - Multinomial Logistic Regression (SoftMax) - Student/multinomial_logistic_regression.py", "length_bytes": 13679, "score": 3.78125, "int_score": 4, "content": "import numpy as np\n\nclass MultinomialLogisticRegression(object):\n def __init__(self, input_dim, num_classes, std_dev=1e-2):\n self.initialize_weights(input_dim, num_classes, std_dev)\n\n def initialize_weights(self, input_dim, num_classes, std_dev=1e-2):\n \"\"\"\n Initialize the weights of the model. The weights are initialized\n to small random values. Weights are stored in the variable dictionary\n named self.params.\n\n W: weight vector; has shape (D, C) because each class will have its own set of weights\n b: bias vector; has shape (C,) \n where C is the number of classes\n \n Inputs:\n - input_dim: (int) The dimension D of the input data.\n - std_dev: (float) Controls the standard deviation of the random values.\n \"\"\"\n \n self.params = {}\n #############################################################################\n # TODO: Initialize the weight and bias. #\n # Check the comment above to know the expected shape of the weights and bias#\n # The weight vector are initialized small random values, while bias gets 0s #\n #############################################################################\n self.params['W'] = np.random.randn(input_dim, num_classes) * std_dev\n #self.params['b'] = np.random.randn(num_classes) - was suggested\n self.params['b'] = np.zeros(num_classes)\n #############################################################################\n # END OF YOUR CODE #\n ############################################################################# \n \n \n def train(self, X, y, learning_rate=1e-3, reg=1e-5, num_iters=100,\n batch_size=200, verbose=False):\n \"\"\"\n Train logistic regression using stochastic gradient descent.\n\n Inputs:\n - X: A numpy array of shape (N, D) containing training data; there are N\n training samples each of dimension D.\n - y: A numpy array of shape (N, 1) containing the ground truth values.\n - learning_rate: (float) learning rate for optimization.\n - reg: (float) regularization strength.\n - num_iters: (integer) number of steps to take when optimizing\n - batch_size: (integer) number of training examples to use at each step.\n - verbose: (boolean) If true, print progress during optimization.\n\n Outputs:\n A list containing the value of the loss function at each training iteration.\n \"\"\"\n num_train, dim = X.shape\n\n loss_history = []\n for it in range(num_iters):\n\n #########################################################################\n # TODO: Create a random minibatch of training data and labels, storing #\n # them in X_batch and y_batch respectively. #\n # Search up np.random.choice #\n # and numpy array indexing: https://docs.scipy.org/doc/numpy-1.13.0/user/basics.indexing.html#indexing-multi-dimensional-arrays #\n #########################################################################\n indices = np.random.choice(num_train,batch_size)\n X_batch = X[indices,:]\n y_batch = y[indices]\n #########################################################################\n # END OF YOUR CODE #\n #########################################################################\n \n loss, grads = self.loss(X_batch, y=y_batch, reg=reg)\n\n if it % 100 == 0:\n loss_history.append(np.squeeze(loss))\n\n #########################################################################\n # TODO: Use the gradients in the grads dictionary to update the #\n # parameters of the model (stored in the dictionary self.params) #\n # using stochastic gradient descent. You'll need to use the gradients #\n # stored in the grads dictionary defined above. #\n #########################################################################\n\n self.params['W'] = self.params['W'] + learning_rate * grads['W']\n self.params['b'] = self.params['b'] + learning_rate * grads['b']\n #########################################################################\n # END OF YOUR CODE #\n #########################################################################\n if verbose and it % 100 == 0:\n print('iteration %d / %d: loss %f' % (it, num_iters, loss))\n\n return loss_history\n\n def softmax(self,x):\n '''\n Implement the softmax activation function.\n \n Inputs: \n - x: a numpy array of shape (N,C) denoting the scores of the hypotheses of \n the classes\n \n Outputs:\n - probs: a numpy array of shape (N, C) containing the probabilities given \n the scores of each X[i]\n \n Hint: \n Any np.exp(a) with a large enough a will yield an incredibly large value\n Thankfully, softmax is constant invariant as long as the constant c is added to\n all the scores of that X[i]. \n\n Refer to the proof here: \n https://www.quora.com/Why-is-softmax-invariant-to-constant-offsets-to-the-input\n \n '''\n max = np.reshape(np.amax(x, axis=1), (-1, 1))\n divisor = np.sum(np.exp(x-max), axis=1, keepdims=True)\n probs = np.exp(x-max) / divisor\n return probs\n\n\n def cross_entropy(self,probs, labels):\n '''\n Cross entropy for C outcomes. (Can be thought of as a measure of misclassification)\n\n Inputs:\n - probs: a numpy array of shape (N,C) showing the probabilities of an X[i]\n belonging to any of the C classes; this is the output of self.softmax\n - labels: a numpy array of shape (N,) containing the actual labels (y) of each X[i] \n\n Outputs:\n The data loss given the hypotheses (before regularization)\n '''\n \n N = probs.shape[0]\n \n #own version for array\n #array = np.zeros((probs.shape[0], probs.shape[1]))\n #indices = np.arange(probs.shape[0])\n #array[indices,labels] = 1\n \n array = np.eye(probs.shape[1])\n array = array[labels]\n ce = -np.sum(np.multiply(array, np.log(probs))) / N\n return ce\n \n\n\n def softmax_cross_entropy_loss(self,x,labels):\n '''\n This is a special function designed to compute the loss (loss), and calculate the \n gradient the loss (dloss). As the gradient computation also need the individual \n prob of the actual class (y), both the loss and dloss are computed here with the\n output of self.softmax. \n \n Note: We can calculate for the gradient separately by calling self.softmax again,\n but note how that will double our computation for the probs (softmax)\n\n Inputs:\n - x: a numpy array of shape (N,C) denoting the scores of the hypotheses of \n the classes\n - labels: a numpy array of shape (N,) containing the actual labels (y) of each X[i] \n\n Hint: the gradient of the loss only affects probs belonging to the actual label.\n There are two ways how you could get the probs of the actual label:\n #1 Create a (N,C) matrix, where in each row, the actual class will get a 1 and the\n rest will get 0 (hint^2: np.eye can accept an array of which indices the ones \n will be placed\n #2 A matrix indices can be separated per dimension: following the style of\n matrix[dim_indx_1, dim_indx_2]\n See : http://cs231n.github.io/python-numpy-tutorial/#numpy-array-indexing\n In this case, dim_indx_1 could be an array going through 1..N, and dim_indx_1 \n refer to the columns (label/class) you just need\n\n Outputs:\n The data loss given the hypotheses (before regularization)\n '''\n \n N = x.shape[0]\n probs = self.softmax(x) # turn scores into probs\n loss = self.cross_entropy(probs, labels)\n\n dloss = probs.copy()\n #########################################################################\n # TODO: Calculate for the gradients of the loss #\n #########################################################################\n \n #own version for array\n #array = np.zeros((probs.shape[0], probs.shape[1]))\n #indices = np.arange(probs.shape[0])\n #array[indices,labels] = 1\n \n array = np.eye(probs.shape[1])\n array = array[labels]\n dloss = array-np.multiply(probs, array)\n \n #########################################################################\n # END OF YOUR CODE #\n #########################################################################\n\n \n # the gradient of the loss may already be calculated here\n return loss, dloss\n\n def loss(self, X, y=None, reg=0.0):\n \"\"\"\n Compute the loss and gradients for an iteration of linear regression.\n\n Inputs:\n - X: Input data of shape (N, D). Each X[i] is a training sample.\n - y: Vector of training labels. y[i] is the ground truth value for X[i].\n - reg: Regularization strength.\n\n Returns:\n Return a tuple of:\n - loss: Loss (data loss and regularization loss) for this batch of training\n samples.\n - grads: Dictionary mapping parameter names to gradients of those parameters\n with respect to the loss function; has the same keys as self.params.\n \"\"\"\n \n # Unpack variables from the params dictionary\n W, b = self.params['W'], self.params['b']\n N, D = X.shape\n\n # Compute the forward pass\n #############################################################################\n # TODO: Perform the forward pass, computing the class scores for the input. #\n # Store the result in the scores variable, which should be an array of #\n # shape (N, C). #\n #############################################################################\n score = X.dot(W) + b\n #############################################################################\n # END OF YOUR CODE #\n #############################################################################\n \n # Compute the loss\n loss = None\n #############################################################################\n # TODO: Finish the forward pass, and compute the loss. This should include #\n # both the data loss and L2 regularization for W1 and W2. Store the result #\n # in the variable loss, which should be a scalar. Use the Softmax #\n # classifier loss. So that your results match ours, multiply the #\n # regularization loss by 0.5 #\n #############################################################################\n softmax_ce_loss, dloss = self.softmax_cross_entropy_loss(score,y)\n loss = softmax_ce_loss + ((reg/2)* np.sum(np.square(W)))\n \n #############################################################################\n # END OF YOUR CODE #\n #############################################################################\n\n # Backward pass: compute gradients\n grads = {}\n #############################################################################\n # TODO: Compute the derivatives of the weights and biases. Store the #\n # results in the grads dictionary. For example, grads['W'] should store #\n # the gradient on W, and be a matrix of same size. #\n #############################################################################\n dW = np.dot(np.transpose(X), dloss) / N + reg * W\n\n db = np.mean(dloss, axis=0)\n \n grads['W'] = dW\n grads['b'] = db\n \n #############################################################################\n # END OF YOUR CODE #\n #############################################################################\n\n return loss, grads\n \n def predict(self, X, poly_order = 1):\n \"\"\"\n Predict labels for test data using this classifier.\n\n Inputs:\n - X: A numpy array of shape (num_test, D) containing test data consisting\n of num_test samples each of dimension D.\n\n Returns:\n - prediction: A sorted numpy array of shape (num_test,num_classes) containing the probabilities for X[i] belonging to each of the classes\n \"\"\"\n W, b = self.params['W'], self.params['b']\n scores = X.dot(W) + b\n probs = self.softmax(scores)\n prediction = np.argmax(probs, axis=1) # Remember to get the most probable class as the label\n \n return prediction\n\n"} {"blob_id": "6224624995d618dd42733f5f86f7541a51aec6f8", "repo_name": "baci-brunet/Algorithms-", "path": "/QuickSelect:QuickSort.py", "length_bytes": 1428, "score": 3.59375, "int_score": 4, "content": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[15]:\n\n\nimport math\nimport random\n\ndef partition(arr, low, high): \n pivot = arr[high] \n i = low - 1\n for j in range(low , high): \n if arr[j] <= pivot:\n i = i + 1\n arr[i],arr[j] = arr[j],arr[i]\n if i >= 6:\n print(arr)\n \n arr[i + 1],arr[high] = arr[high],arr[i + 1] \n return i + 1 \n \n# finds pivot value\n\ndef quickselect(A, l, r, split):\n split = 1/4\n k = int((r-l)*split)\n pi = partition(A, l, r)\n \n if pi == r:\n return pi\n \n if k == pi:\n return pi\n elif k > pi:\n return quickselect(A, l, pi - 1, split) #k instead of pi?\n else:\n return quickselect(A, pi + 1, r, split) #k instead of pi?\n \n \ndef quickSort(arr, lo, hi): \n split = None\n if lo < hi: \n pi = quickselect(arr, lo, hi, split)\n pi = pi + lo\n \n print(arr)\n print(arr[lo:pi])\n print(arr[pi + 1: hi])\n \n quickSort(arr, lo, pi - 1) \n quickSort(arr, pi + 1, hi) \n \n \ndef main(n):\n arr = random.sample(range(0, n), n)\n x = len(arr) \n quickSort(arr, 0, x - 1) \n print (\"Sorted array is:\") \n for i in range(x): \n print (\"%d\" %arr[i]), \n\n\n# In[16]:\n\n\nmain(2)\nmain(4)\nmain(8)\nmain(16)\nmain(32)\nmain(64)\nmain(128)\nmain(256)\nmain(512)\nmain(1024)\nmain(2048)\nmain(4096)\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n"} {"blob_id": "c4ce8cb096120452a9e25f7d1fb86f9a4ffb2570", "repo_name": "PrajjwalDatir/CP", "path": "/gfg/jug1.py", "length_bytes": 2795, "score": 4.1875, "int_score": 4, "content": "# Question 1\n\"\"\"\nso we have linked list with data only equal to 0 , 1 or 2 and we have to sort them in O(n) as I think before prajjwal knows the answer of this question\n\"\"\"\n\n#so first we need linked list to start withs\nclass Node:\n\t\"\"\"docstring for Node\"\"\"\n\tdef __init__(self, data):\n\t\tself.data = data\n\t\tself.next = None\n\nclass linkedList:\n\t\"\"\"docstring for linkedList\"\"\"\n\tdef __init__(self):\n\t\tself.head = None\n\n\tdef push(self, data):\n\t\ttemp = self.head\n\t\tnewnode = Node(data)\n\t\tif self.head is None:\n\t\t\tself.head = newnode\n\t\t\treturn\n\t\telse:\n\t\t\twhile temp.next is not None:\n\t\t\t\ttemp = temp.next\n\t\t\ttemp.next = newnode\n\tdef printList(self):\n\t\ttemp = self.head\n\t\tif self.head is None:\n\t\t\tprint(\"List is empty\")\n\t\t\treturn 0\n\t\twhile temp.next:\n\t\t\tprint(temp.data, end=\"->\")\n\t\t\ttemp = temp.next\n\t\tprint(temp.data)\n\t\treturn 1\n\n\tdef sortList(self):\n\t\tif self.head is None:\n\t\t\tprint(\"Nothing to sort here.\")\n\t\t\treturn\n\t\telif self.head.next is None:\n\t\t\treturn\n\t\t# here zero one and two are to point at the latest 0 1 2 countered so that we can just swap with them\n\t\tlast_zero = None\n\t\tlast_one = None\n\t\tlast_two = None\n\t\ttemp = None\n\t\tcurrent = self.head\n\t\tif self.head.data == 1:\n\t\t\tlast_one = current\n\t\telif self.head.data == 0:\n\t\t\tlast_zero = current\n\t\telse:\n\t\t\tlast_two = current\n\n\t\t# print(f\"current is {current.data}\")\n\t\t# self.printList()\n\t\tcurrent = current.next\n\n\t\twhile current.next:\n\n\t\t\t# print(f\"current is {current.next.data}\")\n\t\t\t\n\t\t\tif current.next.data == 0:\n\t\t\t\tprint(f\"current is {current.next.data}\")\n\n\t\t\t\ttemp = current.next\n\n\t\t\t\tif last_zero is None:\n\t\t\t\t\tcurrent.next = temp.next\n\t\t\t\t\ttemp.next = self.head\n\t\t\t\t\tself.head = temp\n\t\t\t\t\tlast_zero = temp\n\t\t\t\t\t\n\t\t\t\t\tself.printList()\n\t\t\t\telse:\n\t\t\t\t\tcurrent.next = temp.next\n\t\t\t\t\ttemp.next = last_zero.next\n\t\t\t\t\tlast_zero.next = temp\n\t\t\t\t\tlast_zero = temp\n\n\t\t\t\t\tself.printList()\n\t\t\telif current.next.data == 1:\n\t\t\t\t\n\t\t\t\t# print(f\"current is {current.next.data}\")\n\t\t\t\t# self.printList()\n\n\t\t\t\ttemp = current.next\n\n\t\t\t\tif last_one is None:\n\n\n\t\t\t\t\tprint(f\"current is {current.next.data}\")\n\n\t\t\t\t\tself.printList()\n\n\t\t\t\t\tcurrent.next = temp.next\n\n\t\t\t\t\tif last_zero is None:\n\t\t\t\t\t\ttemp.next = self.head\n\t\t\t\t\t\tself.head = temp\n\t\t\t\t\telse:\t\t\t\t\t\n\t\t\t\t\t\ttemp.next = last_zero.next\n\t\t\t\t\t\tlast_zero.next = temp\n\t\t\t\t\tlast_one = temp\n\t\t\t\t\tself.printList()\n\t\t\t\telse:\n\t\t\t\t\tcurrent.next = temp.next\n\t\t\t\t\ttemp.next = last_one.next\n\t\t\t\t\tlast_one.next = temp\n\t\t\t\t\tlast_one = temp\n\t\t\telse:\n\t\t\t\tprint(f\"current is {current.next.data}\")\n\n\t\t\t\tself.printList()\n\t\t\t\tcurrent = current.next\n\t\t\t\n\nll = linkedList()\n# test case : 12012010 answer should be 00011122 \n\n# bug is when we encounter 1 before encountering\nll.push(2)\nll.push(1)\nll.push(0)\n# ll.push(1)\n# ll.push(0)\n# ll.push(2)\n# ll.push(0)\n# ll.push(1)\n# ll.push(0)\nll.printList()\nll.sortList()\nll.printList()"} {"blob_id": "ed87c9d8dd85f9a3f838938bdab13bef6c14edad", "repo_name": "KsenijaM/sympy", "path": "/sympy/tensor/tensor_fields.py", "length_bytes": 20858, "score": 3.65625, "int_score": 4, "content": "#-*- coding: utf-8 -*-\n\"\"\"\nModule tensor_fields contains functions for working with the tensor fields: \ncalculation of the differential and the gradient of the function, \ncurl and divergence of a vector field, \nthe calculation of the Li derivative and the external differentiation of differential forms. \nFunctions are work with the multidimensional arrays arraypy and tensors, \nclasses and methods which are contained in the module arraypy.\n\n\"\"\"\n\nfrom sympy.matrices import *\nfrom sympy.tensor.arraypy import *\nfrom sympy import Add,diff,symbols,simplify\nfrom sympy import sqrt\n\n# ---------------- df --------------------------------\n\ndef df(f,args,output_type='l'):\n \"\"\" \n Returns the 1-form df, differential of function f(x).\n\n Examples:\n ========\n\n >>> from sympy import *\n >>> from sympy.tensor.arraypy import *\n >>> from sympy.tensor.tensor_fields import *\n >>> x1, x2, x3, a= symbols('x1 x2 x3 a')\n >>> args=[x1, x2, x3]\n >>> f=x1**2*x2+sin(x2*x3-x2)\n >>> D=df(f,args,'t') \n >>> print D\n 2*x1*x2 x1**2 + (x3 - 1)*cos(x2*x3 - x2) x2*cos(x2*x3 - x2)\n \"\"\"\n# Handling of a vector of arguments\n if not isinstance(args, (list,tensor,arraypy)):\n\t raise TypeError('The type of vector of arguments must be list, Tensor or arraypy')\n if isinstance(args, (tensor,arraypy)):\n\t if len(args.shape)!=1:\n\t\t raise ValueError(\"The dimension of argument must be 1\")\n\t if isinstance(args,tensor):\n\t\t if args.type_pq != (1,0):\n\t\t\t raise ValueError('The valency(ind_char) of tensor must be (+1)') \t\t\n\t idx=args.start_index[0] \n if isinstance(args, list):\n\t idx=0\n\t\n# Creating the output array in accordance with start indexes\n n=len(args) \n array=arraypy([1,n,idx])\n indices = range(idx,idx+n)\n \n# Calculation\n for k in indices:\n\t array[k]=diff(f,args[k])\n \n# Handling of an output array\n if output_type=='t' or output_type==Symbol('t'):\n\t differential=arraypy.To_tensor(array,-1)\n elif output_type=='a' or output_type==Symbol('a'):\n\t differential=array\n elif output_type=='l' or output_type==Symbol('l'):\n\t differential=arraypy.To_list(array)\n else:\n\t raise TypeError(\"The third arguments must be 't'-tensor,'a'-massiv arraypy,'l'-list\")\n# Output \n return differential \n\n# ---------------- grad --------------------------------\n\ndef grad(f,args,g=None,output_type=None):\n \"\"\"\n Returns the vector field Gradient(f(x)) of a function f(x). \n\n Examples:\n ========\n\n >>> from sympy import *\n >>> from sympy.tensor.arraypy import *\n >>> from sympy.tensor.tensor_fields import *\n >>> x1, x2, x3, a= symbols('x1 x2 x3 a')\n >>> args=[x1, x2, x3]\n >>> f=x1**2*x2+sin(x2*x3-x2)\n >>> g=Matrix([[2,1,0],[1,3,0],[0,0,1]]) \n >>> Gr=grad(f,args,g) \n >>> print Gr\n -x1**2/5 + 6*x1*x2/5 - (x3 - 1)*cos(x2*x3 - x2)/5 2*x1**2/5 - 2*x1*x2/5 + 2*(x3 - 1)*cos(x2*x3 - x2)/5 x2*cos(x2*x3 - x2) \n \"\"\"\n# Handling of a vector of arguments\n if not isinstance(args, (list,tensor,arraypy)):\n\t raise TypeError('The type of vector of arguments must be list, tensor or arraypy')\n if isinstance(args, (tensor,arraypy)):\n\t if len(args.shape)!=1:\n\t\t raise ValueError(\"The dimension of argument must be 1\")\n\t if isinstance(args,tensor):\n\t\t if args.type_pq != (1,0):\n\t\t\t raise ValueError('The valency of tensor must be (+1)')\t \n\t idx_args=args.start_index[0]\n if isinstance(args, list):\n\t idx_args=0\n\t \n# Handling of the metric tensor\n # 1. if g is not NULL\n if g is not None:\n\t if output_type is None:\n\t\t output_type='t'\n\t if not isinstance(g,(tensor,Matrix,arraypy)):\n\t\t raise ValueError('Type must be Matrix or tensor or arraypy')\n\t if isinstance(g,tensor):\n\t\t if g.type_pq != (0,2):\n\t\t\t raise ValueError('The indices of tensor must be (-1,-1)')\n\t\t\t\n #The definition of the start index\n\t if isinstance(g,Matrix):\n\t\t idx_st=0\n\t else:\n\t\t idx_st=g.start_index[0] \n\t if type(g)==type(args) and idx_st!=idx_args:\n\t\t raise ValueError('The start index of the metric tensor and vector of arguments must be equal')\n\t \n\t if isinstance(g,(tensor,arraypy)):\t \n\t\t g = g.To_matrix()\n\t if not g.is_symmetric():\n\t\t raise ValueError('The metric is not symmetric')\t\t \n # 2.if g is NULL\n else:\n # g - the identity matrix\n\t g=eye(len(args))\n\t idx_st=0\n\t \n# Creating the output array in accordance with start indexes\n n=len(args) \n array=arraypy([1,n,idx_st])\n indices = range(idx_st,idx_st+n)\n \n# Calculating\n g_inv=g.inv()\n if isinstance(args,(tensor,arraypy)):\n\t args=args.To_list() \n for i in indices:\n\t for j in indices:\t\t\n\t\t array[i]+=(g_inv[i-idx_st,j-idx_st]*diff(f,args[j-idx_st]))\n\t\t \n# Handling of an output array\n if output_type=='t' or output_type==Symbol('t'):\n\t gradient=arraypy.To_tensor(array,1)\n elif output_type=='a' or output_type==Symbol('a'):\n\t gradient=array\n elif output_type=='l' or output_type==Symbol('l') or output_type is None:\n\t gradient=arraypy.To_list(array)\n else:\n\t raise TypeError(\"The third arguments must be 't'-tensor,'a'-massiv arraypy,'l'-list\")\n# Output \n return gradient \n\n# ---------------- rot --------------------------------\n \ndef rot(X,args,output_type=None):\n \"\"\"\n Returns the vorticity vector field rot(X) of a vector field X in R^3 (curl, rotation, rotor, vorticity). The rotor can be calculated for only in three-dimensional Euclidean space. \n \n Examples:\n ========\n \n >>> from sympy import *\n >>> from sympy.tensor.arraypy import *\n >>> from sympy.tensor.tensor_fields import *\n >>> x1, x2, x3, a= symbols('x1 x2 x3 a')\n >>> args=[x1, x2, x3]\n >>> X=[-x1**3+x2**2,9*x2**2+x1,5*x3+x2]\n >>> g=Matrix([[2,1,0],[1,3,0],[0,0,1]]) \n >>> R=rot(X,arg) \n >>> print R\n [1, 0, -2*x2 + 1]\n \"\"\"\n# Handling of a vector of arguments\n if not isinstance(args, (list,tensor,arraypy)):\n\t raise ValueError('The type of arguments vector must be list, tensor or arraypy')\n if len(args)!=3:\n\t raise ValueError('ERROW:three variables are required')\n if isinstance(args, (tensor,arraypy)):\n\t if len(args.shape)!=1:\n\t\t raise ValueError(\"The lenght of argument must be 1\")\t \n\t if isinstance(args,tensor):\n\t\t if args.type_pq != (1,0):\n\t\t\t raise ValueError('The valency of tensor must be (+1)') \t\t\n\t idx_args=args.start_index[0]\n if isinstance(args, list):\n\t idx_args=0\n\t \n# Handling of a vector field\n if not isinstance(X, (list,tensor,arraypy)):\n\t raise ValueError('The type of vector fields must be list, tensor or arraypy')\t\n if len(X)!=3:\n\t raise ValueError('ERROW:a three-dimensional vector is necessary')\n\t\n if isinstance(X, (tensor,arraypy)):\n\t if len(X.shape)!=1:\n\t\t raise ValueError(\"The dim of argument must be 1\")\n\t if isinstance(X,tensor):\n\t\t out_t='t'\n\t\t if X.type_pq != (1,0):\n\t\t\t raise ValueError('The valency of tensor must be (+1)') \t\t\n\t idx_X=X.start_index[0]\n elif isinstance(X, list):\n\t idx_X=0\n\t out_t='l'\n\t \n if output_type is None:\n\t if out_t is not None:\n\t\t output_type=out_t\n\t else:\n\t\t output_type='a'\n\t\t \t \n# The definition of the start index\n if type(X)==type(args) and (idx_X!=idx_args):\n\t raise ValueError('The start index of vector field and vector of arguments must be equal') \n idx_st=idx_X\n \n# Creating the output array in accordance with start indexes\n array=arraypy([1,3,idx_st])\n\n# Calculation\n if isinstance(X, (tensor,arraypy)):\n\t X=X.To_list()\n if isinstance(args, (tensor,arraypy)):\n\t args=args.To_list()\n\t \n array[idx_st]=(diff(X[2],args[1])-diff(X[1],args[2]))\n array[idx_st+1]=diff(X[0],args[2])-diff(X[2],args[0])\n array[idx_st+2]=diff(X[1],args[0])-diff(X[0],args[1])\n\n \n# Handling of an output array\n if output_type=='t' or output_type==Symbol('t'):\n\t rotor=arraypy.To_tensor(array,1)\n elif output_type=='a' or output_type==Symbol('a'):\n\t rotor=array\n elif output_type=='l' or output_type==Symbol('l'):\n\t rotor=arraypy.To_list(array)\n else:\n\t raise TypeError(\"The third arguments must be 't'-tensor,'a'-massiv arraypy,'l'-list\") \n# Output \n return rotor\n# ---------------- div --------------------------------\n\ndef div(X,args,g=None):\n \"\"\" \n Returns the divergence of a vector field X.\n\n Examples: \n ========\n \n >>> from sympy import *\n >>> from sympy.tensor.arraypy import *\n >>> from sympy.tensor.tensor_fields import *\n >>> x1, x2, x3, a= symbols('x1 x2 x3 a')\n >>> args=[x1, x2, x3]\n >>> X=[-x1**3+x2**2,9*x2**2+x1,5*x3+x2]\n >>> g=Matrix([[2,1,0],[1,3,0],[0,0,1]]) \n >>> D=div(X,args,g) \n >>> print D\n -3*x1**2 + 18*x2 + 5\n \"\"\"\n# Handling of a vector of arguments\n if not isinstance(args, (list,tensor,arraypy)):\n\t raise ValueError('The type of arguments vector must be list, tensor or arraypy')\n if isinstance(args, (tensor,arraypy)):\n\t if len(args.shape)!=1:\n\t\t raise ValueError(\"The lenght of argument must be 1\")\t \n\t if isinstance(args,tensor):\n\t\t if args.type_pq != (1,0):\n\t\t\t raise ValueError('The valency of tensor must be (+1)')\n\t args=args.To_list()\n\t\t \n# Handling of a vector field\n if not isinstance(X, (list,tensor,arraypy)):\n\t raise ValueError('The type of vector fields must be list, tensor or arraypy')\t \n if isinstance(X, (tensor,arraypy)):\n\t if len(X.shape)!=1:\n\t\t raise ValueError(\"The dim of argument must be 1\")\n\t if isinstance(X,tensor):\n\t\t if X.type_pq != (1,0):\n\t\t\t raise ValueError('The valency of tensor must be (+1)') \t\t\n\t X=X.To_list()\n\t \n# Handling of the metric tensor \n if g is not None:\n\t if not isinstance(g,(tensor,Matrix,arraypy)):\n\t\t raise ValueError('Type must be Matrix or tensor or arraypy')\n\t else:\n\t\t if isinstance(g,(tensor,arraypy)):\n\t\t\t if isinstance(g,tensor):\n\t\t\t\t if g.type_pq != (0,2):\n\t\t\t\t\t raise ValueError('The indices of tensor must be (-1,-1)')\n\t\t\t g = g.To_matrix()\n\t\t if not g.is_symmetric():\n\t\t\t raise ValueError('The metric is not symmetric')\n else:\n\t g=eye(len(args)) \n\t\t \n#Calculation\n sq=sqrt(abs(Matrix.det(g)))\n divergenc=0\n for k in range(len(args)):\n\t divergenc += simplify(1/sq*sum([diff(X[k]*sq,args[k])]))\t\n# Output \n return divergenc \n\n\n#------------------LieXY-------------------------------\n\ndef LieXY(X,Y,args,output_type=None):\n \"\"\" \n Returns the vector field [X,Y], Lie bracket (commutator) of a vector fields X and Y\n\t\n Examples: \n =========\n \n >>> from sympy import *\n >>> from sympy.tensor.arraypy import *\n >>> from sympy.tensor.tensor_fields import *\n >>> x1, x2, x3, a= symbols('x1 x2 x3 a')\n >>> args=[x1, x2, x3]\n >>> X=[-x1**3+x2**2,9*x2**2+x1,5*x3+x2]\n >>> Y=[-x1**3+x3**2,x2**2+x1**2,x3+x2]\n >>> L=LieXY(X,Y,args) \n >>> print L\n [-3*x1**2*(-x1**3 + x2**2) + 3*x1**2*(-x1**3 + x3**2) - 2*x2*(x1**2 + x2**2) + 2*x3*(x2 + 5*x3), x1**3 + 2*x1*(-x1**3 + x2**2) + 2*x2*(x1 + 9*x2**2) - 18*x2*(x1**2 + x2**2) - x3**2, -x1**2 + x1 + 8*x2**2 - 4*x2]\n \"\"\"\n# Handling of a vector of arguments\n if not isinstance(args, (list,tensor,arraypy)):\n\t raise ValueError('The type of arguments vector must be list, tensor or arraypy')\n if isinstance(args, (tensor,arraypy)):\n\t if len(args.shape)!=1:\n\t\t raise ValueError(\"The lenght of argument must be 1\")\t \n\t if isinstance(args,tensor):\n\t\t if args.type_pq != (1,0):\n\t\t\t raise ValueError('The valency of tensor must be (+1)') \t\t\n\t idx_args=args.start_index[0]\n if isinstance(args, list):\n\t idx_args=0 \n\t \n# Handling of the first vector field\n if not isinstance(X, (list,tensor,arraypy)):\n\t raise ValueError('The type of vector fields must be list, tensor or arraypy')\t \n if isinstance(X, (tensor,arraypy)):\n\t if len(X.shape)!=1:\n\t\t raise ValueError(\"The dim of argument must be 1\")\n\t if isinstance(X,tensor):\n\t\t out_t='t'\n\t\t if X.type_pq != (1,0):\n\t\t\t raise ValueError('The valency of tensor must be (+1)') \t\t\n\t idx_X=X.start_index[0]\n if isinstance(X, list):\n\t idx_X=0 \n\t out_t='l'\n\t\n# Handling of the second vector field\n if not isinstance(Y, (list,tensor,arraypy)):\n\t raise ValueError('The type of vector fields must be list, tensor or arraypy')\t \n if isinstance(Y, (tensor,arraypy)):\n\t if len(Y.shape)!=1:\n\t\t raise ValueError(\"The dim of argument must be 1\")\n\t if isinstance(Y,tensor):\n\t\t if Y.type_pq != (1,0):\n\t\t\t raise ValueError('The valency of tensor must be (+1)') \t\t\n\t idx_Y=Y.start_index[0]\n if isinstance(Y, list):\n\t idx_Y=0\t\n\t \n if len(Y)!=len(X):\n\t raise ValueError('The different number of arguments of the vector fields')\n elif len(args)!=len(X) or len(args)!=len(Y):\n\t raise ValueError('The different number of components at the vector field and vector of variables') \n \n# Define the start index in the output tensor\n if type(Y)==type(X)==type(args):\n\t if idx_Y!=idx_X or idx_Y!=idx_args or idx_X!=idx_args:\n\t\t raise ValueError('The start index of vector fields and vetcor of argements must be equal')\n if idx_Y!=idx_X:\n\t\t raise ValueError('The start index of tensor and the vector field must be equal')\n idx_st=idx_Y \n \n if output_type is None:\n\t if out_t is not None:\n\t\t output_type=out_t\n\t else:\n\t\t output_type='a'\n \n# Creating the output array in accordance with start indexes\n Li=arraypy([1,len(X),idx_st])\n \n# Calculating\n if isinstance(Y, (tensor,arraypy)):\n\t Y=Y.To_list()\n if isinstance(X, (tensor,arraypy)):\n\t X=X.To_list()\t\n if isinstance(args, (tensor,arraypy)):\n\t args=args.To_list() \n \n if X==Y:\n\t return 0\n else:\n\t indices = range(len(args))\n\t for i in indices:\n\t\t for k in indices:\n\t\t\t Li[i+idx_st]+=Add(diff(Y[i],args[k])*X[k]-diff(X[i],args[k])*Y[k])\t \n\t\t\t \n# Handling of an output array\n if output_type=='t' or output_type==Symbol('t'):\n\t Lie=arraypy.To_tensor(Li,1)\n elif output_type=='a' or output_type==Symbol('a'):\n\t Lie=Li\n elif output_type=='l' or output_type==Symbol('l'):\n\t Lie=arraypy.To_list(Li)\n else:\n\t raise TypeError(\"The third arguments must be 't'-tensor,'a'-massiv arraypy,'l'-list\") \n\t \n# Output \n return Lie\n\n\n# ---------------- NotNeedElement --------------------------------\n\ndef NotNeedElement (_list, index):\n\t\"\"\"The function returns a tuple containing the remainder of the input list \n\tafter you remove the element at the specified index.\n\t\"\"\"\n\tres = []\n\tfor i in range(len(_list)):\n\t\tif i != index:\n\t\t\tres.append((_list[i]))\n\treturn (tuple(res))\n\n\n# ---------------- dw --------------------------------\ndef dw(omega, args):\n \"\"\" \n Returns the exterior differential of a differential form\n\n Examples: \n =========\n \n >>> from sympy import *\n >>> from sympy.tensor.arraypy import *\n >>> from sympy.tensor.tensor_fields import *\n >>> x1, x2, x3, a= symbols('x1 x2 x3 a')\n >>> args=[x1, x2, x3]\n >>> om=arraypy((3,3))\n >>> omega = tensor(om, (-1, -1))\n >>> omega[0,1]=x3*x2\n >>> omega[1,0]=-x3*x2\n >>> omega[0,2]=-x2*x1 \n >>> omega[2,0]=x2*x1 \n >>> omega[1,2]=x1*x3\n >>> omega[2,1]=-x1*x3\n >>> d_omega = dw(omega, args) \n >>> print(d_omega)\n 0 0 0 \n 0 0 x1 + x2 + x3 \n 0 -x1 - x2 - x3 0 \n 0 0 -x1 - x2 - x3 \n 0 0 0 \n x1 + x2 + x3 0 0 \n 0 x1 + x2 + x3 0 \n -x1 - x2 - x3 0 0 \n 0 0 0\n \"\"\"\n# Handling of a vector of arguments\n if not isinstance(args, (list,tensor,arraypy)):\n\t raise ValueError('The type of arguments vector must be list, tensor or arraypy')\n if isinstance(args, (tensor,arraypy)):\n\t if len(args.shape)!=1:\n\t\t raise ValueError(\"The lenght of argument must be 1\")\t \n\t if isinstance(args,tensor):\n\t\t if args.type_pq != (1,0):\n\t\t\t raise ValueError('The valency of tensor must be (+1)') \t\t\n\t idx_args=args.start_index[0]\n if isinstance(args, list):\n\t idx_args=0\n\n# Handling of a differential form\n if not isinstance(omega, (tensor,arraypy)):\n\t raise ValueError(\"Type must be Tensor or arraypy\") \n idx_omega = omega.start_index[0]\n \n# Define the start index in the output tensor\n if type(omega)==type(args) and idx_omega!=idx_args:\n\t\t raise ValueError(\"Raznie indeksi!!!\")\t\t \n idx_st=idx_omega\n\n# Creating the output array in accordance with start indexes\n n=omega.shape[0] #the dimensionality of the input array\n p=len(omega.shape) #the rank of the input array\n a=arraypy([p+1,n,idx_st])\n valence_ind=[(-1) for k in range(p+1)]\n d_omega=a.To_tensor(valence_ind)\n \n# Calculation\n idx=d_omega.start_index \n if isinstance(args, (tensor,arraypy)):\n\t args=args.To_list()\n\t\t\n for i in range(len(d_omega)):\n\t #list of tuple. example:[(0, 1), (0, 1), (0, 0)]\n\t tuple_list_indx = [NotNeedElement(idx, f) for f in range(len(idx))]\t \n\t for k in range(p+1):\n\t\t d_omega[idx]+=Add(((-1)**k)*diff(omega[tuple_list_indx[k]],args[idx[k]-idx_st]))\n\t idx = d_omega.Next_index(idx)\n\t \n# Output \n return d_omega\n\n# ---------------- NeedElementK --------------------------------\n\ndef NeedElementK (_list, index,k):\n \"\"\"\n The function replaces the item \"index\" on the element \"k\". \n The result is a tuple.\n \"\"\"\n output = []\n for i in range(len(_list)):\n\t if i != index:\n\t\t output.append((_list[i])) \n\t else:\n\t\t output.append(k) \n return (tuple(output))\n\n\n# ---------------- Lie_omega --------------------------------\n\ndef Lie_w(omega, X, args):\n \"\"\"\n Returns the Lie derivative of a differential form \n\n Examples: \n =========\n \n >>> from sympy import *\n >>> from sympy.tensor.arraypy import *\n >>> from sympy.tensor.tensor_fields import *\n >>> x1, x2, x3, a= symbols('x1 x2 x3 a')\n >>> args=[x1, x2, x3]\n >>> X=[1,2,3]\n >>> om=arraypy((3,3))\n >>> omega = tensor(om, (-1, -1))\n >>> omega[0,1]=x3*x2\n >>> omega[1,0]=-x3*x2\n >>> omega[0,2]=-x2*x1 \n >>> omega[2,0]=x2*x1 \n >>> omega[1,2]=x1*x3\n >>> omega[2,1]=-x1*x3\n >>> LwX=Lie_w(omega,X,args) \n >>> print(LwX)\n 0 3*x2 + 2*x3 -2*x1 - x2 \n -3*x2 - 2*x3 0 3*x1 + x3 \n 2*x1 + x2 -3*x1 - x3 0 \n \"\"\"\n# Handling of a vector of arguments\n if not isinstance(args, (list,tensor,arraypy)):\n\t raise ValueError('The type of arguments vector must be list, tensor or arraypy')\n if isinstance(args, (tensor,arraypy)):\n\t if len(args.shape)!=1:\n\t\t raise ValueError(\"The lenght of argument must be 1\")\t \n\t if isinstance(args,tensor):\n\t\t if args.type_pq != (1,0):\n\t\t\t\traise ValueError('The valency of tensor must be (+1)') \t\t\n\t idx_args=args.start_index[0]\n if isinstance(args, list):\n\t\tidx_args=0\n\n# Handling of a vector field\n if not isinstance(X, (list,tensor,arraypy)):\n\t raise ValueError('The type of vector fields must be list, tensor or arraypy')\t \n if isinstance(X, (tensor,arraypy)):\n\t if len(X.shape)!=1:\n\t\t raise ValueError(\"The dim of argument must be 1\")\n\t if isinstance(X,tensor):\n\t\t if X.type_pq != (1,0):\n\t\t\t raise ValueError('The valency of tensor must be (+1)') \t\t\n\t idx_X=X.start_index[0]\n if isinstance(X, list):\n\t\tidx_X=0\n\t\t\n# Handling of a differential form\n if not isinstance(omega, (tensor,arraypy)):\n\t raise ValueError(\"Type must be Tensor or arraypy\") \n idx_omega = omega.start_index[0]\t\n\n\n#Define the start index in the output tensor\n if type(omega)==type(X)==type(args):\n\t if idx_omega!=idx_X or idx_omega!=idx_args or idx_X!=idx_args:\n\t\t raise ValueError('The start index of tensor,vector field and vetcor of argements must be equal')\n if type(omega)==type(X) and idx_omega!=idx_X:\n\t\t raise ValueError('The start index of tensor and vector field must be equal')\n idx_st=idx_omega\n\n#Creating the output array in accordance with start indexes\n n=omega.shape[0] # the dimensionality of the input array\n r=len(omega.shape) # the rank of the input array\n a=arraypy([r,n,idx_st])\n valence_list=[(-1) for k in range(r)]\n diff_Lie=a.To_tensor(valence_list)\n\t \n# Calculation\n idx = diff_Lie.start_index\n if isinstance(args,(tensor,arraypy)):\n\t args=args.To_list()\n if isinstance(X,(tensor,arraypy)):\n\t X=X.To_list()\n\t\t\n for p in range(len(diff_Lie)):\n\tfor k in range(len(idx)+1):\t\t\t \n\t\ttuple_list_indx = [NeedElementK(idx, f, k+idx_st) for f in range(len(idx))]\n\t\tdiff_omega=diff(omega[idx],args[k])*X[k]\n\t\tfor j in range(len(idx)):\n\t\t\tdiff_Lie[idx]+=diff(X[k],args[idx[j]-idx_st])*omega[tuple_list_indx[j]]\n\t\tdiff_Lie[idx]=diff_Lie[idx]+diff_omega\t\t \n\tidx = diff_Lie.Next_index(idx)\n# Output\n return diff_Lie\n\n"} {"blob_id": "e3ee965a1e35069eaa7b73ce79a2a324fe3ff381", "repo_name": "kesarb/leetcode-summary-python", "path": "/practice/a/min_cost_to_connect_ropes.py", "length_bytes": 1786, "score": 4.125, "int_score": 4, "content": "\"\"\" Min Cost to Connect Ropes\n\nhttps://leetcode.com/problems/minimum-cost-to-connect-sticks (premium)\n\nGiven n ropes of different lengths, we need to connect these ropes into one rope. \nWe can connect only 2 ropes at a time. The cost required to connect 2 ropes is \nequal to sum of their lengths. The length of this connected rope is also equal \nto the sum of their lengths. This process is repeated until n ropes are connected \ninto a single rope. Find the min possible cost required to connect all ropes.\n\nAuthor: Weikun Han \n\nReference: https://leetcode.com/discuss/interview-question/344677\n\nTime complexity: O(nlogn)\nSpace complexity: O(n)\n\nExample 1:\nInput: \nropes = [8, 4, 6, 12]\nOutput: \n58\nExplanation: The optimal way to connect ropes is as follows\n1. Connect the ropes of length 4 and 6 (cost is 10). Ropes after connecting: [8, 10, 12]\n2. Connect the ropes of length 8 and 10 (cost is 18). Ropes after connecting: [18, 12]\n3. Connect the ropes of length 18 and 12 (cost is 30).\nTotal cost to connect the ropes is 10 + 18 + 30 = 58\n\nExample 2:\nInput: \nropes = [20, 4, 8, 2]\nOutput: \n54\n\nExample 3:\nInput: \nropes = [1, 2, 5, 10, 35, 89]\nOutput: \n224\n\"\"\"\n\nimport heapq\n\nclass Solution(object):\n def min_cost_to_conneect_ropes(self, ropes):\n \"\"\"\n :type ropes: List[int]\n :rtype: int\n \"\"\"\n\n value_pq = ropes\n heapq.heapify(value_pq)\n res = 0\n\n while len(value_pq) > 1:\n temp_value = heapq.heappop(value_pq) + heapq.heappop(value_pq)\n res += temp_value\n heapq.heappush(value_pq, temp_value)\n\n return res\n\ndef main():\n ropes = [8, 4, 6, 12]\n solution = Solution()\n res = solution.min_cost_to_conneect_ropes(ropes)\n print(res)\n\nif __name__ == \"__main__\": \n main()"} {"blob_id": "62d062f3dd1dbc7f50d046945e13450f6e70499f", "repo_name": "anna-droid-beep/data-structures", "path": "/tests/BinarySearchTree/TestBinarySearchTree.py", "length_bytes": 5212, "score": 3.5, "int_score": 4, "content": "import unittest\nfrom BinarySearchTree.BinarySearchTree import BinarySearchTree, Node\nfrom BinarySearchTree.TreeTraversalOrder import TreeTraversalOrder\n\nclass MockBST:\n\n def __init__(self):\n # With Level-Order/BFS printing, the BST is 3, 1, 5, 2, 4, 7, 8\n root_1 = Node(3)\n root_1.left = Node(1, left=None, right=Node(2))\n root_1.right = Node(5, left=Node(4), right=Node(7, left=Node(6), right=Node(8)))\n self.bst_1 = BinarySearchTree(root=root_1, node_count=8)\n\n # With Level-Order/BFS printing, the BST is 5, 4, 3\n root_2 = Node(5, left=Node(4, left=Node(3)))\n self.bst_2 = BinarySearchTree(root=root_2, node_count=3)\n\n self.bst_3 = BinarySearchTree()\n\n\nclass TestBinarySearchTree(unittest.TestCase):\n\n def test_add(self):\n cases = [(9, True, 9), (0, True, 9), (1, False, 8), (2, False, 8)]\n\n for elem, exp_add, exp_size in cases:\n with self.subTest(elem=elem, exp_add=exp_add, exp_size=exp_size):\n mock_bst = MockBST()\n act_add = mock_bst.bst_1.add(elem)\n actual_size = mock_bst.bst_1.node_count\n self.assertEqual(act_add, exp_add)\n self.assertEqual(actual_size, exp_size)\n\n def test_remove(self):\n cases = [(3, True, 7), (1, True, 7), (5, True, 7), (9, False, 8)]\n\n for elem, exp_remove, exp_size in cases:\n with self.subTest(elem=elem, exp_remove=exp_remove, exp_size=exp_size):\n mock_bst = MockBST()\n act_remove = mock_bst.bst_1.remove(elem)\n actual_size = mock_bst.bst_1.node_count\n self.assertEqual(act_remove, exp_remove)\n self.assertEqual(actual_size, exp_size)\n\n def test_contains(self):\n cases = [(0, False), (1, True), (2, True), (3, True),\n (9, False), (10, False)]\n bst = MockBST().bst_1\n\n for elem, exp_exists in cases:\n with self.subTest(elem=elem, exp_exists=exp_exists):\n act_exists = bst.contains(elem)\n self.assertEqual(act_exists, exp_exists)\n\n def test_isEmpty(self):\n mock_bst = MockBST()\n cases = [(mock_bst.bst_1, False), (mock_bst.bst_2, False), (mock_bst.bst_3, True)]\n\n for bst, exp_emptiness in cases:\n with self.subTest(bst=str(bst), exp_emptiness=exp_emptiness):\n act_emptiness = bst.is_empty()\n self.assertEqual(act_emptiness, exp_emptiness)\n\n def test_getSize(self):\n mock_bst = MockBST()\n cases = [(mock_bst.bst_1, 8), (mock_bst.bst_2, 3), (mock_bst.bst_3, 0)]\n\n for bst, exp_size in cases:\n with self.subTest(bst=str(bst), exp_size=exp_size):\n act_size = bst.get_size()\n self.assertEqual(act_size, exp_size)\n\n def test_traverse(self):\n mock_bst = MockBST()\n\n cases = [(mock_bst.bst_1, TreeTraversalOrder.LEVEL_ORDER, \"{ 3 1 5 2 4 7 6 8 }\"),\n (mock_bst.bst_1, TreeTraversalOrder.PRE_ORDER, \"{ 3 1 2 5 4 7 6 8 }\"),\n (mock_bst.bst_1, TreeTraversalOrder.IN_ORDER, \"{ 1 2 3 4 5 6 7 8 }\"),\n (mock_bst.bst_1, TreeTraversalOrder.POST_ORDER, \"{ 2 1 4 6 8 7 5 3 }\"),\n (mock_bst.bst_2, TreeTraversalOrder.LEVEL_ORDER, \"{ 5 4 3 }\"),\n (mock_bst.bst_2, TreeTraversalOrder.PRE_ORDER, \"{ 5 4 3 }\"),\n (mock_bst.bst_2, TreeTraversalOrder.IN_ORDER, \"{ 3 4 5 }\"),\n (mock_bst.bst_2, TreeTraversalOrder.POST_ORDER, \"{ 3 4 5 }\"),\n (mock_bst.bst_3, TreeTraversalOrder.LEVEL_ORDER, '{ }'),\n (mock_bst.bst_3, TreeTraversalOrder.PRE_ORDER, '{ }'),\n (mock_bst.bst_3, TreeTraversalOrder.IN_ORDER, '{ }'),\n (mock_bst.bst_3, TreeTraversalOrder.POST_ORDER, '{ }')]\n\n for bst, strategy, exp_order in cases:\n with self.subTest(bst=str(bst), strategy=strategy, exp=exp_order):\n act_bfs = bst.traverse(strategy)\n self.assertEqual(act_bfs, exp_order)\n\n def test_height(self):\n mock_bst = MockBST()\n cases = [(mock_bst.bst_1, 4), (mock_bst.bst_2, 3), (mock_bst.bst_3, 0)]\n for bst, exp_height in cases:\n with self.subTest(bst=str(bst), exp_height=exp_height):\n act_height = bst.height()\n self.assertEqual(act_height, exp_height)\n\n def test_integration(self):\n bst = BinarySearchTree()\n self.assertTrue(bst.is_empty())\n\n bst.add(\"A\")\n self.assertTrue(bst.contains(\"A\"))\n self.assertEqual(str(bst), \"{ A }\")\n\n bst.add(\"Z\")\n bst.add(\"D\")\n bst.add(\"E\")\n bst.add(\"K\")\n self.assertEqual(bst.get_size(), 5)\n self.assertEqual(str(bst), \"{ A Z D E K }\")\n\n bst.remove(\"A\")\n self.assertEqual(bst.get_size(), 4)\n self.assertEqual(str(bst), \"{ Z D E K }\")\n\n bst.add(\"ZOO\")\n bst.add(\"ZEBRA\")\n self.assertEqual(bst.get_size(), 6)\n self.assertEqual(str(bst), \"{ Z D ZOO E ZEBRA K }\")\n\n bst.remove(\"Z\")\n self.assertEqual(bst.get_size(), 5)\n self.assertEqual(str(bst), \"{ ZEBRA D ZOO E K }\")\n"} {"blob_id": "e5116daf8aaf84022c85b49fed776a3764d7b197", "repo_name": "KevinKnott/Coding-Review", "path": "/Month 03/Week 01/Day 07/c.py", "length_bytes": 2325, "score": 3.984375, "int_score": 4, "content": "# Reverse Nodes in k-Group: https://leetcode.com/problems/reverse-nodes-in-k-group/\n\n# Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.\n# k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.\n# You may not alter the values in the list's nodes, only nodes themselves may be changed.\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n\n# So for this problem I think that all we have is our classic reversal problem except\n# we need to use recursion after every time we reverse so that we can swap every k nodes\n\n\nclass Solution:\n def reverseKGroup(self, head, k: int):\n # we need to find out if there are k nodes to swap\n count = 0\n cur = head\n while cur and count < k:\n cur = cur.next\n count += 1\n\n if count == k:\n # then we swap from head to k\n newHead = self.reverse(head, k)\n\n # and keep the cur which be at the end of the reversal and only the unprocessed values and our tail will be head\n # we will then call reverseKgroup for head.next (we use cur as the next spot)\n head.next = self.reverseKGroup(cur, k)\n return newHead\n\n return head\n\n # Basic reversal\n\n def reverse(self, head, k):\n prev, cur = None, head\n\n for _ in range(k):\n temp = cur.next\n cur.next = prev\n prev = cur\n cur = temp\n\n return prev\n\n\n# This problem takes a bit of thinking but isn't too hard. I highly advise drawing out this problem as it really does help quite a bit\n# The reversal isn't too complicated but thinking of how the values change is hard otherwise\n\n# The above runs in O(N) and uses o(N/K) space for the stack. I think there is probably an optimization of this problem where\n# we dont have recursion but I think it would be rather complicated.\n\n# Score Card\n# Did I need hints? Nope\n# Did you finish within 30 min? 10 min\n# Was the solution optimal? Optimal for time not space. I don't have a lot of time today\n# Were there any bugs? None\n# 5 5 3 5 = 4.5\n"} {"blob_id": "78d599cca1135c44f290a7286b47d4694e41ec0b", "repo_name": "xBDL/udacity", "path": "/ud953/1.10.py", "length_bytes": 877, "score": 4.0, "int_score": 4, "content": "# -*- coding: utf-8 -*-\n# Lesson 1: Vectors\n# Module 10: Quiz 4 (Parallel, Orthogonal)\n\nfrom vector import Vector\n\n# Problem 1 (parallel/orthogonal)\nv = Vector([-7.579, \n -7.880])\nw = Vector([22.737, \n 23.640])\n\nprint(v.is_parallel(w))\nprint(v.is_orthogonal(w))\n\n\n# Problem 2 (parallel/orthogonal)\nv = Vector([-2.029,\n 9.970, \n 4.172])\nw = Vector([-9.231, \n -6.639,\n -7.245])\n\nprint(v.is_parallel(w))\nprint(v.is_orthogonal(w))\n\n\n# Problem 3 (parallel/orthogonal)\nv = Vector([-2.328,\n -7.284, \n -1.214])\nw = Vector([-1.821, \n 1.072,\n -2.940])\n\nprint(v.is_parallel(w))\nprint(v.is_orthogonal(w))\n\n\n# Problem 4 (parallel/orthogonal)\nv = Vector([ 2.118, \n 4.827])\nw = Vector([ 0.000, \n 0.000])\n\nprint(v.is_parallel(w))\nprint(v.is_orthogonal(w))\n"} {"blob_id": "fc57ae040d41ef7e9292af83a838ba616002a987", "repo_name": "yamau1/Forest-Fire-Detector", "path": "/ASB-Forest-Fire-Detector.py", "length_bytes": 6095, "score": 3.515625, "int_score": 4, "content": "# ASB #\r\n\r\nimport cv2 \r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\nfrom decimal import *\r\n\r\n#////////////////////Settings\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\r\n# A regular(non-fire) image at noon time of area for calibration:\r\ncalibrationImageURL = \"forest1.png\"\r\n# Fire or smoke check image:\r\ncheckImageURL = \"forest1burn1.png\"\r\n\r\nsmokeThreshold = 0.08 \t# Recommended value is around ~0.1 | ~0.08 \r\nfireThreshold = 0.1\t\t# Recommended value is around ~0.1 | ~0.08\r\n\r\nresizeImageWidth = 800\t# Recommended value is 800\r\nresizeImageHeight = 400\t# Recommended value is 400\r\n\r\nshowPlot = True\r\n#\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\Settings////////////////////\r\n\r\nprint(\"\\n########## ASB Forest Fire Detector ##########\\n\")\r\nprint(\"Calibration Image URL=\",calibrationImageURL)\r\nprint(\"Check Image URL=\",checkImageURL)\r\n\r\ndef skyFormulaRGB(threshold, inputImg, inputImgWidth, inputImgHeight): #calculates every pixel and sets white which has potential to be a pixel in the sky. others sets to black. \r\n\tfor x in range(inputImgWidth): #roam every pixel\r\n\t\tfor y in range(inputImgHeight):\r\n\t\t\tr = inputImg[y,x,2] #2:red\r\n\t\t\tg = inputImg[y,x,1] #1:green\r\n\t\t\tb = inputImg[y,x,0] #0:blue\r\n\t\t\tformula = 1*(int(r))+0.1*(int(g))+0.9*(int(b)) #give a value to each pixel respecting to a special formula\r\n\t\t\t#bigger threshold (threshold) value , generally more black pixels. bigger value=has more possibility to be a sky pixel. \r\n\t\t\tif ( formula > threshold ): #sky\r\n\t\t\t\tinputImg.itemset((y,x,2),255) #if its resulted as a sky pixel, set every channel value to 255 (white)\r\n\t\t\t\tinputImg.itemset((y,x,1),255) #0:blue , 1:green, 2:red\r\n\t\t\t\tinputImg.itemset((y,x,0),255)\r\n\t\t\telse: #ground\r\n\t\t\t\tinputImg.itemset((y,x,2),0) #if its resulted as a ground pixel, set every channel value to 0 (black)\r\n\t\t\t\tinputImg.itemset((y,x,1),0) #0:blue , 1:green, 2:red\r\n\t\t\t\tinputImg.itemset((y,x,0),0)\r\n\t\t\t\t\r\n\treturn inputImg\t#return modified image\t\r\n#________________________________________MAIN________________________________________\r\n\r\ncalibrationImg = cv2.imread(calibrationImageURL) # A regular(non-fire) image at noon time of area for calibration\r\ncheckImg = cv2.imread(checkImageURL) # Fire or smoke check image \r\n\r\n#\t\t\t\t cols(width),rows(height)\r\nresizedPlotImgCalibration = cv2.resize(calibrationImg, (resizeImageWidth, resizeImageHeight)) #resized calibration image for plotting\r\nresizedPlotImgCheck = cv2.resize(checkImg, (resizeImageWidth, resizeImageHeight)) #resized check image for plotting\r\nimg = cv2.resize(calibrationImg, (resizeImageWidth, resizeImageHeight)) #actual image to work on it\r\nskyExamination = cv2.resize(checkImg, (resizeImageWidth, resizeImageHeight)) \r\ngroundExamination = cv2.resize(checkImg, (resizeImageWidth, resizeImageHeight))\r\n#print (img.shape)\r\n\r\n#(threshold value,input image)\t\t\t\t\r\ninputImg = skyFormulaRGB(120, img, resizeImageWidth, resizeImageHeight) #bigger value,more black pixels.\r\n\r\nkernel = np.ones((5,5),np.uint8) #set kernel matrix size\r\n#**********SKY EXAMINATION (Disable Ground)**********\r\neroted = cv2.erode(inputImg,kernel,iterations = 15) #erote image to get rid of unwanted empty spaces\r\nfor x in range(resizeImageWidth): #roam every pixel\r\n\t\tfor y in range(resizeImageHeight):\r\n\t\t\tif(eroted[y,x,0]==0):\r\n\t\t\t\tskyExamination.itemset((y,x,2),255) #0:blue , 1:green, 2:red\r\n\t\t\t\tskyExamination.itemset((y,x,1),255)\r\n\t\t\t\tskyExamination.itemset((y,x,0),255)\r\n\t\t\t\t\r\nhsvSky = cv2.cvtColor(skyExamination, cv2.COLOR_BGR2HSV)\r\nlowerS = [0, 0, 2] #lower hsv limit (hue,saturation,value)\r\nupperS = [180, 20, 180] #upper hsv limit\r\nlowerS = np.array(lowerS, dtype=\"uint8\")\r\nupperS = np.array(upperS, dtype=\"uint8\")\r\nsmoke = cv2.inRange(hsvSky, lowerS, upperS) #set to white all smoke pixels\r\n\r\nfor x in range(resizeImageWidth): #set to black all ground pixels\r\n\t\tfor y in range(resizeImageHeight):\r\n\t\t\tif(eroted[y,x,0]==0):\r\n\t\t\t\tsmoke[y,x] = 0\r\n\r\n#**********GROUND EXAMINATION (Disable Sky)**********\r\ndilated = cv2.dilate(eroted,kernel,iterations = 20) \r\nfor x in range(resizeImageWidth): #roam every pixel\r\n\t\tfor y in range(resizeImageHeight):\r\n\t\t\tif(dilated[y,x,0]==255):\r\n\t\t\t\tgroundExamination.itemset((y,x,2),0) #0:blue , 1:green, 2:red\r\n\t\t\t\tgroundExamination.itemset((y,x,1),0)\r\n\t\t\t\tgroundExamination.itemset((y,x,0),0)\r\n\t\t\t\t\r\nhsvGround = cv2.cvtColor(groundExamination, cv2.COLOR_BGR2HSV)\r\nlowerG = [0, 150, 50] #lower hsv limit (hue,saturation,value) 18\r\nupperG = [20, 255, 255] #upper hsv limit 35\r\nlowerG = np.array(lowerG, dtype=\"uint8\")\r\nupperG = np.array(upperG, dtype=\"uint8\")\r\nfire = cv2.inRange(hsvGround, lowerG, upperG)\r\n\r\n#**********EXAM\u0130NATION RESULTS**********\r\n#*****SKY(Smoke)*****\r\nprint(\"\\n########## Examination Results ##########\")\r\nskyWhite = 0\r\nfor x in range(resizeImageWidth): #roam every pixel,search for white pixels (which indicates smoke)\r\n\t\tfor y in range(resizeImageHeight):\r\n\t\t\tif(smoke[y,x]==255):\r\n\t\t\t\tskyWhite += 1\r\n\t\t\t\t\r\nsmokeRate = skyWhite/320000 #400*800 = 320000\r\nprint(\"\\nSmoke ratio: \",smokeRate)\r\nif(smokeRate > smokeThreshold):\r\n\tprint('Possible Fire Thread In The Sky!')\r\nelse:\r\n\tprint(\"No Thread Detected In The Sky.\")\r\n\r\n#*****GROUND(Fire)*****\r\ngroundWhite = 0\r\nfor x in range(resizeImageWidth): #roam every pixel,search for white pixels (which indicates fire)\r\n\t\tfor y in range(resizeImageHeight):\r\n\t\t\tif(fire[y,x]==255):\r\n\t\t\t\tgroundWhite += 1\r\n\t\t\t\t\r\nfireRate = groundWhite/320000 #400*800 = 320000\r\nprint(\"\\nFlame ratio: \",fireRate)\r\nif(fireRate > fireThreshold):\r\n\tprint('Possible Fire Thread On The Ground!')\r\nelse:\r\n\tprint(\"No Thread Detected On The Ground.\")\r\n\r\n\r\n\r\n\r\n#**********PLOT**********\r\nif(showPlot == True):\r\n\ttitles = ['Calibration Image','Check Image','Masked w/skyformula','Sky Mask\\n(Masked+Eroted)','Sky Examination','Smoke(Sky)','Ground Mask\\n(Masked+Eroted+Dilated)','Ground Examination','Fire(Ground)']\r\n\timages = [resizedPlotImgCalibration, resizedPlotImgCheck, inputImg,eroted, skyExamination, smoke, dilated, groundExamination, fire]\r\n\tfor i in range(9):\r\n\t\tplt.subplot(3,3,i+1),plt.imshow(images[i],'gray')\r\n\t\tplt.title(titles[i])\r\n\t\tplt.xticks([]),plt.yticks([])\r\n\tplt.show()"} {"blob_id": "23b6e65092b8ecde57ea5c054afa9d1a0771cd89", "repo_name": "yasser-elbarbary/problem-solving", "path": "/graph_BFS.py", "length_bytes": 4074, "score": 4.40625, "int_score": 4, "content": "# Python program to find the shortest\n# path between a given source cell\n# to a destination cell.\n\nfrom collections import deque\nROW = None\nCOl = None\n\n\n# To store matrix cell coordinates\nclass Point:\n def __init__(self, x: int, y: int):\n self.x = x\n self.y = y\n\n # A data structure for queue used in BFS\n\n\nclass queueNode:\n def __init__(self, pt: Point, dist: int):\n self.pt = pt # The coordinates of the cell\n self.dist = dist # Cell's distance from the source\n\n\n# Check whether given cell(row,col)\n# is a valid cell or not\ndef isValid(row: int, col: int):\n # return (row >= 0) and (row < ROW) and (col >= 0) and (col < COL)\n\n\n# These arrays are used to get row and column\n# numbers of 4 neighbours of a given cell\n# locations :[up, left, right, down]\nrowNum = [-1, 0, 0, 1]\ncolNum = [0, -1, 1, 0]\n\n\n# Function to find the shortest path between\n# a given source cell to a destination cell.\ndef BFS(mat, src: Point, dest: Point):\n # check source and destination cell\n # of the matrix have value 1\n if mat[src.x][src.y] != 1 or mat[dest.x][dest.y] != 1:\n return -1\n\n visited = [[False for i in range(COL)] for j in range(ROW)]\n\n # Mark the source cell as visited\n visited[src.x][src.y] = True\n\n # Create a queue for BFS\n q = deque()\n\n # Distance of source cell is 0\n s = queueNode(src, 0)\n q.append(s) # Enqueue source cell\n\n # Do a BFS starting from source cell\n while q:\n\n curr = q.popleft() # Dequeue the front cell\n\n # If we have reached the destination cell,\n # we are done\n pt = curr.pt\n if pt.x == dest.x and pt.y == dest.y:\n return curr.dist\n\n # Otherwise enqueue its adjacent cells\n for i in range(4):\n row = pt.x + rowNum[i]\n col = pt.y + colNum[i]\n\n # if adjacent cell is valid, has path\n # and not visited yet, enqueue it.\n if (isValid(row, col) and mat[row][col] == 1 and not visited[row][col]):\n visited[row][col] = True\n Adjcell = queueNode(Point(row, col), curr.dist + 1)\n q.append(Adjcell)\n\n # Return -1 if destination cannot be reached\n return -1\n\n\n# Driver code\ndef main():\n mat = [[1, 0, 1, 1, 1, 1, 0, 1, 1, 1],\n [1, 0, 1, 0, 1, 1, 1, 0, 1, 1],\n [1, 1, 1, 0, 1, 1, 0, 1, 0, 1],\n [0, 0, 0, 0, 1, 0, 0, 0, 0, 1],\n [1, 1, 1, 0, 1, 1, 1, 0, 1, 0],\n [1, 0, 1, 1, 1, 1, 0, 1, 0, 0],\n [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],\n [1, 0, 1, 1, 1, 1, 0, 1, 1, 1],\n [1, 1, 0, 0, 0, 0, 1, 0, 0, 1]]\n source = Point(0, 0)\n dest = Point(3, 4)\n\n dist = BFS(mat, source, dest)\n\n if dist != -1:\n print(\"Shortest Path is\", dist)\n else:\n print(\"Shortest Path doesn't exist\")\n\n\nmain()\n\"\"\"\nfrom collections import deque\n\n\ndef is_valid_point(x, y):\n max_x = len(grid)\n max_y = len(grid[0])\n if x < 0 or x >= max_x or y < 0 or y >= max_y:\n return False\n return True\n\n\ndef shortestCellPath(grid, sr, sc, tr, tc):\n \"\"\"\n @param grid: int[][]\n @param sr: int\n @param sc: int\n @param tr: int\n @param tc: int\n @return: int\n \"\"\"\n\n\n q = deque()\n q.append([sr, sc, 0])\n seen = set()\n positions_to_look = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n while len(q):\n curr = q.popleft()\n seen.add((curr[0], curr[1]))\n \n if curr[0] == tr and curr[1] == tc:\n return curr[2]\n \n for each_position in positions_to_look:\n new_x = curr[0] + each_position[0]\n new_y = curr[1] + each_position[1]\n \n if is_valid_point(new_x, new_y) and grid[new_x][new_y] == 1 and (new_x, new_y) not in seen:\n q.append([new_x, new_y, curr[2] + 1])\n \n return -1\n\nif __name__ == \"__main__\":\n grid = [[1, 1, 1, 1], [0, 0, 0, 1], [1, 1, 1, 1]]\n sr = 0\n sc = 0\n tr = 2\n tc = 0\n print(shortestCellPath(grid, sr, sc, tr, tc))\n print(shortestCellPath(grid, sr, sc, tr, tc))\n\n\n\"\"\""} {"blob_id": "ee9031a339c7aa8aa70fdf391386dd5a37c15418", "repo_name": "zhou-jia-ming/leetcode-py", "path": "/problem_1162.py", "length_bytes": 2174, "score": 3.5, "int_score": 4, "content": "# coding:utf-8\n# Created by: Jiaming\n# Created at: 2020-03-29\n\n# \u4f60\u73b0\u5728\u624b\u91cc\u6709\u4e00\u4efd\u5927\u5c0f\u4e3a\u00a0N x N \u7684\u300e\u5730\u56fe\u300f\uff08\u7f51\u683c\uff09\u00a0grid\uff0c\n# \u4e0a\u9762\u7684\u6bcf\u4e2a\u300e\u533a\u57df\u300f\uff08\u5355\u5143\u683c\uff09\u90fd\u7528\u00a00\u00a0\u548c\u00a01\u00a0\u6807\u8bb0\u597d\u4e86\u3002\u5176\u4e2d\u00a00\u00a0\u4ee3\u8868\u6d77\u6d0b\uff0c1\u00a0\u4ee3\u8868\u9646\u5730\uff0c\n# \u4f60\u77e5\u9053\u8ddd\u79bb\u9646\u5730\u533a\u57df\u6700\u8fdc\u7684\u6d77\u6d0b\u533a\u57df\u662f\u662f\u54ea\u4e00\u4e2a\u5417\uff1f\u8bf7\u8fd4\u56de\u8be5\u6d77\u6d0b\u533a\u57df\u5230\u79bb\u5b83\u6700\u8fd1\u7684\u9646\u5730\u533a\u57df\u7684\u8ddd\u79bb\u3002\n#\n# \u6211\u4eec\u8fd9\u91cc\u8bf4\u7684\u8ddd\u79bb\u662f\u300e\u66fc\u54c8\u987f\u8ddd\u79bb\u300f\uff08\u00a0Manhattan Distance\uff09\uff1a(x0, y0) \u548c\u00a0(x1, y1)\u00a0\n# \u8fd9\u4e24\u4e2a\u533a\u57df\u4e4b\u95f4\u7684\u8ddd\u79bb\u662f\u00a0|x0 - x1| + |y0 - y1|\u00a0\u3002\n#\n# \u5982\u679c\u6211\u4eec\u7684\u5730\u56fe\u4e0a\u53ea\u6709\u9646\u5730\u6216\u8005\u6d77\u6d0b\uff0c\u8bf7\u8fd4\u56de\u00a0-1\u3002\n#\n# \u6765\u6e90\uff1a\u529b\u6263\uff08LeetCode\uff09\n# \u94fe\u63a5\uff1ahttps://leetcode-cn.com/problems/as-far-from-land-as-possible\n# \u8457\u4f5c\u6743\u5f52\u9886\u6263\u7f51\u7edc\u6240\u6709\u3002\u5546\u4e1a\u8f6c\u8f7d\u8bf7\u8054\u7cfb\u5b98\u65b9\u6388\u6743\uff0c\u975e\u5546\u4e1a\u8f6c\u8f7d\u8bf7\u6ce8\u660e\u51fa\u5904\u3002\n\nfrom typing import List\n\n\nclass Solution:\n def maxDistance(self, grid: List[List[int]]) -> int:\n # \u5e7f\u5ea6\u4f18\u5148\u904d\u5386\uff0c\u4ece\u9646\u5730\u51fa\u53d1\uff0c\u6700\u8fdc\u7684\u6d77\u6d0b\u5c31\u662f\u6700\u540e\u4e00\u6b65\u5f97\u5230\u7684\u3002\u8bb0\u5f55\u5faa\u73af\u6b21\u6570\u3002\n import numpy as np\n if len(set(np.array(grid).flatten())) == 1:\n return -1\n else:\n step = 0\n m = len(grid)\n n = len(grid[0])\n queue = []\n for x, line in enumerate(grid):\n for y, item in enumerate(line):\n if item == 1:\n queue.append([x, y])\n\n while len(set(np.array(grid).flatten())) != 1:\n new_queue = []\n for q in queue:\n for dx, dy in [[0, 1], [0, -1], [1, 0], [-1, 0]]:\n if 0 <= q[0] + dx < m and 0 <= q[1] + dy < n:\n if grid[q[0] + dx][q[1] + dy] == 0:\n grid[q[0] + dx][q[1] + dy] = 1\n new_queue.append([q[0] + dx, q[1] + dy])\n queue = new_queue\n step += 1\n return step\n\n\nif __name__ == \"__main__\":\n s = Solution()\n print(s.maxDistance([[1, 0, 1], [0, 0, 0], [1, 0, 1]]))\n print(s.maxDistance([[1, 0, 0], [0, 0, 0], [0, 0, 0]]))\n"} {"blob_id": "ad665e3a3bc934aff4d52b5afe591f313bb4fe03", "repo_name": "csaezcalvo/advent-of-code2018", "path": "/day 5-1.py", "length_bytes": 1271, "score": 3.71875, "int_score": 4, "content": "def inv(word):\n new_word=''\n for letter in word:\n if letter.lower() == letter:\n new_word += letter.upper()\n else:\n new_word += letter.lower()\n return new_word\n\ndef concat(word1,word2):\n redword1 = word1\n redword2 = word2\n while (len(redword1)>0 and len(redword2)>0 and redword1[-1] == inv(redword2[0])):\n redword1 = redword1[:-1]\n redword2 = redword2[1:]\n return redword1 + redword2\n\ndef reduce(word):\n if len(word) <= 1:\n return word\n word1 = word[:len(word)//2]\n word2 = word[len(word)//2:]\n red1 = reduce(word1)\n red2 = reduce(word2)\n return concat(red1,red2)\n\ndef remove(word, letter):\n return ''.join([l for l in word if l.lower()!=letter])\n\ndef best_reduce(word):\n #Finds the letter such that after deleting it and\n #reducing gives the shortest word\n red = reduce(word)\n best='a'\n bestlen=len(reduce(remove(red,'a')))\n for l in 'bcdefghijklmnopqrstuvwxyz':\n length = len(reduce(remove(red,l)))\n if length < bestlen:\n best=l\n bestlen = length\n return (best, bestlen)\n \n\n \n\nfile =\"/home/carlos/advcode2018/input5\"\ndata = open(file,'r').readlines(1)[0]\ntext=\"LlspxXPjJMmBbVvyYNnzLlZFfSTtULRlLrTtbBlaAJjqQUuXxQnWwNqIiDiIdRIWwQqirWQqwfFlLiIeYyEJiIjjPHhpStTsJVTtvtjbBjuUJJZUuZzGgOoHhUumMYyoOBboVHZzhvsKkSspPZzFfTtScCOzkKfUxXLluLlRrFTyYSstuUJVvLljJjTqQCxXjJxVvCcwWVvXzJjyFfYleEUuAORroamMLRMmOorKkSNnsXxvVJjZOohHeELGglVGkKJjgvciIMeEvQqVmVvHgGKkhwWdDMmwbBrRrRWjrRJSCcoOPpkKepPjJEswaAfFVvWwfFpnNoDdOPpqVvFfHJJjjzZCmMvwWXxJjzkmMKZQqPzyYZHhKkAFfapgOoBbFAVvatTfGCyYTtcgGLlEerRFHhfIbVvBbBiFfNSsnDDddNnnfFjJtjJkKRrTNRxTtXTtQqRTtnfFNAarRrqQIjJiuUsSgZGglLzYiIyGiIGgcxXCrrRRrVEyYtTzlLZeZuUzJFfiIjgGuUhNnHSgGsAateEIhHpPoOiqoTtgGqQOzZQJjIjJYTtyFYmMyfxXcCxPBCcwnlLWwNWbpSsrMmIiIiRKvVyYfFuUkiIbwWBwWkKHhEeRrXMJjjJmkKxXFsZzSCvVcvhGgHVeEfKkhHJjvVfLWwzZlFZzlXNUuKjJknxPNXxnpoOfFzQkoJjOKqZzfFZzNnbBwWEeZLLdGbgtTGBgZzDlxbBaAXusSUwNnFfQWwqWUutThHMmVioOIfYyFPpTtMmVvxXBZHEaAeSshzgSSssBbGaAKkBbjJSsbyYeekGgKEsuUSEZzMBQqbqQmtTGgdDtTJjlLMHhmGguwWSsroORGnyrRYNgWwfFRrlIiLUKwWYykuUuBxXbOXxoSssSLlFfNngGMzZajJAowWOQxXqmAaXxjFfTttTiIJPphHIWZjJzwWPoOcCpwifFrRcvwWgucCjJUwWkKFfqQSkKswWGmMVSslsSaALOocClLkKQEvVJjeBbjJNaAJjPpYyDdnLlRruLSsliIUBOxXoFfIjJBbiLOolPpbxXdDmMxhHXNnpPNTtVvpPFfmMiIQqJYyrRZzLvVljGYygnzZNWWwwEeyKvVqQkmMLleEYykKYQfFQdDqqPpcuPpUYykKYvhHVLRrlyCvVzZqNvVdfFNnTaAcCdDtXxAXkKYCcykKipPIxCcUuNngGDdoOazktTyYKDdZbGzZgdDrRBkRlqQDdpPLjJHhrTPKNgGwyYWnkmMyYYdDyvVpgGGgfFFfvVPzZGgpOvVoNnfvVwWFtXxgGGgsIiSEeWwKSsHhsSiuUmMIyYxXykxXKUGAagYyoOBbhdDahHAtTrRwWNqQBbiIyYnrRdfbBFGyYYygDLWwxIiXfFlIiHLbBlyqQYSsEeumMYhHWwqQMmzHhZzZIMmEeiQqeMuUBbkKpPNnWOowVUTtZzlLuvmQqDdWwPpPFfzZqRrKAakzKNsSnksLlSKmpPqIiVvQVvMiISsLlTzZspPEoOeUaAMQqmuTtStQuUiIDdYyuZZzzzZSsMmUuYyLlCcXxSsPPppFnNKkfUoOQqrbBRmMOoYjYyJvVzHhrRZyYmMtNcCdDXaAxXjJxsSqOUuoJjhHvVbLlJPpjBQHyYhAVvavVngGJjMyYTtmSsRrrRNpPMrRdIiQqFmMfOuUoMmlLGgfFjhHJIcCiUuFfrfFRhHnNrrRRwWcNouUOQLRUusSrOoZzlzsBbSZhmMHByYbsNQxXqnSoOyYqzAKkpPazvgGVWwZZpJjSsPeGgJjEoOApPCsScatTpPjTtJjJyYbByLlYlLCQqVoOrxXDPpdWwRqQIiEeUuvXxlKkLuUmMMSsCcFyVvPpYfmmMcNpPbBdcCDDyYdLeEnNmCcMlpZzZzYyAqQaxXPBbpUuoOUuMhYyHwGgKkWkpPKmPvzfFZVfFpJDdZXbBdAaaUuADXxHgGvVRhUudDPpHmMpPcCXxvVNnXxrtNnTmMhIDdnNFfLliuUUAoOaLlunNeQqEOWtTOowoTQIiHhSsqthHxXcCMmhEeHYvVHhhHVoOPpvyJxnNXoDdOSSsmMBbGgBbxXsDyYdJjkKsrRMmkKxXDVvdSgKkkKsSFfmLlEeuUMGVvCcoOSOOoosmgGfFuUuifSsFICcOoucPpCAazHhZwGgWUJZNEenlLWwHhICcOVvoWwiziIykKYyDdaAYZpwvVWgGPWUuwGfFNngTtstTNQqKkHhnwWoOSqHhfFQJjgGeEixTtXIiIgiIGDdlLZdVRrMmIivHhDTtLlYQqPJRrjiZzImUubBMppVvdDeEkKdaADIpPzZmMdDvVqCcFsSeEfrmMRQVvjJirxXwWRyeEYUxjEeuDdkPpeEjvViIziAaInNvhHAasDnNCcYHhYlVvLydlLDxfFXYyDCcUxXuiGgLlOoIcHhezZPzZptTECEwNnpPbBCbBceYyEWiWwIXxfqcCQOoFKuUdWwDkniINVGguUFUfFRrnyYgGNuyYSsZzGkKXaAxDdrAakHDHhdhTtssSBYyKkbJavVApPjvVjJahHAyYSdDkKGgKkmMFNWwSsntJjTfbKkVvKktDdWwgGkPsSOYyoWwvAzZaVHhvLrzZRtTHhlCcyEeYpPJUMmAaLlYFfZzynNjJqQAaISsEzsSNfnoObBzZNWwiIEnNIieJjVuUEeEVvevFxXXKkxYywWnUWzvVXxBbZwHhQqKuGgAaUkuUusSnNVvBbhnNbBEwWvUuVejwBbWAaJuUGgpPHFfhDdaPdDHhCcSspsSsfvVFSAvcCVIiyYIiOcCVvJjRrDdoCZzIymMYrRBACcyYkKabAaaAKOpqQOnXxNhHBblLihHYyuUsSxWUuwcsSCjiInNJjSsQvcCnNeECcorRLlGgOVqNBbnFqQqfFNnnNqQQEeFfmMTaaAACcexrRXAYyaEMmpRrKVvkXYygGHhxBwWLlbMmDJsSoOjsJjSIvXxVidYSFfsyemMaAaALlEPpeViIvEexkKXswWiIjUBbxXaAzYyZBjGgJRrbuAaeEJjgGwZzWrUsSuRXxpNCczZMmsSnqQPjdbBVvUuDolLSsbbBBoOHhPpdXxDOEeJTtTtjmMfFJjFfHhLrtTRgGoOaRGgKkriIlpPNZdDznLWwGgNlLnNbBfHhKkxXAkKaEeGsiVvIDKknNdTFEeYyclLKbBkComrRDaqQAdFfzZMmMplLPcCgGyOoYwksSYqQKkIVviFfzZCfgqQYBsSbyKBQqtTblLkcGgHhyYWHhzWwienNKkDdCcERThcCHtUtTyYYgvVVvGyukwWKrIulLHAahcLlCZzNnULlCkBltTTRdDHhRrrtzYJjkKyuZzipPKqQkOonppJjPmzZMWjtTJjJTtjJzAXNnxhICzZcbBFCbBcFKTtMmKketFfeEKkmMTZzuUAaVCcrRUurzZRGgvpPYyEeHhnNvVsEiIezZSSRrmjJMuUDTtoOLlmMoOdDhHKIiFPBbtTTtJjbBjJhcuHhtTUlLCHqQWTtTtUuwfFeOgGhHrFfRkKhHzZiIxXYyqKkQPphQcVcCvcCwNnWCgGOUuovVYyfFOhmqQGIiRrsSKGmMuUjJJlLKkAajqQGgRrFYyfZzBbgRIikSsBbBbvVtZbBpPzkKUuSsOuUOokKfKkcCjJoOVvcRrQuUqCIiFGhstThHSFnGgNfyYyHhYHxXnNWfFgkKjJQtTKkqhfFHYyShHsQlLkKRrrROMmxXZzonNOPpBboaAexXEqpxXhYARrabBHhOoeEuUiGgpcCmMPIfeXGDQsuUbBPxXpPpzmMrzZRZdDEHhemJjkKMSOoyYqQyFciIiICOwWEecCiIYyDTtdvVeOoeEeESsOcCxXUuUuhuUyRryYqbxXBUuQWLlwfFqyYAnOoNaVvQUuJljJLjUuulTtLULlkKWwVHhvShPpjAIidEeMmDGJgGTtjgcCBbaxXFdDfTtWwSEeMmLBblKkiIzTtiNnIZCcsCcXxiFZzfRiIrWwDiIAKkarTtRdlLDdyTtfdkKDNnyTtYFcCeUuEUuUuRrRKkCcuXxUrxXnNcCYMmZaAzKkCtWwIiPbBpgGTcXxdxEenNWwXsSDAapPIJRrfjJrRFLfiIFlUFxXbBNnfRrVvQyYqcCxXxBAaIibPJQqTtLljpXsSeXxExXdqfFZzzQRUuYiIWlLwhHhQBbyBbobBulQqKkLIiUMmGgXxOdoOMmKkCcVhHzkJjRaArKKXxvLlVkmznNoryrzuULltCMmcuUTYyHrzZWwUuaAkKZpPMnNmWwyYzRhlnZzNLvBbVZRiTtIzmDdMdEYyeDMSDdsFfFfKkXxQnNdqrRQTtDddLqQoOqQYylDQqDcXxoOhvVHIiCsSqhHyqQbcCBpPxXYpXxPMmAeYyYynQqOoNcjJCsSKkkOjnNJsSoKWJkKDdDxXsSsbBaAyYEeHrRhMAaCrRAacCcQqDcCtTdBbfFcCSNnawcCWAkmMKPpfIieEFLaAjJSsJXpPxYymBEeJjLljgGJiIbvMmhfOoYBbyBbHhdDhmMwDdVvkNnOoKrrRaAPphvyYVcCzHhzSsZfFLlwyWwYWTtzZFfEVIiupOoXxPUuUDVaAvMmdWwNsnNSaUYyxqQXQqIiixXIjcCOomMPtDdbBTpmIQqQHhtTWgWsoOcCSwEetZzXzwcoOCmMmGgMgUYyuyqjJQYvVJbVZzlLaALrRAaUuTAkKatlvHSsheURruVvcCuRrUlvVLPpYynMmAaSZzszZwWQqkGgKIimMSskYfFhUuHzZGgaAnNyCcKmANnLxXtTmMcCmNnMjJtwWMmhfFJFfEwWejrJjrRRsSyYeEHhaiZBQqQDdqbsSLDIDdiZzoONnIixXyYCWqQnxXNReEDdOopPrRwMmWaAzZAahHZzphKkMvVmdDWUuhovVkKVSsvLlBbCcOUCcPranNSsoAaKkuaAiIdDmMGOoNnhtaATpPQdDlGgeuvVIiUcCEfFeRrEksSAFBbNnJjUuiIaAjJBvVQxXVAauUvLNnVPpOdAXOyYoxNnpqQnuUAaNzAGfoeEOAXxabrRqQtTBcAhHpTtpPfFqyYlCaAcVbBvnNEUuoOqQfSjJsjyYJFzKkdDWwuUXOKkXLlUuptTPzKkBwsSWbZzpPFXxfCeEcLlRPpdzEeLxXnwWBLlYurRUyMmeEMRQIiuakKxXAUXssSrRcRHhrbBKBbiIhHkDdIiUusSWwyYZYnNnJbtTGgBjNyuhwjJWHhMZLltTzdhHDGWwgxXjoukKJjJjQqsSUOoDdKiTtdDhHLlIhErlvVyYZzxfOoKkVvBbFDYPeWBbwLlaAGgqQFfVvlLmOoeENbpPNjJnBEeCvVOocGPQqpggQwWqGcCfFGgnMNnBbtTtTcChHzZmuUMsCcSZzRQOoqGEhHeaAUucCuUEuzKuaAUrRhHwWklLnopPOdDyYzuYYyysvmiUuqQjJIrTtzZeSsEsSJAHCchsSamzZOrhwWMmWSsPpwbtTKkkKBpSsTtlFfLPxXyyJjYCYCPpcpWwsSDnNdgGzZkCcEeoXaAWwxKpPzZQQKkMmqPLJkAbBExUuRrvVxzZgGXPxXQqpzGcYyzyYaAtTZCsXxSQpPqHhiIauUAJSRDdeEtjJTrMLlmSISAasQyYdDiIxXZzJjAalLOHAahxXJjlQqKkLQiIqovVLlzdDjqQJnNbBWwZzTzZhHwWtZcWwCbmMFfHbYyBvVDddDhBqFfnzZPXxpvViIjpkKPYyJZMmiPpIjHSshviIVcCzZcCuUcCCgGJjXxcLVvlBpwWPblLYypPxXbUEfFeuuUQqBYyhsspPSfFafFnNksSKDVGgZzvVvdeEnNpQqvSsVBbPpRSsVvJpmMPZaAgFfKuUgGnNkpFfPiSsZzZzGgUulKVVvvkLoOAaLeElpyYgGuRQKkGgqGeAORroaFfEbByYVDsSSMmsOolpwiEeIgGWzZPLdhHoOdXxDmMDHhvVaEepKkQTfFCctPIlLizzZTtgDabBAADdjJhCsSSsgNnGxsEeStThlLHgGEeXcBbhHzAIiaZlKkSBQqxXhHLLlQqkJwUuiIWqJjnNbBjJqQwWFfzbzNQqnZBvVZFQqcClLZzgmMSyYHeEhWwsqjJQoibBIaAHNnhKAakOfFUuRrFfuWzoCcUiIuyuUYjkKSsGgSzAaZiIlaAEvDfFVvdVeEasSrRSsetTtTEZzqHhhHKkikKVvjJmXFXMSIiiIsBHhbMmevWqQWwMUuHhusSUMbBJMmwWEejeyYmQqMNPvVnXxaAvVKkrwWGMJjMmdlLzlLZALwWeElmmTtMMmMdDaZnNfKHhDSsAadkKAaSGDjJdgsQqxEeZzJjuPpUilLqkKQSkHhKElLPpeoJhmMHjFfOLlsLEexTtXlHDdGkKQuUquUgZzrFfvHhRrnNVyfyYBBZcCWwShHsTtvJjTtoWlLwLTtHZzmaAEPptTYyPpePNKGgkPpsSnSOoJfFgGayYAwWrRqQfJPpNnjFBbUuNkKnvVaRrAyYHesnNnNkwWKdDPFfSfFsdDoiImMgGOnBbgVvUGguGAaNUuXZzxnPpOiIoNeWFzqJjQZLlehHzZKMmbiIBBbpqQAiIqQHVvhaOaAowmMWgGEOoGOokKECFftTxwhEeHcCUuWbBwWXqmMmMwWDdQfuUFYyAQqeEahHyYbBTttTtwWnNPpgtmMSsTSIiIFaABbvVfhuqlLrRuUOoQPpONnJpPjjJdDGgjgBDEeCcdkeEKKkbFjAaWzgGZwCFfcWwWQbBiMuQqUmPfeERrFQqaAOopCbBvpPRBbuXxUrZdDzyPpYHjmMtTtTgDLldDdABAYyaQcCquySmMsJnNLlHpNnBbPbMmsnNkJjKSAapWwPBGeEgHhnNEeEMmeCcqSsgslbfiyQCcnNqlyYLpBlLplNqrRQobBHBkKbhmMxDdXsMmdfFPrRpsSpPLeHUqQuzZoOhEQqQFfaAfFGgfWzeqQEPpbBZuUIYdDmtcCjJTyjJSsHhLlVvYOqQqQoXaKwWYywWUuoOqQZHhLqQugGKkUGgVvAbBaSTtHhYMmysuUMtwZbBaewkdeEDdDTeEfYbBpPzJyYCeEsSaAjrRJLhCcHRkKrMBbyYXxmOoIiWcCiIzZpPNdFfDHMFflLBbqQKeEyYCvVcUubBUhHLluCciFfMmsQgGqDddDiNtTfUuqQpkKgmuUMwdDIFfqQKJjksSiWRYcjJWoHmtTMhhrRHBbJGdDHhgoQqloaJjsSBbAfInNivhHDaAdVDHsSgAaAaJuyQqCcYKcCmYnOooLxFSsNnfTwWFfdDtXlrDdiIckVvquURrTgGleHhbEFUeaAEuUuXIPscKxXtrEeAETeBbVdkKDuUhhqQHHHQoOnNAvVoORGLlgmlLhHXAxXQqaxxXiDdHhrRdCcUmMuTtqdDdDPfFpQqqQhWwwCcUOounNDeEdJrRjLmMhHqqQKGgktVjJKPFVppPnNNnBVnXMmkKehHuzFkafFNnxkKpVfyYFpPtAafFPpBbcYylLWwcCxXCePpEvemMEVzZgGIilYyxXAduUNBbnKgGkXxVvdDnNqQbEeYtTShHsyDIiVvbYyDwFfWduUGgcCLwWdDjiIAaAGTtbrRcCkLlzHhgGZdDPpPyiIsMwWJecCiIdDjUIihHWkkKGeVvEZrSshHnNUuqhHnNJjHhzZQFJMmotdDTyhDdHGgzZjVzZvjzpaCcDdWUHhZSszuGgwWxXPpzZBbjJXIPDdpWyYnhDEmtTMpNcCnPsYySKKkQqkDHhdGgBDvVdpPmMgGvoTrRtOEeSbIimCcDdMyYnNOYIiyoULzJCcfFmMiMmyYJQqjHhIbBYdDxbBXJyYneENBbjkKyIiDdsSlDdvVvVLDdxoOXLfLlFUuXxvEeVcBbraLlpPAKkRcsKtTTtmMmMkSDdJjUuRiIrgGjGgDdJUuYaiIiIAcCyKkdOwWzRfVvFzIbwRrWzZQYyzbBZQdUuzZqoOKAamZWwzVvMKLlgGdHhDHhfFHhGpbZzYyEoaAdSsBJjQUqiBYAwLlWRraTGgtqQyOFpNvVnbRrCcYPpUuJFfsPwWFdDffAPtxSsurVvIiRUqQnOeERdDrFbBNnfHhDdvQZzqbBeElFCmMjRbBriDdIRIirJetkqXxcgYyjMmmMtghxXlLAiPpJGPpgjIwWYLlyVvnNeEoKkyYDdjJDdzeEMpRUHSsrRoOlLXxjJjdOgGJIiVeESsvjTEeNntmMsSpPgttqaATtuUASfIiFAUvVsSiKkIueEnAaTthHRrvYyaAVMmcnNhklLKEeHFXxfLljxXeEJUYyFfeiBjJlLSswWGgxDQqQyIiIiYnDdNcCFfPHvOoVlLfFhpbwlLPSspWowEAaEeJTtSDdsjElPpkbBCccCLlKLeZzMmEeespPDNndSYcCxFfeEXyPEeMZzmMNnmMSsmRYywWiIaoOWwAqaAZeEGgTtGdDgzcJjbBROorRrCFfEevVkKOoQAamMeEKkyYrOogGmFfYzHTtjJDicCnsSpPzZDdUkKuQgnfFJNQElmraARgGiJjoOcCJjakKAiFfIiJjoOVTeGozCcZjJMCWwxYyWwEeXcQlLOoqjPlLpxcuUCaAAsSPphAJjaxXAaNcCZauUEeKmMwWRreJcDdCjydFcFfnWutdDQqTgGCcbjDdJYyaiXxIEMmKDTGYygFfOoNneJFfHhjOoSsGkqNqdDQyYWHdDhyrRuwWUifFrCXxOolEWSiIkKRrswbBtTmQqmMMJkKjrBbDdlLCccTtIFfiHuTtHhUZzxcCdfFDHioOIPUudNnSsxXHmMiIhhEoOMmMcCuOPpjJohHUbBKkVTRImMiPprUSsVrRvDoOamMrldDLDdqQSLlpPdGgTtDMmGgTtpYydDVvczZiWwlLkKMmbBoOIIiClLDdBbxXUkrCcyYRKFfQpPUzZuqfFyxXrZzKkcCUfFWnNUuUuwZzZwWuzYyZUzNnfFueEtTLlbBcMqQmMtRDdrwkPmVNnvgGxXCClLPPsSBbpknEjfFQqgGBueWUGguMhHvuUVTDdtEeRrVBbPgGSIpLlsSPBbsSYybjJBcfFwWBirmMnJjuUNRvVeEiHRrthHQqThwwWDBbxXgGpNnsDdSPRrhkuqEeJjVaAItTtqsNnJWdKkDryqQJpPjThHHZXwWEeXkhHKdBbziUGfyYwWLllLNLlGlysSgGWwSsGgvVKgGdCceJXWEemJjMwzZxJjUzZYyBqQbJjDSsfsSBKkuFfUgGbdnYEeEoOdDwXxWnNwQbiIdxXGgDkKtLlRrhBnNCaqQXgGxHhaAIlLiwWuUDdqxXaAoLlQZzqpPSNnndDMmrRPpRAamMoOJjLiIIMmiKEmkKaAPpfNDkKACcVWwdrNnRDHhMmJjvMmmMmwWcCRKkQqsPpSzZKOKapiICcPFRNfFnPUbvVpPYybdDvuUVvaEeHhIaAMmipPAsSlWwpkqQuUKYyWwPSsrRlfFRibBIrzZLfXxvVFmxATtaXgbBwWVCcOoPptMSsEemECTtPpcnBbjlLMqQRYyRrrHrFpPfrRGgKxXkXxTteaArRGXxqgGQyYLqLlJjsUuMmjJslpPSDdsBtTbyYLpPUAautTSVJjhmMbBmHhTLrRfUuFbJjuWvyzZZAaJcCjOowWhHIiErRhHjtTRuUDPwqQrjJKVvkDUuEBYyzZYfiIFyTrRtqUuQqLiVrDTYXwWxshHSUuvnnNpPUtVMcCOoNGgnsSnBmOovqcCKkCcMmsUuXIidDdFQqMcCmVRroOXIDZzptTIiKkMtpPTmEesSUuPyYdsacCCEemMJjRuUoEeOSstTFCHhcfKLuUCclkpPQqaZmMLlCczAskyYKdYEeVvPpPzlLpPvVpPZhFfHEeEehfFAmsSMpPEYyAWwZmngWPpnNsSsAPqQSspPCcWwpkKaZEezurRUStKQqsUHfFhTzZttjJbBYyuWLEMmWKkbBwBZzbrUuFYTtYysuUSXdDvLmMrRlVsNnSxRfFaAIirnfFpPkxXEsSXzsQqSZLlxZzQqZsWwScEGSsusaAdDlLLlEyYbBGGgIipkPbBuURrBawEeWuKEQpPaADwWdqJjpYyvzZMHhmJjSlCcLygGYyYWUuoIwJCYoXxaEcCFfmMGiIgQChcCHxXcqgWwEfsSFxnNZnBbNzSsHhjgEfFeEiIeqDeAaAaNnEDdOFftGngfFWwtTwPRroKGqQgSNnsybBpwawsShHtTFJjYyOqCcQeUuEkKHoOGghfWwtxMmXhhHnNHvcCVXxPpQqTgpkKLCcjhqQZzHoOJlIYOoNSPdsSUMmuLlkiIRyaAYrKTtMmnAAaHhacxXtWYycBIIiizZbOMqQmKnNPcCHhpQJMmjAiIgGRryGgmJjsKENuUEeRHhVyYvcCVXxvZzrnecCGlLgKhvjJXVNnaAonNONCcoOKrhHoOFfVfPpkKFvVUuhkKxXLlmUrRDdDdvVGgyYjJAmMGXxEtTvVKrRTtkrRecGgTCBbcFfQsSqkKEettCXvVyfFVvYpUWwulLPhHEncCDxXFfrIimcRrCMDdKoOFRrXxhWwiiQqJAagGGTGITtwyNnLlKgGbJjNnhHBozDdZaAJbHhBlFBbfcCsYyfsaABbpzZYJCuUAMmRrStTsSVsSIMmiUZRrzyaHhsSuUsYgGxXIiZsVdEelLHnxPpXNNnhJjCcdFkafAaYsqQOoQqRrKzZHXxZyTtYtTnNgoOueoOZzEwWuUgyxXYXfnNUukEWwUuiuZzDdeEGdDgUQgGmMqjJyYUvVHhsEUunNfFZzkCcZzKsSUueStThHskMmeEANnJLljOoaNqQehMXKilLINnpRrDdPqhHdPpDfFxXCcXxMmbBQVJcCiIAaOvVojDFfFfTSPzZpEDdeVvstHhTaAkKhWwHhmHuUyhlLuoOgbBzZadMmDEzZeYeEbBKkaAdQaAqqQqISmMqQsmMzZSEeFOofBHhFXgGWwWKkdvtelpWXxwPLlLHxXxPIiisuUrDdRrKNnhJTarRvxXNnMPiWuUwfxPpXqwnNsTalLUuAKkEZgZzWwtTfFCkFexXpvVPRrCzZcpPIpPWwyYiVrRUOouIiaAQLAamaAMlkvVFfiIRxXrKiaaPwHhWSshHKIikmMTtRQrRMmvyYSsVqIiPpnibwWiKnQwWHhIgGTIijJAatUAasotNnoOHhGCcyUbBuzZuUGgLhcAaXxIimKkvsSVMVvhKkHafmMFAaAfCUuYHjgYgGoOyGYOoYyyHmnkKsnWxbByYwWUuCkCcKoOgGYyzZckzZKFNQZzuUVrRMmYQqSsyWwTtAdDanNoUwhmvVMuwMSsqQmMrPpvydDRrYVMfXxFdDQqmbBEecRrCAdDCWwajqAaiIcLVvDjBbJgGPpmMLlRrdYJyYKZzsGgxhDdIiIiLKklLsTtSFfAeaAEjJTpPCctTXpsSPHEXxlVjJnLJjlNBDdbBwzczZNXsSjJqOSnNfFpPtTsSvVbSsLlFfprRDcCdONnRGAKkalMmLwcJVvjeEYTtMmVoGnqQNgOrRETtWtjxfvzcCwcCuUmyYwWMWWDdwGhHIiObNdVYyYYFfylLVKkndDNcHhCiIUuPIipuULlKkSZzsXIiNnxHVvAUuaXxHSlVruUjZzHIiqQZSqQoOsaAzhEeXxJuBIQaQIJgGtTnwhHWUquaEexXuUXTTttNntTbBxBbGQqPpWiIMnNmSlAlbZEexvVXpPVvuiIGzjhHqeFfEQvfWdDLlnkmbuUoOWNVIiKOoBONniYwVvzZTaZzVDdxXNnHheqQDVlLNnbVvBrjiIcCIiAaHwWaAhQpNnPqsSOiznNbKkNnBiIRrYyJjbBofeANnaxdDxmiBnIwWbBFhHfiITtiDdAoIiOUswpPYyxIifneENgGnqlLQfiSsuGgjhJjqvPpJjVqQzZQyYUuFfLlHDdIiHhWwqiAaAeEBDdbqQgZEekKNuYyVvoPpqQYeuFSbBsqAcsTFmNqtlLZrkIiKtsSTWLlLlFoOKkfIhkKHrmMJmSErzZgqQWOowGRyYehHVvarRIsSiAelJuwWEeUphvzZuBaqvlLVyfFHyYTWwHchzZRrgGuUMAarRiYyyYImxXFfWwIitTQxXZkKGgzqnhHIiiIDSshHGgjJdOoaAzUudFfZWIiwGhxOSsLuUlNnmDWwdaxXkKFcrRCfAhzZMytTbDdDlLxYyHbBxXhXlLHpPPpPppJPovVeEOpfcmMFzZFfhHDUEexXhkQqKsSXXxSuUvBnIipPfFeUoOuAanNxZAaskVGdWwDgyYgGMmuUvAaCJjpPqRrQzZlhHLaAWSswSGfFVveHKVfFBbrRcLliImkKfFMPKkdDReErRvVkKudRrNnDCTAaxHLlQqkKsSdDiqQIhUuMsNhIiHaxXPndPpfXxuFuMiTCqQsKkcCblrRFFfbBHhfLwWthMmfPtNnPZfcGgrzZtdDTPpDdpCkKcxDjOrRcbrdDQqRuuUrRZRTNntrKkzDgGDwWRrTsScjbjZBbzBbRUBWwbDnLltTquUQyqpwWnTbSdDsBtNPFEewTtkOoiIggJNnDdXgZzxmMGgtdDTFfUuCcUfZCcyGgYBCcWwrAjJaPBvVbLDdRnsrRnNSowWhWwALqQlaHcwYybBWlLsjXxIuUiJPSmMRrgrRaAgbuKknNBbQcCqegGEeMMrLlSsSHRrhsmbRdwKkWRuGgbBhHyYjeEaEqQePSsBbsSpPQqbpCwuHvcCGMHgWdiWwHhRrIDKkcdDCwpDyYNndmMwWPUuTtRgylyVOhHByHhYopzZaXeEOoVjPYyNSsDXwzvmMPGuUgpiIYcXxXxdDRrkKmMwWbBybTfFmMWZMXjdbBsbBOAaolgZzGFfFfdDSGgICvqBbQEaSSsKkzZTxWwIiUuXsEebFflLKksIihFYyhzdDfFryYztThHinwWKpSaAgGNnaOBbojlLxXHUuvVkKqQAGgUuawpgpPGaDdlvVjJLzyYZGgakKPpATtnpPNWOaAowpPUfGguUYykKdrleEFfLfrxkgGLlhHxFlLxXfYnNaVlLNjZzwIiuwyYYyWUTtTuiItqMmgOowOcCWwoWGiIQyfnBbaBmYRrsSRDdrpPyqQeEEePJfuxcYyNnxCJlLzuUvTUwEeWnnwWNnpPHNnOvVcCyKkuypPaAZIVvmMQGRrgjkKJJDdjCjAaJcRVvsSvnNNnVvCcVKMfFIijUuSsFHnZwWzKkoBblLknfFmMNhHAGjdDOyYoJKkxXgMmhHawWdpPDFdtpsSmNngBbGYMmySJjLCclrdsSDtdQqEOogGJGhPFyVwcOoCAycOfFvhhdDHOorRFIOolLsmMySsYCXqQXxmMmMiaTVvoHhOGbVlksSjhHJKYyLizZUsSuvaAkGottpQqPBWKHhMYymeamFfjBbMmJMiWTtlocCOLHhRMmrnNtvVTFfFfiIAawTtWwuUINQqMmjJozZzfFeEuUoOwFfepQZtYOoTuUDdoqQORbcCMvVhnlLNhHXLHhfFlUuMjmDesSWsLlAalFfKklDdtGgrVCEDdJtTjvPwWCjUuYyyRKkrQPlLozPqaAGgSXwWPpoKkhHtTmFaVmrRMvvsNbjJBtTnSjJqBbOoGNaXzPuEwWeyYxXPVmZzMEbozZcCcPXsHrRGPpkDdKgaAHLCcwcCWlrRIXwZRJvNnSYyofCJjGwrRftCjJbBmMAHhxxXMmfvnNcjzmMmMfFZCvQqQPpqNnwgjotToMmOAaTZzAuUgwJUxKkyYyLBOmMiqQuUYodlKkjbBJrvVbhHKkwEbEPnUAZNnoXotpPJaKkdDiIbmMBqnZWwgGyGOEZGIkPElRrwWLrQlIjbfFgGfFyYPVdDZpzZZSKsjJSCcZzIVvcqQqQdJjikpPOojJsENhSsMjJmeAHhaEHIKHXfFxZzpLrRlxtuUTQqPiIpXpFfYykKcCAxXjbgvVQCSsSEBbbBeKmdrRDOeHwtwWTVhHAAfFSLLyYOzZAaRrlwUQlUupByZjVpHWwYWdxXqrfAaxXiInHhMmYPyYOckKiICAaLaATtRcbujJUKIiVOoIhHiYGwWgIghHCfFqjJKvKEaAbDJjdGccCjBbbNnBmsjfZbQqBQRnNEhHEeBJjOJCzqQZSsSseajzPiIpZvaAVkUvVuZAazLlXxZrHWwNEeeETmMKkDGjuUCcJNndcREjJwjJuMmKkKwNneFfXiIWwxDwWwEeWfooOHhOdDdduMmZqQzRrJjOaARzpgGPBGgfxwqQjCcJWZSszwPhHpmzZluUOcJaXQsSIiejJEoZjwWgGLfFnwXxWNhiHFmMfhxeEmMabxXPpBjPtQpnNPquUjpPEeJTaAfFRrCcBbKkPpNnFfNfOoAgGTcGMmdwWDoVvQpoOooSsaGgYdxXDyAGcSBwWbbQEeRrqzZcCYyBsCMdDmCcgOoIoOzZkdDwWVvkKXxKkLlLAcbBCaaAFnNfvcCVHRreESJjatkEeuUoueNnEaArRTjJFPpWwOoiIfGAlLajJXxTRzZMmrtglLoONnmMXxVnNFnNTxXAxwceRrVCJTtjIQqiDdwcCncgGPpqpPmPpUuMHwqGgyYHhYDXxlmiIMLjJHAbBOoaeEXHmQnFBEUuebpIiOBbCtTcAaDtDXuUwFwWSZMmROXxXXxInRAGgaWPpAtTVvBbPsSpaAZzFjgYdejgMmeEGrnwWNUuMhHzVSsUWwGgxXsnNSfFlkKuxXqQvVMmUyYjotTAaoJjbqQBLMRWNngfFpskthNeWRrYytTHhlXxRcVhHxXJeEjazRSpPaAsXxvkiIKJjWbgeEcDdHXxYyhGHApfwWFwWHaAhKdDUuszZSwWwAaxXKkoPpjnNJAaPkKJpGgPHsSXqQYqHhLEeYtdJjUuDtaoORTNrRBbiiiIJjnNkKBXxbwwWWwWQqFXLiIIiaaAjhUqQurpUJjtTuUudKVPxXaAtOoKbYyLlBMmHhxBCcbcCXhHkaAclLQsMmwHhqJkKtTdxXRrtTKKkmhZoGHhIslLCclhHZzSsjjMmMmZNnwWWwgPpGUumNNsSdvbBgSsGxtTXlutTUrCVvMPpHhmyYYyVvzjnNWXyPAVxvOHtFfRrTVvhWGgGgwuoMAooOBbqrZzRbifFIycQKrqTLltQRsSxXqLlQSMKkcRrpPGgaAbcCluUPYQuTPpTUutxdDEEotiITGadZiYvjJVtTfFyVvICcKkWwEeLnNDRaaAMmMcJmMZRBIeWsdIiDQqSwkKYyIrRiMmKQqlQEaJjVwGnuiAagqQVWwvGtyYkKkLCqnCcCGYYynpPobBONorviIXxQqrhHJBNwTtWqQJjcCkzSjJWwdDfOpPoFZmGgpPMNnzDdNnHhsWaqQBbAxMPzZsSqQxXzFjJUutTwrRrRuUkCcKyBbEAaqQkDdKFfwWCcqDUtTjQTanNXfFlLxPruDnNETtUJjGgWXLuUllCcLoehbBHVwWgGPgGxXpwDdUurRZWeIKkemkjJkVvVpRrjdDbBYLcCscTtCbaLTtlzKkLeqbBrFaABbQhTrXxRHlLJjPphsSArKcGXOhjWwhHlBbLUuJCWwcIVvzZiDdgGUaAoOAaWMzEHhnNLleZNXNnBjfjMmoTtSTtsIiONkfPpFaAnuUNopGTtjKkJzbYzCfFcXbBfoyVGMmUTttLGwDUVZzsrFfHLllRrdbBiNIlLinZgGGgeUWwuNgvDdZmRkKrJEwaVxMsSmmMeEjWwRYHhoOHsuUoIfFLIRrUuCUOteETpOoektNnHsgGfUuFrsSRtQqqCjmGgMpIikJbBwAfFatItHjJhTagGAZZzzEezZxXBlcCUlLuuUZAxXaOuJPpAfFaYSuhsWGgwlZzMmkKUuFYyaAisqqOozjHhOEeorRXHFGuvVbBKCckYyIYycCMmieYyZSiIuCcsSsaHHhiINsMmnklZQmMhsNCiQXxAaqbBvlCcLsVvBbmMopPkKOIQqisNnuvsSDdfFHhRrDUuerWxXmPwyYuUmqYyIBdDxEefCwZzBbOqHPysSYOdEIiIQvVxXeVlLbBtTsSRWwGgUgGurCdtlrXetTEeyHWwhBdEeJjBfFbrnNRqQMmeGgpgAaCfPnaLqQaAllLwcjJGqVFSsKLsAKkLzvVeEgyYhPptTRSUryYKxXdcCCcdDDlLcpakKOoBtTbhPpHhqoEeOOZvohJxKggqQqmgGpPrnTXxtTcIiISWLuUHhJIlCdGJMmKkLlcCrRAKlLkyDBXcCxaAmMgIiGYdDxXxeEXbeEBcfFFcMmCHhuNxXnFeXxkKDdRrQshHxLnNIilvXxVXvNnnWhzZHwzKmNnMJHoOYvdDRcSNnrSQuUzZRBbwYyUwwVPpisSUSfFcxAPBetTJvVMUsApTsPpqWhsXhHxSHAaxlRTtPVvpijJKaxMmHmmpWwPMMgGhyCwpuUkKMeNnmVKkXxXaQZzuuiIbKkLlVvwWzwWvqEoOqQFfBbhpbBYyWcCfAapxaGgAXkXxdKktKteETLlpCcCcSsPiIjfqQmMKaACckFJoDeEdZsSRrzuFfvvVjfqpPQFTCtHhNPpVvnrHhRTMByYmMdDVvyHgGdrRDhvVYqgmJjzZMmzZqbnoONBNneEzZygGOounvSsUQqOxXFfonGPpgNugzEebBlLlDyZFkHJVcCaVdjaekOTPpghHaGNngZPZYuUAHhatDMmdTJjrRNkKkkKKdRrVWSswwnbVCcgUIoFgtTGtTMAEeWwWwaZCczUDGCeBbdgVlLdwCcslNnuUYkZwiIWyPphJVvpPkxLlnLZUuMmGIgGiFfjhHqsWSVvyCHkKhczCcZIlLiNyAhMcCmmMSsHfFxXYAaCMmEevfnmMNpiOoIuUBKbBVzWpPwVnyRlLpPFfrgGnuMoGsIDCcPcCUufFPKtNyYQqBwYLlQqnVQjJEeqvvVKkqRxZzaAuIcZzgGjHhJoicCzHmMAahcMmCECUucPWwABiIbzIedxyaAFfiYrRsbtEeoFITsSjtTkSdDWfFhHYyrRURSszWwTQLhHBFfTgGtFhDdHfbPJjjtVvKkTYygGGgJPyKKkkwyyvVkKcfFZzRtMJjuUXKGjXlLxLCclJZzPQlLaiuvRroxZKknNhSDdNnCcsHFoOyNnkKuYbeEBjAarRXoOoBUBdwWyjjxYZzIygbBTlJvVAlskEEezxbnYyxXSEKVvqsnoHhuMDddDmYXSyQiIqYaNCeVvIiHheiIHaBbKkLEpyYqQZzXLIUnUPWRrhCAjLlpUujJDdtTEaucGgCCPMmpvVFffrjJYHTQqtgngWWYlOHQqaHhJqSsYLrRPpRZlLAQqNnruUiyYGQeYyrnrpKlLzgvVtTnNDGbupPlwlLEeSsfFqNDiIdHhHxpeEOyYVvhtTHhHdpPCMulzWielLKGsRhHrSgtFfYOommKSpPVEeKnloOgegGqAOoapwhHeZgOIioVVbYPpLloOXiIiAnqCQOouUqctbBXqQZzZzxHCrRYycRrzBFfwKkWcNnkCXEfFxXwGPwjHmMxhUvbXxaEeABVVvuHOYnNFDdrFQqfASYfFEeykdyYsSsHhobBgGxdHOBdDqXxQaAumAbBzZKAXxeEYsSyNKWPpMccPJjpSmYtTSTIrKkErKkWXxIaSOoAEGwesSLlcCOMqNZzqkKRpPrdiIDuUHaANZIizBQPwnNWUuvDbeEBdDHbBhIiPpFCcBbcCuUFsdWwDxXbBSSsvVaAeQExDdEICqQdNnoXaiINnALbMglPpLGmXzZdDZGgzvqQtHhWwnNTYysgMGgeHhAwqQyYiIWapPAXxZQFHVvKWQwOXTtfFfFEeOJjuVGtzZTnNMbyYJOojlLSvkKAqQaHVbBPptTnNeEMmBbvVwWNLNcgSaAcnCYkIBioWwhgoLlPEDZzEpLbGgBOoVWDdwcCfFyaQoOErKkdDRPlLmMwWDNnjJdQIXximhACcKEzZNsQFreEdDOznzZtTeEznNZQqGgcCiVqLlrIjJzUuZitnYYRrwpZvVhHjoJjSsZzOdDBeErcCKkWAgcCGaZzwWRRrlajVvJiIRqHhecDdOFqQeZzEwWUupPfTeEEFwCPieEehoAQmIiVvfxXAMBbsqQSGfCcxXyYDTKktzvVZoXxUanNcbBOzGgZHFfhQqOooeycCddDDUkysOzHPEevpXdLWwRzIeEDMRvVdDEekFfKBCIdQqDijPpCcGmcCyZKkEeAXxgGhrImuUuLlLlQqIiegGIcCiEUuIVZZzaEjDNndeEOZbAxXpRrGUdlUZzZefpQgGlLzZIxXhsKkljGWwRgGrgTtCNqQeEWwncMmJPJOOoLOolojrUfFuhWwwWHaOosuzZnNUeyYzaAuUYhPWGgHIIAaaAqMmjJBLldDfFOOzyywUuYyWYYZutDxMnNftYafgOoGAaDbJjbBLlBhHYIikeGXQlLBbqEexdRYymOJkKjQLlPpqoZzeTIXVPpIIqMFfHWwPMmcIjmhHMDAaUuPpwWtMmTeEbnNkoOKXHdnNldDYfFTttWwbBTHLlhlHZrMmZazBZcrdrJgGBbjRjGSionRSsVvToOgfFjXxJSYSpkKPteEXxTFpyyYRxUXuUxCIQlIiHYmXjkCMLxXZpxXPepPENPtTvNvlEkKkvoOQBbrIiPzZyzRmMrZjCLxxXxuhMmHhHUUwuDSsJVuUvlyYaGFzkZUcKksoOZgGNdrRarSIizyCcyEeFfgObBQqoRAargUuAaGpjSBBQqpPWwyYajJBqcCLWIiwzbBTXgESyYsFAadDmgMmVUuJbstTVvhkngfiwWVvIFfwWTtWtTvMmWwCctTtTPfMmuldiIncrZzdKkKmyYLlsqNMmnfFtmPJIkAaYOoMTtYzZymBLnfMcXKsyhHeEpjJWwxXcnNWDDdcCMmbBYXrRHhuUyFZzfsvHhcCZzgGbulBIiyueEzShHsqcsSCQUoMqRXfcKWYyXAaBUuJcCHZzMqMmfFLhudfRkbBdIiDLlEkiINmMBbuNnSFQEesBBbQrRqaiICapzCcLIsfFXfFxSDXxMilLIXKkGdadDxXNnYMgyBLctTCaHJUuMCOoxKkDuqQlryHNrGgyYAuUqQEeazMmZDdDdaAUlLVvutTDPmMKkIAaipwRrRhVsSBbFfbBhFfHcCzcCIiZnOcZaeqgROovBbWHEehtsShHTQdDKceGeZMmkKBbVRrvoOrOowHJsSAaAaNoOIWwSrCcRJpPjbBqOsPbLlKmKkqQHhVvICcifDtDdCcwQqydDeEKkchBbzZCpuqQUvAGwWcENVCMmSUhJjPpqmYybBmwWTtuIisjXDVFiDVmnNKKlKklLsSBbtTBQOoqQNnLmEHFNnmMYveCuGdDsLlSRkGgkUzZupcSfdDbMHOgJRrQqjGYTUyqQYHhtirYylLCeUeTbBAaeaAedDQVGRcpoZzdDxTtEZzNlzPpoOCDdZHxXHeEoOoDLlKwWacXxLlCfvTbpFyfGvVKkjIieLlExIiVvXbwbBWvYLlUbBMmEehzZQkkjJWByHhAapPpeZzHwWjJgGAwaUVvuTuWwnNrjqQJmMpzZPVxXrjhXxSsZlVSoORROokKJtqrpUeEuUuFqXoWicCNzFQOmPpMguQNQEuUxZSBspLYelMpPXeHhEexXuFcCvRrVXxwWylDTtCgGcduQqbIcMEMmTtedDQSsQrRFfqohyYAWuUwarRHSsugmcCZzSqqOVOZzoORrPpyKgqQsGgyWoBprqwaUuaEewWtTAVvACctWJjwiIKkgAaGjWwqQNyYrRnmMNiRrIZaEtGgFfqQTucrRMmZzCovfTECerRERrcCicJNnjamMoPnPZQPpVoOFYIPYyjqQBbcuUAryYYyRzIGgHhqQKWcvVGYyFlbBLugZzGuSGgqYVvfFihHIsrRGiIglAaLlwrxXuULRfnfWUueEFxmMmcIinNoKulfFLUkKGggEeGVWwyYCYyVpuztTGQqUuGVKPBwPzAcCnNafgSshlLXxACczpTtPbTtfOdmlJjHhHXRIiLIOomeqQgGoDdJccGeEgoBbFfGNndwWkKYaieEIGgyYAyEeMmBFfdOoDbyYqPpQpZzBCcWpPorFcCkRFpPfEbBQpYJZWPpbKrIiQldMDruVxlSsEEGwXQGgSpPsPTYBRrQFhXvVxEFyYtZBbsSWJjkKGgMuIWwAioZhVaAhHHhRgJJQqOoKqmUYCbeNneErkKRdDEjJBqQlLaAAafFkWwpozZOdDkKnqzevVMctTCmSPpPHhyNMmOYKGKkgJjlblkpstEYFceQfNkblBDxpPnNxTtwWCnQqEeNcCiIxXBsJnNQQvOWFWTAoTxCcyYAlLyuTtwWyYqLsjshjsSsHVqQvCFXnrwsylKksMmnDiQqCJjcIdHVzlPxQRVaAovVaOkoOKojJAlgGXlfGmRrjzeBVvbIkquVvRbWcvnNVVjwCiVHhzmMxAzZaqQXZbJsmMXxwWSFIRrvCcwWViwWTJjbqLlRUhyQrRqEemMWOCccRTqHhVxelNGeEogHoMmPxXHhsWYyHhEUlLLqyOyYodDbmYyFIlEepxsuAYhyqAaXgGxoWwOYyYBIXhhIbmbBeEVPzufFYTtigJcUuoTKRGgGIiJjEigSXxsWwSlRrSrAbFQqcCreEvVeTGgeQQqXOojgfNnzlWqiMfFyLlLFQmMgRzjRrfFJrRNxXpkKCeDLQPjJpRWJjkaAKUVUtsGipPnpZNElLgwnbfUgPcCIiPYylLkKpNisjFfGgJmkZRGgrzDdZNvPhHnuhHdVnPprBwDoNRrnirEDYyMmYrHQaRrYyAcbWwanSsamMUnNuOJrVvqdvpIiPQrGZzgBspHiIcCLYyvTFTQqtfPvGnNIEeZfFSEQSsiIBbMmqMmbjOoJeEBHhOhXIPzcmkYYMXFfLrFfsFJRtTrjPtTpJjAlTtZzegvVGUuELrIHvpPJjVsysaLlHlLxiBbfAavSiwrRRrjJzMPRTtmfFtzLMUuZBbEEGYGlLEeAcCIMmilgFVyzAkKrQKkGvCMMezrPgGvWSDlLdNGgZLcfyQGeXMmPpxIiaogSWkKaxMeyYmNyvaWasotOXxJjOpLjJwTmusyYWwSxCxtWNVwWeyfyPpYFEebkmnLDZERrjaAwFxyuUYOCNCRVkiIcMAaxOoQjYKbBsmMwWtLlTGgjJZTtzCWivVwZOIionRSwBkoPyYAaplLRTRysCJcARHIvFidDnNwWyYIihyDtoOTSVHhwWoBblLKiIhhEYGJkHhicNCrRczzfhBTtbpPHzXuIwWitTPzWnhnVHhvVvOSgGcNnUdoOzFwdDWAPSSsYkGPpgKyHxkKXzPpZENnsSPVLeElsXxSvQqlLVIzyaqaCcAQgGAXxtTIizEmMyYeZXxruSybZaBbAJdpPDGgzLfFjxfSnKVBWwbQwVvPpBbFfVqQSKHyTxhOYyFfTtoPYRtiRVVaAdeMmbBHaEemtTMxWRsoLgtldDLTENnenDixXgZhMmkKhlSFfDdrjVBVNmMdDiIjdDkTYytAPpLrgHqQfXxYvVuUmZzuiIDwWBwpIQqbZPuGSKkqTtDdqRRrtcmaqfpOnxNnXjJnxNzDxzztUqMIFfWwhzxuDgGFVvitOfbBhkBlMmLXaqQzfIzeEYdDyrRYQqyZPyHhXxQZFaADdIipIlKjJkoadDAAaFfHiQnNqBrRnNIlafQqvsusMreLlpesSvAaaKkvEcuBbUJgPpEiVMOyYqQiakMCwWrkKRdrgKkrpyQYytTDdHhYkUuqNnaAHQlLcCyMsXaXxrgIgYyjJGUKVvkOobkKiIBqjPplBheCcMMmpyTtYPeXxOYfaIGtzanNAZvVIicCTgbSshCcHRkLwlMmczZfXxBvVWPIioOpRrRrxWppPqHtJZTBypRbguNqjJhNXJjzkKmcQQkKiTFfVcCvnNOyYsYElHhcPpaATtRyGoptSfYykTtPwWMmtTrRSUgKkpJjFAtkKHpPhUfdJjpYyPAsSUMEePpNnHeTDwWuKkUXxpTcCmzXCzZcITtixEhtKCYhHhuNnJNJozZODyYwWdnNUMdDdDqeEVVwJjLWqQqVBOobBWxXwpPbvtnRiIxXinBzWWZzjJZzfFVvLSYCnSsxADUuZnxNIIaqQTtmXxNpelIEelLAaxXRrWoyGpPJzefFVyYyVSeAZzeBbFfzMsSmGJQqMcoOhmMGzthxICcJMhHBIiYHhgVCazZAQISIQRDaJzpPgXxTtEFfXlwGdKoTlYOitTfMLoOwWlzHycNnXxIoOrUuggGUuTFfRUSWJdKkNnjLlDdJJIoHMpfFiIcsSGiIgPXPeEpWKZzPpTSXTtxstJiIwAXezUcmBbNnSicalURrrRxOIioXbcnNiQDdnGriiwSatnBNnhBwwJUujWhHHbBhwrjJWwQfFgqEeQWPvVrWwKPlmMLpzgruSmMARScFxXfsMJcCCZmgVPxTHuBkKVlQgGDdEwJEeClQBOitDwWghiuUIvwSNViJjFoJjrBGBIiRPpKroOWlhHjJDdmMmnNxoJRrjOcCQjMIWFqfFeEquUVvOorxXRuSsUVeDrPxCTtTHLUaANJCcHWwQUaEeFtTUTMhHmtUFyEVZzOmDdiMnNaAnBnnXRrkshfGzlLZRrBhHLUMQpPedDKlHwIibBidMnnNVvdjPdDrRphExXBMJJynwqOoQgGgpVvPshZUhHmMvVOooOAyODdOoIErRyOWuIaAZsSZzFCNpnVRrVvvWoHhFNzoOQqcjqHJeFMJIMmGstaOdVvDtTEfcFfCFZzBbetToALlKlaHDdsWwShAnEsSxZuUOozrysSCcfFAFOoqjhQqzUoLuezZBLWSSRrYysJknJjNnDXjvIqdDQFeYJgwRijHoOhJkKKFUEzRRrynSKksLCHaWAawfVRkooLUuMOoVxXBJelLjJruURIijpMmPuUpUMmutrRaZDxmMXNZRrEnNhSYtUWFlqZieEDTMrknihMAQeElILlnkhiImOoSsZUmoseNnEjvlFGSHswWSeFfEagirIiycERWwLxCxXQWrtCcRhfFHccwnNiImloOakKASjdbmMBlEllLfVvXzOKBoNnFflsYyhAaaSNnoOvHhVIwWBVBDGNogGkqQsSvNLQqTgGovMfHhUhHsSguUBbXBbxGWwuUSsUuppWweEoFJjfOrdeIjlrzJIaAOuUuhOxmhHhHtTvVMXOoshHaASTPpHuXLlkKAazYGbeEZgHyyJKQxcHuKkFflLrRHhVvwMcsKoOOSsGQrAnNWVmlLMQYHxeERhHMaAxFeIiEfMqQpOoBneKbBgLqVvQDdjJnrPXnNrWwmMTHfVIzZLliDdTYoEoOMOovVmeAaOyRtqQmmMsSCcUuMyCuTsyyCQhQDishyZiwQDOoAaXxdcXxPziYyXxNcCRSujWaAwwTtAaAafAaZvVNRrCtTcmKkAZIhgSeEiTbiSJvqWNrRLxwHhKhHbBFZzAaJdDWwYyjZtLpPlBctTyDpIIijPtEfdDFeagdDrRGzZzZoENmMbKRmYpMmaRUxtTUuwqMmjQFYscKbBtTqbdDJwWjOpfvVFPoRrYcCWTXxXDdxfSqGgQyqbEoLyAPpjoOHNxHCAYKCcfkDfAasSWYteaAEYyGQqggGTYNNJdEPJjayBbwkKkKgGnBbpYZUwRaawWCVvmMCSZvUWfFLDXVhHvpZpWwaPpaVvmOGggeMWEkYdDVvyiLlIKkKfwGgSheEaeEnVWHOzZkKpOrPjNnJphJjjydDbXtFfrhCCUmwqjcCFfFXAaoOxfOwSsSlJpJYcCOBgGbSBbgtTJlLuKkAdDEJwQqWAaAidYoODGTtrNhCBEvVosSaAYuPpLvSlzgnNGaAIVJRcTbtFfTziByVvuUrRvVpcCBsqDdQbCSoOtnNuUyWSsoOaAPpQBhnQBvVzzZTPDMDdHuDrPsSGfCcPqkRrKRljJLSkKrUcgGovVyCivJgmZqQzoANniISabLlgAaFIbaGkxnseZnkKkpLnNkKvSsyiRrGZJjrqnUXOoMLMmUsUuSgAmVryqGgppiFzZybOwWhNWaAQMRBNpPnbrNvyYnNtZkmwhpPYXVvnbOCcGgCbZdDCcJjEKgTdDdBSswMyYhBIJjilVIDdJjiIYmFfzZZoOvoUeIwWdzeoEnNenSvuXxFowjZRWGHJJjodDOBbnfzZGyFRrsBbSUUuWLzMiImZEFfeNqZzMFTtodmdNRrhiAkKWzjJHfNjFuWcZzXDNnEfFjJznNTrJWfxKomfuUFAbBafkKFOLPpoODPpXJAajiLvVlOpIRRVvbBrBbwYyxGgpFjCXxCcbaJSsgucNQAJjrRmcjzWwYsSCfFAaSsfFyrRYfLvVAxqVrdgGnNDlLfPPUIiCnNJjcHnNSCUvZGcUzpPSrnzwGgnKzYErdBbDRcxELlDzyYZFtSsevxQpCqaZOijIOoxRlLRmZXjpFfKCfUabGaTinnMzFQqwAyZyIvvQqdoOGehHbSfPEbBphWxdtaGgRrhaAiSnXxTvGsNRwwIEekUSsFfFJuxVmyLlDdxjvBcCWyFyFfjJbIixbBZziwGgDcnNCcCfAaQDdAafmMqQFZzlgsybBbacmMQqKkyGSHJgMThobZzBfFNBdLrevGVvJjjJRrgMmMoOjJiBHkKheEKnNmrtTesogkwHPIiOZzDhOKMPMZMGguLlUVvGGgphFPpEDUHgXnduaqQrlGhlqdmvqQGgFvVAaipEiICtYyrrlgaAGRjVtTZhyATdjJwWNSwcrGqQgFiloMmxZAaiDFYyZSKibmqjuUJcdBeEQDXVjBdjHhJDbJvxdqbVvVvjJDCQMBIkszfdgGIAatTzXAasSyYOLIfRCqQWsnDtaMlLmYHzZztmMKkTvSswWJrLRRYFfIiyYyTcefFPIfVMDQLkKHgXxLRVvlsSLAUDNxGhudIieWwfHPgmzmFxIiXfpmkoHdOooVIivphJjWKGOSERMnNkeEXxHhJjWwbImaAVERPplDbnbBOaQqAHtmuUGjhsgYCABEeUYyMmutTwWngrRGNYHhSGDcCdLfFqFWwdSsWwWIOouUXBFfYfYwbVJuUXYVvMvyYgGXUjIsSFfifuiIKiWWrnSgVtNsLlIHATDrRXwqQHPepqQFsBEgOXxooODQqVViYzYaWTtxXfZmNNIpPtAWwgBAuFcXxkVvnlLZzNPJxzpPMrrXOohHiJIohHzAQcPqXVywAaWYtJjSshHTfrRFETfdDdeXQqCrRdDeJTtFfjJjyZkEeNWZNIuUoOhHilLRNnspPZuUuKkCgzVucnNshuuUppFRsSvqQQvVXalEeFKkfFvVyYzcCZcyzBbZzZZKkemMEJCMaqnCUjJGjABcJfPXRLlrWBbriPoIxRitDdTIrdloMOkKgGkXFwPpVvjRtZkKedxAeEAaaCwUfJnFhZwaImMHRrnDMDOfyYmQnbBzSsMmKbBkWwZJjlwRruVvuUfYgFNIHhijXQqgGTtpPxhgqQwrzJWOfdDUVsNwWOjJEZDiEuOpPVdDpPzCcMyMjJmijJtTvLbHmWbDtGkeFfFfzBiIcpPoHTthBNxyYvVyBbVvHWMiIKzTVYfFynzRruUZmqwnrRHtToBsSYfuUlLIPPrRQYRvMaGulmxuNQRzrLlRgIYVETtelPKNeEzESNQqXKgABbBirRxXMmfAamMGLNnlBUHhuAsMmazGIiHhKkpPgZOgGmMMGjeEVIcYEeOCuRsrDdCcQpFXxYyWnJjDdNbBwgpRdUhGgmdptZoOYyqOoQbqNBbZUuzHbqwYOPpoTsgGcNnBSbPAarfFRYbIZtTBtCpPrjviZLsVlUyAaOeSsbcHnRgdyDIawWsSjenNmVvMaUjRrGsqQoSsGEDdoOegyjNYrWwRqQNnynPjLsWonNJrRQWMucFfcHwEeWRhyFfYHTxkKJjBdDWwYJpPHRrDoOduURGgoPohnNwvNKkAHsWFVvewmEGwdDWoMAFfOoAPzPQOoqxduUlwuVVvnNzsIicWwcAfFUuArWuzJjyPlLNOowWWZOozYApeDjWwnnytTywFdKFbBxXdDkulLUuUyachXnESEwWesOoehcCJaYlOeOoBQgGYsFtwyziIZBQkCSyRrfqJQWXXxurAfFDdPunNUyrkrRBneaAqdDQOgGATjJpJiVvPoOdYCbiITzxXfkWXlQqnweEIbBdDkKiQVjsIMmBtIsGQqHyIiYizaMGtTgNkKPpnnYyzZAaziHhIFRYyrmMWJUsrHhnIZpyYCqHhWfFIzYHSIdqHqcYYyYyYStUcmMYTrmMtvFKkMmhtRxpRNNnlGkENMmNnbPmqQXmIirXRrhyqvwaRqgokSCmWElNnLeUhCXqkjMmYmDdMYhGzBfcCFgJjyZxUhyYpPQqteezZEEoHNnUKkoAaijZRDdLJiEDRMmPPjJkKuznrRNZFmVOKktlnVAaKOngdbvbisSgGsAHSLOZzbkoZxFLeLeEDJsDxXdaPpAvPtTpYyVLMWCCwWrCcTRwqHhZzccfNnFCXlreCYRIHOoJNCcUunjoOhGACcJZzjZzjJLlhsgEefLVQqKkdDDdJSsSFfOMwWukKCkuUKkKNnczDdyYMHKNiLeElLqgGamHcCINdDKRmtdIxXzQgGCcyYLHhfxXwuTyfFsoOHUuezcCTfFtndzATfFtTPJEjbxMmsSWwuUuUXvmZzlOOKoOrvFoOvVvVAhcRrlNADdaYRrrZeucCfnNfjJiIFkBcCxXxXbIrWcCGqQjyEfIiiVmMJxdNVvzZKjhHswqQlLlbypPYEUlnNOuZaAHJQEefaYRXeNLkAaTPpSgijcCmfEtTjhqQPaApQyYjJNaomMOAnJyYCZgGyYaAvVnfOwLUHnNhulNOoPncgfFGfNnzitTUwoYhHeioOoYlLakKchHCuzHSGWNYjjgGiIWwXxmKkbeHSsJEeQqDNmlaALDIWhLsSkcCdkKIiDEqmulbgFHhHSKoOxNNoOpPbNmDdIMovesSlLnNYfuaVvAuGYgQxXKkqGygfAeEzZuqWpPwXSsxhoMmcCOjnQqVGgvulhtcMmSsXpRdEEevcCQQzZfwiiImJqYyXHhnNMLwIiRkryYbkKyYgbRLqiIQlOfIvnHhNnsWVHGdDJjdTIouULlbSsqLUuzswWSYyPpZcjWeqQqLvbUhtwWXpvGMzcjmSwWAaNnoOCbNnEeBbBsuUXxrasUdDRGZPpkRvVpzzZZwqQGfFqWEewRWgGUpJaAjJjPuWbHKfFkeEbNrRTAsWIXCcseEdJjDSMmxIRgYyNRZzrqICBbBuLACIsOotTMVvkrRKCuZdnNDuUUuFfzZExabBWjwWkwQqEUuexpSsqQVvCPmoOhuJjUOijDBDdbAajwsfBfFcCjJbFuwZzWrtWwGRrRiCZzYhaAZmFNnIoyLtOkDgWCcLxDdeeZfFzcCEGZjAdDdroOTtqMmisiqZzcfFvGuUyUuQqbmjvVioOXHTZgHCmMmmMkPYyuMmUpKjgZNQqVvnFfEaOoBbbBEsvPpYvSsEZjgYOwqQtTiLEwGKkgoOWPnMmMuUNnAiizZnXNeQqEzDdWwdaRrXgGNcQqyuUslrRwwZbZzNxXIrgGNTtTQYywlsSNnzZZznNWvvQdDAamuuUjWwnPpqQjNVvnUHyWwckTHeZMtPdtEofFiIRrOhNSqQuUHhuFfUWwsnmudDapPDpPnkKNFuTaKkfwJjWPAamMGjJsSuHhsYyNnpKFsTPYyOgYraAOoCLeSsXxwWySorRtIdDqBbqCMUuZuUxnHQnxXUGBrPYbtzjVvrRRrTJjhQPwXPpwblLFLoOlCLWgGnNlKrqQBWwiAFRryUEeuoqQEmExXHbLJQuiGTtRAxSmjzZJYpQqzZyYPcCqhHhdDQKyqYFfxXPRBbGRDhHcmKAGgIWwomXxvvVIeqQGjCeVAVEPERmSUSVzZFALHhwWibQqIhdDmMOLjJiPxXaSsATtfzqnNtTYpzZipPFMBbmGgZAmMxbKhHAaHFieEICcoFfTtTHhpPIfdUiIXRrZHimQuTZpPZXdZnnNXNNAaoPFjxXJQAMCTrQQsipOoPIgUpzBjJiPWbdUMyFhGRlQqaGgVvKJdDvVnbBqQvbvJBAaboORDaAdDdVvsLWwHBbMEemfFHzGIEedNGlOSeErwdDXAhEDvvlLrITryhHpHXtYhZzTDRVvrdtkfFsvsSLlOofFfFWCcqvIikNsFEeXUuJLlRrlZjzBYsURYZPpivpeTtbBtThVvspAaaDdfZpPrRtTUuDuNpPnCBbvrrRzZRVszZSsbBoNHNwjJZDdRruUphvVAaVvQqHIiUxZFEeEnNAaeZZMmwWiVvFfnNInCIKjBbgyeHHOodyYDkGgOvsdYHRuhHUrdUuDInNfLlXxVihCcraxdDXCjcBboOSYXxrthHrmMOKoObWsBbrNTtzzDdwWZiIWIwsSJjcCcsSSkypPJhHqXmQqCBbciICKvdDrfFvVcncoHhymMpPYXbBfOoNUuTtnWJiafFAIezdlNMAdDxXaSsKGgBpeEPYEvEenwihHIxXTVvVNnvXwuUWcXGgUMUutiIWlPoSsPobBfFOpoRrTtTMmOSfFRWwrhHAwAjJVYFfnJJEoOeOojjMEDdGgUutTmXAwsGOAEpeEPgZzuUqYVvFChHsSzZlMmLlzoOnHhswVpRZETtmmcSsVgqRnJjNaZYTtMIimvfGLWwaQqgygyYeezzZmlZTMrpmTtZkKWIsVFQqInNXyOgGoWwYhASYShiQqfZzLYySslCHyYDdhcFRamMKuUkSYysfSRljJUuxrRmyyKMCZpizZxHoeseXxEHhzvViQqgVpFUujxXcCJYwWrvSMSsmsVPpROoyftpPZqQzBbVlhPSYyUuyYhjJOYyoHbRgGqVFfDQRSsjoAuUNABUuCuUqhRydeRIOdbBWbRNvDUWwNpVnzKMdDSIncyYAaCpGuFBNBbWGIimMeQWwqncCzPNpPIggGRfDdFrSDdTuUuvuwrlLDdWMXxmoOwlLqldEcPkKnnNcCZrGDWvwWJjuUVwdqeEflYmIJjyYQwLZKkFFfGJxqEtERwWfBaRsLUuoOnRrNsszcCZSGIyYeeEgrRrktOCjGIyUZWwpkKjJvMBiFfHHxibyofpPFOkKXxQiIuUYHyaUSXPLifBbYcCyMBpPQqYQPSsplueCcwAaSpxXOFfhGOgnLDdEXaAvIiQtrMmCowqQYHuroONnLlQqOozZQBtDdfAaZWwlLzjBvlLIcuUWJvCwSsBrUuUQKhHiEZfFJVvMgFLxLOllLLoOvKkrSXxsqXpLZvhNSLfsSuUFYSWRgGNxfFilLIiIFfJeoOJRiIruUOogGjEjfchKkSJHSJSlQwWUYxXaCcXthHPpOatlHhHhLwfwoVqqjSbcXOoFrRfXdoObLBKnFqVvECfyeTSsSPKbBLBRrLEeQqLlkyOookKnYpsEZQgAaGNoOIyYijMmJfFuUPEeKyBbYMkKmqQcUTtuyLiIVZzcCvqQluFflLMQkjjZzGrvHzOIBbaiUUVvumwKkiIhHzTfeQqHCUucfqbytTxxXXthHpqOonnNNxWgeeEnNeLXvURWwGgdhHmDlLSsLqRpZziIXxPkBwXxzjQqyPqsSbBbBcCewWrKfROwiIUubQqBbPMmYqQySszZDgOCpPldDLCjOTNnYytEMilTUutrxRryYyYhZzAaLNlLgeEwGgWGnMEoOeDoFuUYAayBZalLHiIGFEemMAadDZpWbpMmkvggZUXxPgGYyvyYcvPpkOQqFfKkCMBAaMaAmbNniQqIMkKmlLXtTfDdJjPpwKkFBbNFrliILlZnHhNzRWwWmMLzZSyQslIReEriLUUxXCcfgpLlPCwnNkPpTtiZaqNnwXxGgWuUQCJpihHyfvqzpNpOLlACBbIcGgetFIiHhAfLldDfFxoOXFfFbBaVOmwWMUeAmMznRrJaOoATWQRPkRsSrMmKbOwYSGkcCYovXxPpYjJyoQsSQjJvVsPpsSMGEdDeUOqmpBbPCiBUXWwgGxlTtDmMdhHLLYAqQafUqQExNnjJmvVIrRiLEvVylGgPSbTEetiIszXeDdcCqnqUGIioqfOoZnpPsSUuIwTYytOtTxsSQfPRTtHhQrRTjtTfFrrsvLrZzRzZzHJRvppPPrRRlfFLUtAqQWawWhmOoMEPYrRbwnNKKqYyUuHuyVgGBJgFYfPCcBtViWwIFArRkdOhhzcZLneGgFfFOoRrCcfHhXOmMZzmMlLPCrgKknNvdDcCVfFZzvqludDjJULEjJEbHhTtBmMtIwKkWgGiEuEcRsSIkKAaTutyKkxXosTiAEerRabBjJItTtSUuhdDmBFFfsIiCOoPkqQzKkZKKKrgUZzcWwEVfFIiywWZzzZfoOOoheMljJqHhbLkkMvBTtdvVIfYiHIiFnNfhIykuUKvdxJJjSUMboOBMiIQPpKkaALlHusclLvneCgaVdUYytiITuOoDiIPcmMrKkdGgDRVvPpHCYWTdOobBFcCgGAaMkBpxOoXSkKoQsjJinuUnRrNAaqQjhkKWnNRVRrRrcCvzEgPpEDdqQCkSsqKkfFwkKVrbBLlGQEvVAzCoiINYywWRrvHrduUDWUFfuyYdRnhYoOVvVvRLiIUQqFVvQcCqfdXcmjhAlbYqQeEGmyeEBbADgxmdizsSqQXQqxZhHlJjRrnNeEZPAcABbpPbSlLzZSTtsEeqfsUnKeKrFDUHlSsYyoOQmhjbjJxwGgkCFxrBbQmRrOXxVvWwMmuQqVAQqavZJjaAiIUYbLXxUeXxnNOzZoEBoORrVSNnYTtxylLvVdwtTCPIGgiYWwSkxlLCmMmFNlbMTtmyKXxjPpJijpMBbTQnNOowWSIiMkDRlLcCCNAaDvVaDdAzhlLHJjZLUQqzrRZFpVUuwbBFGNWwKHSBjvGMfoODdeGxtZlQOobAbbVvPDdolLlLOpsJPGjJYYMmcCKkZsRADnzZzSCuzKZwzfFZWsMmSfgbBALjJjdUWNnwSscCWuXXlcJYpRBbqVKeRrLVlLnVpnzlmJSsjxXFfcqVvQoOQqKJuUxMyWwhLqUuimMcuqQXryYRrYnNAaPfdDQqnNsysBbGtfFrNfFOIsgqQJcCDtTzZRCzbZAzRHhzhLWwyLwWDhxBoOvVdCcbBJiCphmQiKkivxiAatEKkMRrmhHMrDfDdFqiICceENmMnYybBOoQgVvEKSsybLjfFJXxsSBvVbuUnNlBLZicCYyIzldFAyTNnFnNmXdTKMmktfzeRrEZFTlLUjJtPpTruUwGgWQqRooMmIeElLCcibQlLiihOoSsBbVvtgVUuOVvovcCGGggGTwpHyZEyaAXxYGgSOoARpLSHkKihwkKWHqPzOoZdDFGglLEzuLcCDRxXrcCBbuMxXBbmgOokKPabBfFZzBhHHSshYyzoJjDdJhMmHeXxAzyYviUxXMitTRHazYaAPpyYMLliINCcngJcbjKkJIiyYrmIidezZEivVyYRrZmMrlDxPpPVgGIizZphZoSYlPgGpLiIKuQCcqYdDECEeAuOoOMmdFguCcQqvVUmaEeORroFMqaOHEIpNncnNWfeHhtiIgGoHhBbCEQOFfozZtIiTrsSnNAEUueLrCNMkKnNmncbBbFfBNNnnwRbSsNnYybBJzbSsBPWFfYyyyNTPpTtRQGgknXxNKXxLlOosSSsqQvIEehHNZPVvpoRfqSnekoUTtuOaHfFDdMqpsSeqABbYvaAPpeVnNvElmMPedepOIiGHOjJIbdDinNdDKyccCNMmCGguUsIDdiGCZznlnvvVgGhVzEeZsBmQqgvUoYnNyxoWqCcgGwkhfqzaEmGSsSLlCQqcVIiYyepimMIvVNnPExBDdlHhTtxODcieXTteRrqEuURrfzZfdVpqbnhKkidDrBTtFfcCbRbBIQnyYQIimoEeEWiFfIgYyePPppasIioOAiwReHhRiHhPBbGgFfppPTtsSMWwmtGgsyMDdFxXMmffFsOopPaACCmwknakaUupPMewWEUbohcCDXOSpPQqDgzZGTvVtKsaRfyBbotDdTXhJBgGbWpgWexGgcKbdRfFrDlLaABCEeRrwWbZhQqTQuUNaWIiGgwIxOoyBgeESsGveEvGWwzEWPZzQEGLuUNkvgGsmMkMVPpZuUSszvDdMHhDXxDddUuyTkPpEfFmMIWwwZoOLJjcCUvVmcDqQoPXhPpXxnQoOWLUBlbBLgtTdqQAaGZkPRQqNREqgIjJLrRlESseEfFeSsRazEerRrRrrRGglyQzZjkKAOlLDdoHhhHhoKkLywWweEwGNGdDhyRFrsWwKXJjxkFXxfDdCmMcSgGRcUAePJAaacHwpuNuJjEeilxPeCcleEAhEEcnAeEsxwWyiIKzZkUPpOnNNuURzZrSQkesYyTtGiIgNBXZeKSLxXaiIjLQEeqdsSDtYyjJkKGYikKKkyEemMXaAJnNJYDeEbubOJjxJyUYfQqzXOVUIFIJjHhidDfAqpPQyYqpNnHhjSsJTtgnkKnNDdNkxmTrCKkcvbBbBVCYNnYWYSsYyppDdwWhdDHaAXxwWlqtZfdYyuwWUDFriIuwhHsOoKJuUzZtxXiaIiAFffLiIlxXqQOTrRBSuUMmQqyItTmMVvYXDEiiIZapeZIOwWCVviUmMlLXrQNyWbnTtTkpSsvVpcCdiSgOmOovVUtTKkvVYSsAayBbNQqKkoeEOYNAavUuZvoOIiIjJIiikbPaAFVcAayxXSsaYnhHCcGgJTtUujYswgGScCllLLZzQLlJgaAzlNXKjHYSszKQqSsyRTtrLSWDvGMBbTtmxXDnNEcgdugGmftRrsSTOiuJjaApPzZGvqQBnNVvNWvDzZnQqWkKwpFfPkXAaxKyzpBbzAGtBbNnohLlhHHKEAJDvAviInNSsjOohKsStTZzfzYvVdLZGiIVMmNfOoFskKSUYyYQzZMRrCcGQbaiYyIATtmctJuUVFyYxXfdlLDUOVvkTDhHKHhAaPFwiIOoPCcjJQqHGgdDOofFeQVZBUUltTLqUuyYAxABbavxXMEmAaEePUuWcAaZzbBYCcrRrRXAkIHgGhrGgLXuUwQStIiSJjsPaSumrRMmjrREJsSXxjzZbpaUuXCOosYyuIZFffFzvWWyYuWUNnuMmrOgGoKkQqsSqsvzZPpVOBbUuoRoOZdDzsvVCTtrRrVyhjkZNyYtbBjJTNnVDdSqXxiIEfFfUgGHhNmLlMnNnGsfFSgUnNRsSrufCybdjYyJYIigGaCcYFSsfQyYqyXxjNngNQqnDcLijxXlzZxXwsUuBbiabBxXACFftNReEMQrWwRqnNQGAaGkXUuJpiIPjjeEHFfFfOVRrzoQHWnNClLMEeibBkKImcwATtPlLCRrKksSCckRMAamunNASNLlnsDdmMKkagGoOsrHNnLlSsGFfZlgGaSrwWReNndDElkfaAvQgCLlWWVvwLXxlAlLNpFcGPEKkmRrMDbYyYRrEyJjYxRLFfTDcEebBZzRQqLvHhVlrsENnhHerRSRXxrymMCVvNbBnLlyYcYvTtEqTtnxXNieDozZomMOphQXxoWEecfFFXbiiIiIZzQKkMcCWnNBbiIBbEeCcWwcCpGgbBMfENneFoOwpPREdVUkKSOXxfFALlaooOSrRHhVTtIUuKTtIFXxfikHhcnSHfFBbdbBDqzLKkYAayKNZzWeEwSnhXMmxASMzZmZzUsmMyvVgGDqQdIiYzZEezpPlLWhHwEXxIiNnUDdXxgYycCZzXxfAaiwWIhWwJgGNoxDCKNnsSkcdXOnWwjBbxJdDcCZQCcPpQSMmIfEmgGMeJjLSHUFfsjJvbaAqSsQBBbJjzZndDNVBbyIifCcFlLjUozKklLLpPbVvLliwWMmMmTWjKBbcCPJcQTSPphTKEPoRrucCcizZliOShuUfFyrJGgXvrRAWejZzhHcCMzVjJfFGPlDPpLldLpnDdEAazIlLDLhRSvVvoOwWudNnAaWglLlTyYugvYgGtTOFbRKkrZzBxZPfFpyBVvZVMCcmvgPOKgGnqiIPTtpMmQJCcFSsHhJHhbeEhHxnmlLYywuuUHoUuxgCkRhHamcCoOQgGqMspPUnNumMNnSCUuCSscctYyHqfUuRQEIiAalrRZTtABjJcOoCSUeEuDqQdnNzZlyJPvKKMMmEiDdOoEtEeWwwHhWTwzWvhHEkKpPEeORrnNxwCclLkKPpuenyYNdUaARbBEepAtGgRrqJWWwwudQfFeYUuxXQqPptTkKWfQqhHZIkKipmhHKqQvVqQywWYkXpPdIiDtTwZKYydOoDnbjRrwWdDRVCcROygcNpPGgQclKWwTtTfFyYoOWwIUNCcgWvJjAOoeqLlXxLkWwEmMieEgTtGIibrZzzjCmArFfdloObiIDLlqQdBiSscUuCIznNfFDAcsSCmMguUOeeXkKtUqqQlLyeEaApLBCuUAamsUudDEeqQwWbwWBUuknNqwWCVvYBMmQpPLlOLlaMmmOUCcRroIiRrbsSBVXyYSwaAWHhsyYvKMmkCcazZiITtpWwQqYxwxXJZcRBbuUmMLVDnIiKkoOkKnMHcChzSUuyYsSsyYJJtTLSigsWwSOzhHSsHMKvVJcCjkkDfLlFiOwWoIjQiIWSqCqsSaAQlxXLOoTpQqvkDPRHXvVoOxSfFsJAlxoOfwWSsIiILlIwWJjnFftrQqzZAnNTTyljVvJQqQyKkxgGRrhjpFfBbEeHhBbCcOrRWkTloOLFfhLKklHtBbSsPahOogCGBAawZzVOorjJobBOOoTIitZAvEAaeCrLXxwrREnHTKFEesStTfSfFPQqGwrmYyuUhHlOaqQAGkKgOJLHobBbBkKOFemMEfvVhvVbBuvZmRgGJEDyGJfZEezMmwWawQqDdAarNinRrNlLfCcCcYyFIixorqQzsfWxdsSThHdorRLlhiBGgbgGIHiIMmhHDdZzPfNrsShHQqJjRqqhxXHQeEiIMhxhdyfFHhFfwWGFfgQWhXNnxQnhmBbMfFHNCNJjBbYyDdgouUObBGuUWcvECEeoOWzmMZXamMsStrRlLfpPScCsvsSAagGxxXzZXtRoOrdDfFUOgGKjJHAahTAGgshuUdDlxwWXKiVGgvZsRrSrRkKzJjOzZOPqOgdRrDCOoKkGgtaQqFZznpDdeEoOJAXIHlFfZaAzJrRzOqsStTxAjSscCCoLMvVWXFTOotbZrosSyYBbbaABdDUOoDcCDFdrRUuyYlsSLEWkUWeLlrCDRrqiIQlLgtDdTdtAanhRzGghHLlKJOoDdsSqQAjJEsFfTtSFfcjokKoCcVvOberAaWwxXqRrzUuFJSjOoJMoOxQqXZzVvGgJCgBeprRPkVkfFQcpcCPGiyvnzZyYNNnkBCdDryYsnNSleEosSyYpmzZMWwuUyNWwFRQOEeopPDwyQqFfhPvJCcdDBbbIiBOolLsRXxrcCSzYbPLshHBbSKkquDyYdWLolgGlsaaMmnNvKXxkWrRzZDdhEBeEboMklLspPcFfqGBGgJVvQnEeNqaPFfPpPNNnnhVvlLkixXYxvulLUVXyQqnoOKkqvHhPmMpVQOxXLnzZNUulJKkjjJoeSOoKSsIYyDcCmMzZgxXjBbGzZfnNQqyYFgJsSsSYywPpJjNnWGZzkAaKCvVyYieEEQEeqekOoUueEXxszJjPnNzVvcSsIidOTtoDCvpfFBbBoOfszMnNmZSFJqQiHJjhLqwWpPRlLTtWweEeFfpKiuUpPIKkigzyYrReoTtUunNkKCcgHSscCEeIihmMYzRrNLSslQxXCcAjTwWOyYSFfsKGgkcCxOzuUanNuNpmMmeEMeBeWsSBRLDyYOREFfehHPprFfHhzZywWIoblYXujTtWwWGatOJxXxXGWVmMbBcpPHhJQqCVFXacTXxCcFAFfaWZzgzuUZcFOslqQLVjrvVzWxjJikKVvhymMsSCAacYpYRrybBPhSxpTtSsCOBeaAaoOQqzZAvpEpPhHeEeUyfFYrRpZZzJjtToOsdDSxYyAnmMFfIigPbBpZzQVeEJCcjAkKLlfvVMWbBxfFXKgUuGYNnykwhjJlLHOxmMsQpLlAwWaZOpqYJcYyNnpyYVwWTZztMmDdIiWwNnwWecAaqqQFfQmMvRkKKkGgeOoEdLlKkLlDTnNXxGgLexXELjWwPpGgJSwEdUuAMmaEcCZzeMJbBmAaAaWwmMsNnSlEeLhHxFfkKCckKHmByYwWrtypPTFfzyGgYOQqjJXxAajHhJXxjiIaAJiWwItTKkozZqVvPoOJjgGEMmaAjJrRAzZaWYNnyZcCOgGEevVjaAbBRoDdinNmMIQqORrrJnVvaAYyAEcRrPpCkwGgHhbJnRrJXxjlLUuNHhIVvMmijTTRrOgrRGBbgKSsVzZIwWvBndDNgtAIxcIiScCbBjJiDdfZzHVcCMuUmvVcCozZCYabBBFfOwWogGbUuKkWvYfpxXHgjJjeDtTUuWwTRoOsFfHhMlLPTDfAaewWEKaAOsSMNnmDdNdDhfJmZzeEkYyrgGyYLlqIiizYPpUmMYlLjJohNNtTutVZFfjcXCXArRaUnNXxLYylFjHhgGnNpMbekKEAVsSvuUnNNPpYykzZKFYTFfUtWJzYyZFfnvAycCFnNfdVxXvAaAaWwzZMmDXRreEKXRFYyKkRDSsFVvuIiAPGgWiIhJANbBlNnLKknsFfPkhEegGgaAGHNIZRZHfLlHSCcsWwSBkKStUFfuLWwlsAeVcisbJjBLgGQqZzSIiUujJDJxmzwtBYCWwyWwVZhHWxdniIcChHpJKkYNnyvxAdsSyyYYrRDQqPOPpYFfybovqQYpPLyYDkKdYGbNnRrzZBiIrGDdhmWwWbBOowgVhOoUnNqQWoOcPBpAJFfyYUKkrDrBMRmPpYymZTthsSHzdDrYyREVvUBgSVvsGGGFfmMsFvVpPzZJjyYbBfpwWSPpgXxGWwXEeILlixeGgacCcCASsqQECOZzhHNrhHlXxpRtuUTbzFSsZzuFelLWwEVaAvnNkKFuUfWsSOowfYylLOoWwEePpXIieEVvGxjYyGGlLmvVMWwTtKWmMfQYIiNduiZzJjIrnNJYyBtTDdJCoOtAaJjdlLdRrUpQqCcBbMoDdRrOmPBCoJdBLlbXTtmUuMLlPDwWdDdRCZYyLGgGglzFzpTTtpPrEeRMTtmvVpdDFLlHTBnNnNDdgvVHhGScuUJjtiIIvVmeEUPpiIfVvvXxVtTUFWwDNpxyYXQqAjJEenSXxhFfHmInXxNBbiZlLzuUXtqQcUvzZVrtTpCwWrMmlLNbBnxXRvVrRvkhEgsbBcDEeyYdKSzXEYyNbdhMmHDVjJkKsxszZzZSiInNJTtjHjJhHVvlLirRIudkKGeEkKguRNnrUlLfCFcCTtgGmMjmMqQzZPhoOhHdSsyYvVBaAYmHMknNvVwDdWKDdLgGloGCcgXVvhHEWwoOeHgzsSwEePpWDZeoOWwoOEoONMWwmHwWChtGgaYypPkKAhYQAbiIUVHPjxzZXGgLEBjJYybstTMjDdvVbSFpPfsbbBBBOoOHhoWwRifFHhwOcCyYoRkKRrMmzTAatTWwcCjJQKkWwAmManmMMftSCPpGgjJaQIiqfFvhHVzZQfUZzEnNyOPpgdDGUnzHhKkvhHVGaPpIQCcBNnXxgGbhHJUpPIVyYvxXFZSszNobVvBOEeFXJxWwXjPpxXWSNnsSuaNbImMiITsUuStRrTNntbHhNnwGgWuUBMXXEEekfFKFOZIoWwJRrWyYwwWRvKkdHhXQqxEvAtFfWEeyIoRrbpPkWwrxXRvMmcCrRnbBqQwBMRmMrKKkeENRrwCOocWwFVJZeEgyYoOUMmzBLaLpFfvVPAasMmwgDZzrRfDddEedDtTCxXceEDFdYyAUQuNAmwWMajAaJjiqAOnNodDqibUjtheEHWGUugwKkTzJSFfsjZUuAaJRvEeYtTyLgGeGIfFRrPpiKjJkgEyYYyCcUusBNnqQIiEeoOEekKbXxhhvsSylLCcvDnXxXTtxBQqzZogZVFXdDLLllJTwfIDdWwMlFfwgGWLmYzZaAELGgleyRrsSiFevAjJlLayCyYpPJjfXxqQtTFREerWJGgjgrjJBboCcPJjfFBbBOohFfHoOsoXxVvBbQxnCEeZWbrRvLehxEYyefFfEeZzZzNSsnFtjeEJaOoSslAaHXSnNtTkvgGVlWwOoLLlmMjyaADDdAadXxDdlCqQQJAyYOQqoWwseESchHGgdDaUueEdDpPLljJRmWdWwNnDFfURrrRjJHXxoOAaWuOnNQqHhvFfqdDnfDLldFMmWwzZeEcCQqwLMDdmcUuClWwNnAaWaAgGMZIizmqQaAfbScCsqQJjBXwoONLnNiIlSNMhzZqeEJjhHQJhycEegGTtMbBmnNFCOokKdDWwHqQleEYgFfIiaAnNTauUAOShiIGQqeEgRrHvwWVQqiKksSaAIuuUFfitTqOoqQNQqbSsBkIkKBYyINnNxXpPrpAATtIqzZWwqlLQaAkKvEfKcGyJjYzegGvVtSXxfFWLlOOopPJjoHhGgjJrRxXQPEepdDpPFNnbBkmMKIQsdDSqpDxzEeZXBbfqAaQNeEnFdkKqQMmkKmVAwWtiIGgjHkXxgGRSIyMmYpXHhvVfpPFjJhlXxWwXxLhHESssSfQqFTkKlKiIkLVqyYQDwwWMmeEGZzgAIiQXxRrgTTttZzBbZzGqPpaxfhHbBbxXsiQaADyaYyWwWGgwWAQqawRSsrAAGnNUVvHYhHuaRrAUoOhCcMxXyYHBbtdvmMkgGeEDLldgGxEemPpdDjJaAqQHEgaAGVrRvnKSufwWFvZzWwKpPkVKkIeKqQFjJdDnqQlLxXUuNqQxGTtoXxBbODdCcUklLKGzhSejJEFzZLlfgEeGiIeEsGgkTbBtJjdDSyFdDAFfgGKfKkDtdAaDTDIivSzqQtTZzIiIiySAUuYnNUWweQqwWEUnNuuuUqBbEeBbrRQmMHnNMmhzZwWTXxpPxkKXOwWotuCFfCccXxGgxXDIidvsacjyPSYyFSLLlTtkKjOkYWigeEvuUVtgpcCPLldDjBbIiIvVdDItTRrHfPpkZUulLvVlLzwWeEfXQqxMmFRjJzjJZdkKhHSsSsTtNehHDdxIicZzTLlzZCYycCgLlaCcRrtYGgyTnNJjuMBbHvEeRiIhwaALlWGgWwHkFfdDLiIlnvxkKVcqQCKkHkDdaNnABbMmkwrRWSJoXxtTXxnNOZfFzWwjMoOYdDBbaARraqyYTtOokbmMBMmoCwTBbCMmiSsINDCkKcpQqsdDCcIinBbyhHeiIEibBIiPWwoOGMbBmOoFofWAWPHhYkOpvpPVWQqHhGTtxXTHhtCceENgWxXpPkGgKwbBZlwWLwWzTodQqTAatQdDGJxXXeRBzZMmbGgrzZGeAaAOgjnNJGMdDmHdDzZVVvoOhHCcvUubBSsFfhwpPFNnfWycjVvWiOmOoMEGgmMBbewTtsoOVbBwWKkCcPekUvVUuFfFfgGAYyoOUuCcCJjySAasiIYcbpKqQKbBTtkjJfFXNnxPgeJjSUgbBvVFfiIFfMfFmmMDdeCiIzeJjoOKNmMrCcRFfhxAUuaXuUHyECcefFfeEWmzZMwRqQZzxXeWwlweEEeUzJjZTuSkTJjNnnNwGFfCyYAacNMlLzMmaiITteUuRWwRrvVrayraAfFRjSsQqrRJYHpyDSdDOoxXjwWJyYrNnQqUuceEgRjJrGVvHhAqQSeEWxXwXiIfOoFxxuUXnkKmMNqQHoOhivVzkKXxRrtLlPpaATZfFrOoRxEevvVqQbIikKBfDCcdDxiISLlQGgGgVDdMbNWyYwcnNCmeEvxzZXdDTMmSLlEeskKuWwNBbmMyPpYVypPCcGpPgtdRZsMCcMmmSIinNYCcyzsSSsvIlpRrpPPWfpZVvgGzPVvWwRrHhsSFoOAaHhkKgGSspPwtTQKuUVvlLjWwJcQYyqcCCkNnuUWOowrXxGgRbNEeQMmXxqnGgDUuKkdkPpNcCnKCcewWdRWPpAOoHhaAapdrpPnNJapPAIieeEFfdDzZzPpYWznNZMmqQwWwVeEcCOowUBEeltwWMWpPbBwHoOvQqyoOYqQzZYyMmSQlIigFfzZEDcCdCcTtMzXcxXCxZMmUzpPZgGxPpXDduqPpQmtTZnIFfiNVvzVviIRxXPpQZJjztXxTAawWfFqHFgGfNZztTTtlJjLhHnhhmJNyYOoSsBbKhHkYyeTkKvGgGXxpPNrRnMLlLtTVBBuwWptTrILlivVfAkeHheERrEokKkrPpzZfFlLzWwZJjmMDmXxMdFfdDMBbduUbBDeYyEPpKhHkuUuUadnFdDMekzZlMmeErHhlLQqNsroOGgROmdDyYMQpPAcbHOoWwkKTRrBqjfFJsSoTtOsSUuWeyNbbXgGxbBBBXxNnDHqQhAbBxXaDdDdsSdDwWuLlUFLlwWZCczVveEYPdDwWZzpyoOduQqJjjEeoOTtEDnNWwkYLcCNntTgvMmVnKjJkFguPpPpIZBbDuUxxxXmMaAzhdDuUtYSSssMmeERgGnNyqQYRkTtKhHFfrwjSHhdDWwQkKOoXxToOijLlJvQKkvVUaAUuIOoigKkGzZNfFtTnMEemKmuUMmFfTtmTtMqQYymMMHIigGtTlLdbTRrteEBodDKkcCiIKkOxXWkKIrRXxIbCBgwWGbisVvpvmwcCfFTtaAfFEUbHJjzyYZGgWwhGgJMmRreZyYzNkKKpcmMcMpdOoDobhoOHzZAsPpcCSZzaTtBOKWTLlmCRgGYKkOouwHhJjWPiIGgsCUuGgcCjJcRAXxdutvoOqDdQHhqBqQyYbWwhHkKQmoOeKkHpKkPuMmUHhDpLlhXhCRUuIieYyPpMmIiLEehHcRIEOwWcCoVvTtzZeYzjJZwmMLlnQKQyYqjPpJgaAdDRrqQjJEtEeYaAoOXxydZzSsIkKEeBbikxXyYHhZzZwWzeZzdgJjGDAzzZZgGBbCUuCTtOoccBgGUwHNnhNeEkKCyjsSJYyYfDlLYEkAGwWDdgzUukKnGgHFfGgaXEelLJfFmOgEtvniIFfNIFfklLDdKIvVMmMuZzZzULEeSCczZsYKkyvJWwJjCcjVeqfwWFAaDdSeEsnjvVNKkGqNoOhHlLIdhZVvwWyMpIiiIYygGvVnNAaWOBtTFfdDvfFVbIiInNihkKHsSFfBqWwdIiXbGgzZZzmMOoZzDQqmMdKkPpAasULluSNnIHwWTthAGgRUuraFnfFkKNfpPEdDWwuHCcTthCrRtTwQvVLlqWNdDadDxXAaOTtosaFfVvzZQIiFfUuaAZzXxBbhOUupPGgcCoHTJjTVvzCcZFfzZgQqAaGjJYyOofuUFptTOoPrRGFfYyoDifFIJIIiihuruUPJnDdUuNVvQnNqjmHpPhoOZOoOYyaDdBbHEemMrRGbBGgXxTJGGrRgwWWweEnpPNCQqmMhHvVpFeEfaAPEeqPpQfFQqQnNqeEQKkKlgGLTEDdcfFAaAkKbBXcCxaAafRMmrLVRjJroNXtehdDHERrTjJBbyYzZTpEeXxaCcFpSjhHvVuUVvaAywWBPfIoOiqSkKsQowjdDJwoOWzZyYWbqQdDCejkKJEFfhHZzcHhIQuqxhHXFfaEeArRbSsDOLlQcCqxrRJjXeCcpsSPBDdyYPgCckMmwWkLlraFfAyYIiaAkKlLZzRQtPpobCcBOdDTDqwWqBtTvXxVxdjJtTDXDuUdmdDrRMGggGGgCciZrVvefFtTEZoDAGgOoaYyCCcCyYvVxRrXbBfFpPCcsSqQldDfFBbjZlNnWwuQqDdBsfMmFVmjOoTGgtvVJMpbJjWwVvBIruURiPveEGgGglLVjJbiIQceEmMcCboOTnNtBKkCsSQqqemMgGdhHRrzZHNrYyREewixDdmIiTtMwAPnNZbBJJxXYbBOjFfVCcyYTtvcCkKfuPgGpUuUnNDdRzgKkoqQOBbaAzZKbBwcxXvVCuJuUERrjfFmSMiImGFfaPpAgzZjJYlLplLBbKBAafFKkgyYLlaJlBdcCBsIiRrSnNDwWoOlLjRrJaAaLKlRrCcMmLWRkKKkrwnNkRrxXXVvUTtuxjJzZkfFKiIGgbBmMnNTtTvPXweEWACcIirRcCKMmfDdMmhDDddHGgZUuxXdDjJiIUhHjYyJrhZzHrRfFTtLVXxEYygGoOecCvzZLWwllnNREgGxmMNjJvVjJGgKkvbhHcPYypCmMgGkKPvfpOotTxXhqQpPHkvTQlWHZznNQEeYGgyMmcCDtTIMnQqiINraaAKksSqhWwyyYYmdDMzZvOoEtHheWwvVaRTbBQkKqkmPpaAMcCrRqoFfOQpPClLjnNJlLShyNnYzZHpHhaAibZzBxIYyimMjJfLVvrRtQKCRTHhtAaVvOKOoAakJjzZNypPMAakNUBbunTaAoYyOtUjIiwWGVvhdFOocCYZzywWMmtTKkCcMmOFfTtlLdDGgLOjOZzwOuUoCyKAaknmMNrLlYyGPVvFmMgGVvkEeKvVsSnNFfQqLljJnITfxsSXFnNtTpPPpRrtVHhvSIRrkUjJAajJuDdPpmYyBbyYBnNbhcCPpnNZmMznwWCcFfXkVvKxwRrlOoxXvVpPcOomMjVASsavsUuSJpPWwWwjIiSHhsJjTtZyFtfKkFKBXxbSshHxXUuWwgRrhYyHhHGPAappPWwjJkvVLUulKJwWjuYyUwWWbBCckKJjAaEATtzJbBjuUWxxnNXXGgTXxmcZzCCclzkVOovAxxXlVvwWLvVZzoOMyiQqwFqsSVvLlFjJfFpocCsSOPFfflwzZKkHhaAWNnwhHMmDdBbdDRrSdDsVvSsuUWmEeMLDdlcCCcajJgGqqQQMmAVdDlLvgGBbpPDAaBvVbrRjJhHqSNnsQSoOOoOHvVjJmMnlLYygGhHNBbhnLPbPNnpVvEePyYHEeWOowhXxiImMYImyqQYYyhHBbMFBjJFfxXLSGQMmhGvVgZzTaADdvVVvQqtXlzZzPpZLxBbjAafFOoYAyYaUMgGReErMmCcmbiIaTtlAaaKkAJjIwWiLvVZzGJTtEehXxVcIqkKwJfSsFfFuUftFfTOoaAGJoqQNnkKHQOoKkEnNeXxjJqhdDPpUHoOiOosGTcebBgepPGgnNqIiQDmMdPPpkDdoOOoEhHSsfqtTvVQAaZzwEPpJjdDXxXxgGCcyYmMpFfVvAaSsfFSEhKkUujspMyYhjLlgGsSmMJWwoOYylKkOVzMmxXBbcCbAaSkIiKVTtvsEedDboOuUuUlLlIidNnDVvLFAaYiINneEfLlFRhliDdJjILUuIXnqQNPDdpAaNnuUBetTEbkZyYHhrWwRyxXYzFzyYcCnNcCiIDmpPeEgkKlLmLlMXxkbBYdDyxaAxVvFfuUpiIPXSsHhrRbBXbBKRjdDJNFfIFUufAainHhaAEcCEefFmmwVEOoqQmyYiQqIYyhHsSxfxqdDQFfPKkaAdLlzZfUuFDsSxXpFfTTttpPNnMDCcdIQqQAeLfzyYDdFtnNtTcEtTewWwWxXSBbUusCWwIiTvVYnYyNWwraARyfZFyYsJOZwZzECceIiIiUjJmMjNnJQqzbBZcCzZSEtTezZNnsGJWwjRrYCcyfTtQlLEejGgKlbyYdDssSiITVvtLHnNEUuWweaAOoseESadNnGTKkcUQUuquPpkKCtWJjwZvVtTIiIipbHhbBDdtTaFfAZzBAaqgGPAapPhHoOAdfeRrEPpvVeXxEFvOozZgxCcAawUuWDdXeXxqQDduUeEbBfFErbBTtUMmPUiNnZzIiINtTnKkuIGjJzjrRjfFJrGgPAwsSWNOonBVviwWGgIbIiSwWBbNnHsSHhEntTNejJeEeEoDdljJLNnOLDdboOBEGgeyMmMmPpYtTyjJYlJxXuUJjeErsSQXxqhrRHcCRzYyNcWyYwCeEcCjFfJOGgoaANBbmMRrVvnjFfJiDiIdTtssfUDduQqCcFpPoOjgCcZqQXwFfWeNVvnwWEMmeadlLDVAavKWMGgmwCcxXAaLlttJjTTjHDdhlpzZLliIqkOVwMmWvCFfcEeqQqoOEeQKdDEccCCegGXyYxPTtynLlNrRcNnYHEbBefNnFRoMqQjwFfXxuUWXxWDdwRwhHguUGWMVWwUBbAaurRqQkzZKWwSJjTIjXxJidDtvVuhlLHhHfiIoOFElLjJfFeCcUUBHCBbchuUsSbIKLlkcOoCPpiJjzZZKSswbjJBAazKkpPxXjJjJZoOWNnkCXhHxKkcNZivVIUeVvglLlLSsgGcLnNKkDdtTrRDdYylWwSrSsRsOoxXoOzCcZCsSrxXeERroOEOoPGgOkKoKkpfCcqQTtEEeeFQqqQKkPPrRpTtrOoBNnHhbReEZzpEehHmMSsDfhHbrRBFwWdhHvUPpuVnNxXpysSoOgYyeuUxXEGTtJaATtjBdDbCcjJdmMAaXLjcoOCKkJReteEUuTbBpPHVvZXxzkRkKBbCcraAOpzuUZcCWwPZwWzpPJmfFQqHUedDrZzAamUuMBbRVvbBuIinNUWwEdqQDexXEwCcFfeEWYqQyzCBbSxqoOrRtTNKkKkiInriImSxFPpfXDdyYOooOsbCcWwzZqQrkKsSRRraAcdDFfFfiICNsCcxXSlvVyYRrZDrZLlesSExznNZoxZUvVufFaApPRrmMNnrRDdvVeLaAQhtVvTKYfFykHPaWwCFsSgaWwwWZLfFXtTxlcCbBucCCEecLlUPacCwWIwuUUuFfCcSsWiDovWwcCzVUtTuvZeAaEeElJjCbBceRroOELDdlqYybTtqQIiNniTtwlbBLOoUrRuWdDIfTAarRtnlwWLwWbZzBDdNatnzZNTbBKQqwWhHvlNnLAaVLKkSsqqQtYyTHgUOfFAHhdDRrnnNvVfFYyMmgGSBbsyYNAaRzZSspPpuNnqPpQLlAaStTsEeDDddXxLlyYAaTlLtCcfLlFUuGgNkKnHweEHPrSUubBDaJjAdspPLlpPVvwhHfMmRrkfyYFKFxXHhcCcqHhQdEeTMmtdDlbBzWwIBbAKkbfnzZNFwrhHRBbWBmMgGwuUWlLHhHnNNnFfTPplAayYdDIPpiMmaKHLlhPoOpkJjMyYHhNsSXxuHhYDlLdlLIiyrXxRUiIdDuUKkETtBjlLGWZxbBDdTtTGrRwQqqixtgGTSsXMxXeKkwWEJkKjJuUgmMGuDKkdIzZrRDkKHhLllLjJdQqibiImMlLCNnjJcBJjUuAnveeEbBrRWcCDdwFfAsSlLUuBbaRQqrmMZcCIjeEJWwiHrRtTZzROZzkKLloLlWPptIiSscvVcCGgWwCuUTZzHwWiIFwWPpHSsVlLFfnNFuUfKkxXnNoUuOIiNnMjhHlsrDdRLlvVmSdjwdDEaAJxEeCcXCcfOoFjXxaAaCclTtLPJjhHplLtFfTETXxtHheQqmaAOoSsILliZnHFfSshuUNqQUBmMbuYlLYygMYymZMmzGRRrEnOoMmjYyJNgLlmMGTteQqJjQqQKkqOumMJjUsSokrRKZOobBOoUZzuhaAHzsvVSRrODdyLlYVxXEevxXdDZJjlLZzMsSZnNNnwWviIZzAaZzTtBbeEgIwWiGfdDFfFfaAjPpJUuzpDdmObBogGSIisMPZFLNnlKHhwWXxwWTtkDYDHhdvVqMlkGgKLmHyrLlKkqdDARqQmpPMraZQDdDWpYyPdDobBeVvEOhHtPpBbTwCuUWwcuZzHTtJbBjEBbesYNnHoOoZhHzoQSsqOaAjJGHhrRgeEpPYyjJGgiJjoOmGgMIeEfFiIHaAINniflLFhXjJVmMvwWxNpPnuUEZzBbgGoOxPpRrXuUBbZzofwWsSAaqQgmMLlGYwkKWDdwWgGqdNngxXEexEyYFuUiIgGyeRrEHPBbGwwnNFfWfFWwoOMPpmtThHQKkqCfFYykKhHYycjJIigGiIQbBqgoiIjJZziITBbbbBePpEqQqQBKrkzhxXLlSUusHyYZaHhFfAIiwtTWNnZzRrDdtRrUVuAaUeEvuXxTRLlrlLuSsUVvCmMcGwWKqQlLkgrRkHhYytTKoOaAgMxaAcCXRTtrcNboOBnTtAaCeiIEHFfoqeEQqNpPnpPxXsSuUpUuqYyGgjJQPsSIBbiHfBZGgzbFSJGgjsoSsEeEeEeEtSsTsSIiZQGgQYyUiIuqGgFfGoOgkKOoqccCCuUgGedDEaAwKfFkCcpPyXjJxrRRrYWeEzpPOGgqQEeopcCfkhHUvVugpPQmMsSVvCcqqSsCcBgGsSEJjTzZtemMiaAFWwfEWkKweIbLlUuqQQGODddYynNXxZzDfsoOXxSFNnmMLXxHhNFfnloXxibBfFEeDdypVvPYInNbVvBKkqQAaQqdqPpQYZsSzyVvDdsVXxgQqGdDUufFvGgJFfBrRnNbyYMmjUuwiImMQqWOopPEYydujSsJUDkffysSYyeMmsmMSYyoOEYTfFNntsbBVvSCcIdmMDifFFfbBSaAEzeEZCTtcvVwWevVpPpPUuYIiyswXxWicxXaAiICbBsKkAaKJOotThHjMAafFtTIYyigGmSskYylLrRbBZzSyYHaZwNnGgPNxlLmMXIqQcFNntllLLIiTFfZOozNnTiItrRfEeCUZCcfFlLLaDNndAlLbnNKcZdDPVxaOkKEewQqZzUuWonbBbGgBNAXCfFRrcvpMmwqQCcyYMmsSIiIimmMMCnNIimMYGgyGKfFkfFFcTnNtyMmiuUuUIrDdRvbBViIFQqfLGglyYjJKSwWsWOoAaQiIbBwWtTLlqdDNdDnOfavwWVAmMxXcCcbBwWvViICFfsOoSsSsSSXxsdDJeEjSstlLSsSSsgyYnNmMwtTWFXnlLNxtTnAxqQRrjJXmMkKwWAvVaolLOUuQqrRGglWhHwktTKmMOoYyOSsotTzZlLjJlLVvBuVvUgGOobIiJhVMMmmvHzZPpcXWwxCwWADdtGgTarRJqQNYyPpcRrjaAJnNCnmMmMXxTtNtTtknVvNKTnvVxXqQtTSaAExXKkRrbUuWoeEOxXhHwWwTtVdDvBPLpPluUEeYyAatYeEyfMmUgGuJpRrPwFEefWjJaLlAmMJDdhHNndDIijpPJjtTmMVvfQoOYQqyJjqFTtaAMmsEeSEeXgGkPpHhKTtmMTtIovOoTuUtVPjJokEeigmMGsSyYZzXXxxeEcHaARrLBblEerEeRLYylHhxXlLNtTnDdfFyMmNnWwWwYaAfFFfZemMibBJAaHGghjJiIPpjBbjJHhNniIWOomMXxwOoYyujlLSpPsRrVApPaFWeEnuUEePpNwfCcpWwDdDJjdKJjTodDfFOcCwnNWHvVkvVcCKhUyuUYpPuUuJoKTtkVfFbsSBPpvOoOjJjauUsSSskKzZUuPYypAtVveEXoOxLlTYyCSscfhHWaYyAoOXxwDdBbFKkiIFfCkKcRYyriIBsSGEiIyYeLlgoyIiqQYIiJZzjMmIiQqORYiIyCcrxUeJfFwWbBjAaEuCcPpfEfFGgeFcCCcXjJsSSswWPoAaOVvpKRrCnfJjzZFNcMfFGgCmMrRYFfGgyPpcKaAkHYyhbBOomfcIiCKkyZzfFOoFfYWGgIiJjUuwFxXOgGjXxwWJJjopPRqCcQNnrzXxeEhHZVvRzZiFfoOnNIghHyYsSlGgLfFfDdqQOoduUsSDHhOiIoEWcCsSGNnhHgoSsDdOlLwcCyYmMmMqQeCcMuUuUpPSsBbBoCcOvVbCcpPIEeqQIibDrRdGgEeBHhajJdcEhHeCPpDAiXxDdsSqQAaXxmoltTDdRWwrrRMmHcCwWhAaWwzZLmMIlLiIiIiOsSiIqQVvHNnhyYklLKyKkhxDdXHlLPpYvPpDbBdEeULluCcHeEhMeEmOJDdjoeHhCWwyYAaJjgGcoOQEeqGgDdoOdFfySnNiIsXxicNnPpCmMEKkeTtjJnNgGIhHJjdxXSxmMXhSsHeaAEGgguUGVZzZCBbccCJpPlNnCcLxXKYyUDOodJpPoSsLlOXRtTrHhYoOyPXxpczZgGCqQBbuZzTeEBeEbhHtfFXyYPpxbBgGrRYyDdpwWPPnNxXvVyzFSsAafZaACcDdBNzZnVvbFfRrPpQqrRyYJjngGfFNiIMfXxFWwKkmNCixXjiqQFfgGIJIxXBbpPsCcSlLcXQqGgaAbcCBtTmQqGgFfpPuUbBtTLfFldtTDeErVvRMbBxyYEeWBbwKknuUzPTtoOprNnrRRHhuUsuZzUsSZuUJjXxzAsSaLljJWwiIkexXEKRrQqzlZzLUJjuZTHhwWtjJRyYWwcCPpxdDXHhPpBbrAaXxlLyYSezZEzGgjUNncCwWrRkKbFfBMwWVZzvMuIiUmHhjyYLlIiwkKWIipFfPRrUukEeBbsSfFKIixxXmMZVvzZzAfFazRrLluUjBiiuUIaAIblzZLoOPYyAanNpBbztTVvTtLiMmUuNnIlfFHehHErRbBbrAaRLlSsQqBZEezLtTTZzADdnsSNatlvVvVfFhlLhHbfFLlmyNnYMBLlZfFjJnnmMbBQqGgCqtJjzOoSsZTJjUuVvtRrTxXQdDDqaAqHhQsSjZPpXxZzzJBbJjlzZLlmrRUuMVvpPeEEecCLszAaZmMOoSPplLQmnxKkXGrRApPawWrRTZztgTfFtkKTwWlbBfFXxwqQWjJLJjAaIiyhHqkgGsSieEIwnNWZpPQJjpaAwWwqBbfFQIiPiIpWHhHhJjtTYCcyfGgoOSsKkhHcMCWwQqjJSssSFUUuufFJrRIiDdTtjEZUuzUukKYcCiIeEtzZTKTtHhkBhHbyCgGwWcDANsSnakyYsBbuUSyYKxXxXnQoOtbBTnEefFRrSsGgUIiwWuqoOBsSbaAoOGgBbkmMuUMBbmKLVvsSdDlEeCVvsIiScCZjFQqfJlsSLxbBXrRzmgGuFdDffFhHULlMfLlkKiIFhmMHUTttTCPpcFfvVAeDdqQWwEIiaLkpPKlhHhjxXXxXBbjJDEedUuxJHiFfIuUWwGVvgVSbBTtseXxEvLVvllLFfSscrRZzCyYZtTzwgCcGpPnNWRDdDtTNJjnvVdrvGgVvdDfFaAfFWwGglLDdTtnNhHiIiyYUsSLluIKvwWFfVgGkyYiwjJWymMYtTgGmMtbBeETtTuUImIiLlMjMmJoBbOpPyRrYdCcDGMmgEeidYyWwDTbZzBfFtSsTeEhHVvjNnJrRXSsxaAxIiTtMmEeNnyOoJJjNXxnjfyYJjWwtTFCvVjJcUYyuYzHhwWuUmMZOoXEeWlLwaAvbBVllBhHYybLMmxXHhLLHhOKkolPpACVvboOcCBFfcanNAaUHsShYyhHTTttIiYyJVvjgGSwWUudDsdDPpuhdDHpxXpjJPardDRApDhHdPofXxFVhHvZzOhHyYuUtTCcaRrAnNPJRrjmMNnRrfGcCgEeoOFyeEYcqQhQPGkKgWoOkrRKwWsSbtTrRBiIWpPweEYvafVvFAVvVEmMdDeyhHusSJRrrROolLjfAaFtNnWjJrRwAacCcYyfFOdDNnzZoFfXMmfFxCYyKksJjwuUyYsSWzZYyRrSsSiHOohPsyYZzSpJjkKIbsSBgGsSeEuUYVvYyytTZCcnNzaAzZDgGzZdT\"\n\nprint(best_reduce(text))\n\n\n\n"} {"blob_id": "7380f610c4b7631adb1b4b2e665cbd7e1e8b7104", "repo_name": "pengyuhou/git_test1", "path": "/leetcode/23. \u5408\u5e76K\u4e2a\u6392\u5e8f\u94fe\u8868.py", "length_bytes": 484, "score": 3.640625, "int_score": 4, "content": "# Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution(object):\n def mergeKLists(self, lists):\n ret = []\n for i in lists:\n while i:\n ret.append(i.val)\n i = i.next\n ret.sort()\n a = ListNode(-1)\n tmp = a\n while ret:\n a.next = ListNode(ret.pop(0))\n a = a.next\n return tmp.next\n"} {"blob_id": "2113b8934800cce31fe235cb16086d5a49f61284", "repo_name": "sritar99/DSA", "path": "/UniqueSubstrings.py", "length_bytes": 434, "score": 3.703125, "int_score": 4, "content": "def UniqueSubStr(s):\n\tsuffix=[]\n\tfor i in range(len(s)):\n\t\tsuffix.append(s[i:])\n\tsuffix.sort()\n\tprint(suffix)\n\tLCP=[0]\n\tfor i in range(len(suffix)-1):\n\t\tcount=0\n\t\ts1=suffix[i]\n\t\ts2=suffix[i+1]\n\t\tj=0\n\t\tk=min(len(s1),len(s2))\n\t\twhile j= len(data) or (data[i] >> 6) != 0b10: return False\n return True\n\n start = 0\n while start < len(data):\n first = data[start]\n if (first >> 3) == 0b11110 and check(start, 3): start += 4\n elif (first >> 4) == 0b1110 and check(start, 2): start += 3\n elif (first >> 5) == 0b110 and check(start, 1): start += 2\n elif (first >> 7) == 0: start += 1\n else: return False\n return True\n"} {"blob_id": "e2cbc62c481f93c1621e86ad3abdb2cbb6d65d28", "repo_name": "TeoMoisi/AI", "path": "/AckleyPSO/controller.py", "length_bytes": 945, "score": 3.5, "int_score": 4, "content": "from swarm import Swarm\n\n#For each particle\n# Initialize particle\n#END\n#\n#Do\n# For each particle\n# Calculate fitness value\n# If the fitness value is better than the best fitness value (pBest) in history\n# set current value as the new pBest\n# End\n#\n# Choose the particle with the best fitness value of all the particles as the gBest\n# For each particle\n# Calculate particle velocity according equation (a)\n# Update particle position according equation (b)\n# End\nclass Controller:\n\n def runAlg(self):\n count = 0\n s = Swarm(40,5,5)\n while s.bestGlobal > 0.000000001:\n count += 1\n for particle in s.particles:\n particle.calFitness()\n s.getBestParticle()\n for particle in s.particles:\n particle.evaluate(s.bestGlobalX,s.bestGlobalY,s.c1,s.c2)\n print (\"Fount in \" + str(count) + \" moves\")\n"} {"blob_id": "4397371c5e5625ed5333e5a9e99f40706605e3a4", "repo_name": "aoran-jiao/Tank_Trouble", "path": "/maze.py", "length_bytes": 4997, "score": 3.59375, "int_score": 4, "content": "from cell import *\nfrom random import randint\n\nclass Maze(object):\n \n def __init__(self, x, y, w, ca):\n self.x = x # length of the maze\n self.y = y # width of the maze\n self.w = w # size of the maze\n self.cellsAcross = ca # complexity of the maze\n \n self.cells = []\n self.totalCells = self.cellsAcross ** 2\n self.visitedCells = 1\n self.currentCell = self.totalCells - 1\n self.cellStack = []\n self.step = self.w/self.cellsAcross\n \n self.complete = False\n \n for i in range(self.cellsAcross):\n for j in range(self.cellsAcross):\n c = Cell(self.x + j * self.step, y + i * self.step, self.step)\n self.cells.append(c)\n \n \n \n self.destinationX = self.x + self.w - self.step\n self.destinationY = self.y + self.w - self.step\n \n self.lastCell = self.cells[len(self.cells)-1] # Cell lastCell=(Cell) cells.get(cells.size()-1)\n self.lastCell.marked = True\n \n def reset(self, ca):\n \n self.cellsAcross = ca\n \n for i in range(len(self.cells) - 1, -1, -1):\n self.cells.remove(i) \n \n for i in range(self.cellAcross):\n for j in range(self.cellAcross):\n c = Cell(self.x + j * self.step, y + i * self.step, self.step)\n self.cells.append(c) \n \n \n \n self.lastCell = self.cells.index(self.cells[-1]) # Cell lastCell=(Cell) cells.get(cells.size()-1)\n self.lastCell.marked = True\n \n while len(self.cellStack)>1: \n self.cellStack = shorten(cellStack)\n \n self.totalCells = self.cellsAcross ** 2\n self.visitedCells = 1\n self.currentCell = self.totalCells - 1\n self.cellStack[0] = self.currentCell\n self.destinationX = self.x + self.w - self.step\n self.destinationY = self.y + self.w - self.step\n\n \n self.complete = False\n self.finished = False\n \n randomSeed(millis())\n \n \n def display(self):\n \n for i in range(len(self.cells)):\n self.c = self.cells[i]\n self.c.display(self.step/8)\n \n \n def travelThrough(self, x, y):\n \n ind = self.cellsAcross * ((y - self.y)/self.step) + ((x - self.x)/self.step)\n inCell = self.cells[ind] # (Cell) cells.get(index) getting an element at a specific index\n inCell.visited = min(255, inCell.visited+65) # that perticular cell is going to be painted darker till 0\n return inCell.walls # return the boolean variable\n \n \n def routeStep(self):\n \n # find the current cell's neighbors\n numberOfPossibles = 0\n \n neighbors = [self.currentCell-self.cellsAcross,self.currentCell+self.cellsAcross,self.currentCell-1,self.currentCell+1]\n\n \n # check for edges\n if self.currentCell-self.cellsAcross < 0:\n neighbors[0]=-1\n if self.currentCell+self.cellsAcross>=self.cellsAcross*self.cellsAcross:\n neighbors[1]=-1\n if self.currentCell % self.cellsAcross == 0 :\n neighbors[2]=-1\n if self.currentCell % self.cellsAcross == self.cellsAcross-1:\n neighbors[3]=-1\n \n # check for previously visited cells\n for i in range(4):\n if neighbors[i]!=-1:\n c = self.cells[neighbors[i]] # Cell c = (Cell) cells.get(neighbors[i])\n if c.marked:\n neighbors[i]=-1\n else:\n numberOfPossibles += 1\n \n \n if numberOfPossibles>0: \n \n chosenCell = randint(0, numberOfPossibles)\n \n for i in range(4):\n if neighbors[i]!=-1:\n if chosenCell==0:\n # this is the next cell\n thisCell = self.cells[self.currentCell]\n nextCell = self.cells[neighbors[i]]\n thisCell.marked=True\n nextCell.marked=True\n # let's knock down the 2 adjoining walls\n if i==0:\n thisCell.walls[0]=False\n nextCell.walls[1]=False\n \n if i==1:\n thisCell.walls[1]=False\n nextCell.walls[0]=False\n \n if i==2: \n thisCell.walls[2]=False\n nextCell.walls[3]=False\n \n if i==3: \n thisCell.walls[3]=False\n nextCell.walls[2]=False\n \n self.visitedCells += 1\n \n if self.visitedCells == self.totalCells:\n self.complete=True\n # print(millis()-timer)\n \n self.currentCell = neighbors[i]\n self.cellStack.append(self.currentCell)\n stroke(0,0,255,5+250*thisCell.x/width)\n strokeWeight(self.step/2)\n w = width/(self.cellsAcross*2)\n line(thisCell.x+self.step/2,thisCell.y+self.step/2,nextCell.x+self.step/2,nextCell.y+self.step/2)\n break\n \n else:\n chosenCell -= 1\n \n else:\n self.currentCell = self.cellStack[len(self.cellStack)-1]\n self.cellStack = shorten(self.cellStack)\n \n \n \n"} {"blob_id": "001ac3c7ccac09751092f985859edb3506f6d2e2", "repo_name": "marccarre/google-code-jam", "path": "/cj2021/r1a/prime_time.py", "length_bytes": 1690, "score": 3.6875, "int_score": 4, "content": "'''\npython cj2021/r1a/prime_time.py < tests/cj2021/r1a/prime_time.txt\n'''\n\nfrom collections import Counter\nfrom itertools import chain, combinations\nfrom functools import reduce\nfrom operator import mul\nfrom typing import Dict, List, Tuple\n\n\ndef main() -> None:\n testcases = int(input())\n for i in range(1, testcases + 1):\n m = int(input())\n # cards = Counter()\n cards = []\n for _ in range(m):\n p, n = [int(x) for x in input().split()]\n # cards[p] = n\n cards.extend([p] * n)\n score = play(cards)\n print('Case #%d: %s' % (i, score))\n\n\ndef play(cards_list: List[int]) -> int:\n cards = Counter(cards_list)\n max_score = 0\n for cards_set in _powerset(cards_list):\n if not cards_set:\n continue\n s = sum(cards_set)\n p = reduce(mul, cards_set)\n remainder = cards - Counter(cards_set)\n if not remainder:\n continue\n s_r = _sum(remainder)\n p_r = _product(remainder)\n score = 0\n if s == p_r:\n score = max(score, s)\n if p == s_r:\n score = max(score, p)\n max_score = max(max_score, score)\n return max_score\n\n\ndef _sum(d: Dict[int, int]) -> int:\n s = 0\n for v, count in d.items():\n s += v * count\n return s\n\n\ndef _product(d: Dict[int, int]) -> int:\n p = 0\n for v, count in d.items():\n p *= v ** count\n return p\n\n\ndef _powerset(s: List[int]) -> List[Tuple[int]]:\n ''' _powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3) '''\n return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1))\n\n\nif __name__ == '__main__':\n main()\n"} {"blob_id": "8b945ddc9660e627a87ec1f8b6d85125dc9960dc", "repo_name": "GreatTwang/lccc_solution", "path": "/Python/LinkedList/Reorder List.py", "length_bytes": 737, "score": 3.75, "int_score": 4, "content": "class Solution:\n def reorderList(self, head: ListNode) -> None:\n \"\"\"\n Do not return anything, modify head in-place instead.\n \"\"\"\n if not head:\n return\n fast=slow=head\n while fast and fast.next:\n slow=slow.next\n fast=fast.next.next\n h2=slow.next\n slow.next=None\n #reverse right half\n pre=None\n curr=h2\n while curr:\n temp=curr.next\n curr.next=pre\n pre=curr\n curr=temp\n #insert\n h1=head\n h2=pre\n while h2:\n temp1=h1.next\n temp2=h2.next\n h1.next=h2\n h2.next=temp1\n h1=temp1\n h2=temp2"} {"blob_id": "06eb719875d709d3abfb273764f720d49b1984a2", "repo_name": "DmitryVGusev/Python_lessons_basic", "path": "/lesson02/home_work/hw02_hard.py", "length_bytes": 8196, "score": 4.125, "int_score": 4, "content": "# \u0417\u0430\u0434\u0430\u043d\u0438\u0435-1: \u0443\u0440\u0430\u0432\u043d\u0435\u043d\u0438\u0435 \u043f\u0440\u044f\u043c\u043e\u0439 \u0432\u0438\u0434\u0430 y = kx + b \u0437\u0430\u0434\u0430\u043d\u043e \u0432 \u0432\u0438\u0434\u0435 \u0441\u0442\u0440\u043e\u043a\u0438.\n# \u041e\u043f\u0440\u0435\u0434\u0435\u043b\u0438\u0442\u044c \u043a\u043e\u043e\u0440\u0434\u0438\u043d\u0430\u0442\u0443 y \u0442\u043e\u0447\u043a\u0438 \u0441 \u0437\u0430\u0434\u0430\u043d\u043d\u043e\u0439 \u043a\u043e\u043e\u0440\u0434\u0438\u043d\u0430\u0442\u043e\u0439 x.\n\nequation = 'y = -12x + 11111140.2121'\nx = 2.5\n# \u0432\u044b\u0447\u0438\u0441\u043b\u0438\u0442\u0435 \u0438 \u0432\u044b\u0432\u0435\u0434\u0438\u0442\u0435 y\n\n# \u041d\u0435 \u0431\u0443\u0434\u0435\u043c \u043f\u043e\u043b\u0430\u0433\u0430\u0442\u044c\u0441\u044f \u043d\u0430 \u043e\u0434\u0438\u043d\u043e\u0447\u043d\u043e\u0435 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u043f\u0440\u043e\u0431\u0435\u043b\u043e\u0432 \u0438 \u0443\u0434\u0430\u043b\u0438\u043c \u0438\u0445 \u0438\u0437 \u0441\u0442\u0440\u043e\u043a\u0438\nequation = equation.replace(' ', '')\n# \u041e\u043f\u0440\u0435\u0434\u0435\u043b\u0438\u043c \u043f\u043e\u043b\u043e\u0436\u0435\u043d\u0438\u0435 \u043e\u043f\u043e\u0440\u043d\u044b\u0445 \u0437\u043d\u0430\u043a\u043e\u0432: '=' \u0438 '+'. \u041e\u0442 \u043d\u0438\u0445 \u0431\u0443\u0434\u0435\u043c \u0434\u0435\u043b\u0430\u0442\u044c \u0441\u0440\u0435\u0437\u044b.\nposition_equal = equation.find('=')\nposition_plus = equation.find('+')\n\n# \u0412\u044b\u0447\u0438\u0441\u043b\u044f\u0435\u043c k \u0438 b \u043f\u043e \u0441\u0440\u0435\u0437\u0430\u043c\nk = float(equation[position_equal + 1:position_plus - 1])\nb = float(equation[position_plus + 1:])\n\n# \u0412\u044b\u0447\u0438\u0441\u043b\u044f\u0435\u043c y \u0438 \u0432\u044b\u0432\u043e\u0434\u0438\u043c\ny = k * x + b\nprint(y)\n\n# \u0417\u0430\u0434\u0430\u043d\u0438\u0435-2: \u0414\u0430\u0442\u0430 \u0437\u0430\u0434\u0430\u043d\u0430 \u0432 \u0432\u0438\u0434\u0435 \u0441\u0442\u0440\u043e\u043a\u0438 \u0444\u043e\u0440\u043c\u0430\u0442\u0430 'dd.mm.yyyy'.\n# \u041f\u0440\u043e\u0432\u0435\u0440\u0438\u0442\u044c, \u043a\u043e\u0440\u0440\u0435\u043a\u0442\u043d\u043e \u043b\u0438 \u0432\u0432\u0435\u0434\u0435\u043d\u0430 \u0434\u0430\u0442\u0430. (\u041f\u0440\u043e\u0432\u0435\u0440\u044e. \u0410 \u0432\u044b\u0432\u043e\u0434 \u043f\u0440\u043e\u0432\u0435\u0440\u043a\u0438?)\n# \u0423\u0441\u043b\u043e\u0432\u0438\u044f \u043a\u043e\u0440\u0440\u0435\u043a\u0442\u043d\u043e\u0441\u0442\u0438:\n# 1. \u0414\u0435\u043d\u044c \u0434\u043e\u043b\u0436\u0435\u043d \u043f\u0440\u0438\u0432\u043e\u0434\u0438\u0442\u044c\u0441\u044f \u043a \u0446\u0435\u043b\u043e\u043c\u0443 \u0447\u0438\u0441\u043b\u0443 \u0432 \u0434\u0438\u0430\u043f\u0430\u0437\u043e\u043d\u0435 \u043e\u0442 1 \u0434\u043e 30(31)\n# (\u0432 \u0437\u0430\u0432\u0438\u0441\u0438\u043c\u043e\u0441\u0442\u0438 \u043e\u0442 \u043c\u0435\u0441\u044f\u0446\u0430, \u0444\u0435\u0432\u0440\u0430\u043b\u044c \u043d\u0435 \u0443\u0447\u0438\u0442\u044b\u0432\u0430\u0435\u043c)\n# 2. \u041c\u0435\u0441\u044f\u0446 \u0434\u043e\u043b\u0436\u0435\u043d \u043f\u0440\u0438\u0432\u043e\u0434\u0438\u0442\u044c\u0441\u044f \u043a \u0446\u0435\u043b\u043e\u043c\u0443 \u0447\u0438\u0441\u043b\u0443 \u0432 \u0434\u0438\u0430\u043f\u0430\u0437\u043e\u043d\u0435 \u043e\u0442 1 \u0434\u043e 12\n# 3. \u0413\u043e\u0434 \u0434\u043e\u043b\u0436\u0435\u043d \u043f\u0440\u0438\u0432\u043e\u0434\u0438\u0442\u044c\u0441\u044f \u043a \u0446\u0435\u043b\u043e\u043c\u0443 \u043f\u043e\u043b\u043e\u0436\u0438\u0442\u0435\u043b\u044c\u043d\u043e\u043c\u0443 \u0447\u0438\u0441\u043b\u0443 \u0432 \u0434\u0438\u0430\u043f\u0430\u0437\u043e\u043d\u0435 \u043e\u0442 1 \u0434\u043e 9999\n# 4. \u0414\u043b\u0438\u043d\u0430 \u0438\u0441\u0445\u043e\u0434\u043d\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0438 \u0434\u043b\u044f \u0447\u0430\u0441\u0442\u0435\u0439 \u0434\u043e\u043b\u0436\u043d\u0430 \u0431\u044b\u0442\u044c \u0432 \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0438\u0438 \u0441 \u0444\u043e\u0440\u043c\u0430\u0442\u043e\u043c \n# (\u0442.\u0435. 2 \u0441\u0438\u043c\u0432\u043e\u043b\u0430 \u0434\u043b\u044f \u0434\u043d\u044f, 2 - \u0434\u043b\u044f \u043c\u0435\u0441\u044f\u0446\u0430, 4 - \u0434\u043b\u044f \u0433\u043e\u0434\u0430)\n\n# \u041f\u0440\u0438\u043c\u0435\u0440 \u043a\u043e\u0440\u0440\u0435\u043a\u0442\u043d\u043e\u0439 \u0434\u0430\u0442\u044b\ndate = '01.11.1985'\n\n# \u041f\u0440\u0438\u043c\u0435\u0440\u044b \u043d\u0435\u043a\u043e\u0440\u0440\u0435\u043a\u0442\u043d\u044b\u0445 \u0434\u0430\u0442\ndate = '01.22.1001'\ndate = '1.12.1001'\ndate = '-2.10.3001'\n\n\n# \u0414\u043b\u044f \u0443\u0434\u043e\u0431\u0441\u0442\u0432\u0430 \u043e\u0431\u0435\u0440\u043d\u0443 \u043b\u043e\u0433\u0438\u043a\u0443 \u0432 \u0444\u0443\u043d\u043a\u0446\u0438\u044e. \u041f\u043e \u0441\u0443\u0442\u0438, \u0437\u0430\u043c\u0435\u043d\u044f\u0435\u043c \u043c\u043d\u043e\u0433\u043e\u0432\u043b\u043e\u0436\u0435\u043d\u043d\u044b\u043c\u0438 if'\u0430\u043c\u0438\ndef is_currect_date(date: str):\n \"\"\"\u0424\u0443\u043d\u043a\u0446\u0438\u044f \u0432\u043e\u0437\u0440\u0430\u0449\u0430\u0435\u0442 True \u0435\u0441\u043b\u0438 \u0437\u0430\u043f\u0438\u0441\u044c \u0434\u0430\u0442\u044b \u043a\u043e\u0440\u0440\u0435\u043a\u0442\u043d\u0430, \u0438 False \u0435\u0441\u043b\u0438 \u043d\u0435\u0442\"\"\"\n\n # \u041f\u0440\u043e\u0432\u0435\u0440\u044f\u0435\u043c \u0434\u043b\u0438\u043d\u0443 \u0437\u0430\u043f\u0438\u0441\u0438\n if len(date) != 10:\n return False\n\n # \u041c\u044b \u0443\u0436\u0435 \u043f\u0440\u043e\u0448\u043b\u0438 \u0441\u043f\u0438\u0441\u043a\u0438 \u0438 \u0441\u0442\u0440\u043e\u043a\u0438, \u0430 \u0437\u043d\u0430\u0447\u0438\u0442 \u043c\u043e\u0436\u0435\u043c \u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u044c\u0441\u044f \u043c\u0435\u0442\u043e\u0434\u043e\u043c \u0441\u0442\u0440\u043e\u043a\u0438 .split()\n # \u0417\u0430\u043f\u0438\u0448\u0435\u043c \u0434\u0430\u0442\u0443 \u0432 \u0441\u043f\u0438\u0441\u043e\u043a \u043f\u043e\u044d\u043b\u0435\u043c\u0435\u043d\u0442\u043d\u043e [\u0434\u0435\u043d\u044c, \u043c\u0435\u0441\u044f\u0446, \u0433\u043e\u0434]\n date_list = date.split('.')\n\n # \u041f\u0440\u043e\u0432\u0435\u0440\u044f\u0435\u043c \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0447\u0430\u0441\u0442\u0435\u0439 \u0434\u0430\u0442\u044b \u0438 \u0438\u0445 \u0444\u043e\u0440\u043c\u0430\u0442\n if len(date_list) != 3:\n return False\n elif len(date_list[0]) != 2 or len(date_list[1]) != 2 or len(date_list[2]) != 4:\n return False\n\n # \u041f\u0435\u0440\u0435\u0432\u043e\u0434\u0438\u043c \u044d\u043b\u0435\u043c\u0435\u043d\u0442\u044b \u0441\u043f\u0438\u0441\u043a\u0430 \u0432 \u0446\u0435\u043b\u044b\u0435 \u0447\u0438\u0441\u043b\u0430\n day = int(date_list[0])\n month = int(date_list[1])\n year = int(date_list[2])\n\n # \u041f\u0440\u043e\u0432\u0435\u0440\u044f\u0435\u043c \u0432\u0430\u043b\u0438\u0434\u043d\u043e\u0441\u0442\u044c \u0433\u043e\u0434\u0430\n if year < 1 or year > 9999:\n return False\n\n # \u041f\u0440\u043e\u0432\u0435\u0440\u044f\u0435\u043c \u0432\u0430\u043b\u0438\u0434\u043d\u043e\u0441\u0442\u044c \u043c\u0435\u0441\u044f\u0446\u0430\n if month < 1 or month > 12:\n return False\n\n # \u041f\u043e\u0434\u0441\u0447\u0438\u0442\u044b\u0432\u0430\u0435\u043c \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0434\u043d\u0435\u0439 \u0432 \u043c\u0435\u0441\u044f\u0446\u0435 (\u0441\u0447\u0438\u0442\u0430\u0435\u043c \u0444\u0435\u0432\u0440\u0430\u043b\u044c \u0437\u0430 30)\n if month % 2 == 0:\n days_in_month = 31\n else:\n days_in_month = 30\n\n # \u041f\u0440\u043e\u0432\u0435\u0440\u044f\u0435\u043c \u0432\u0430\u043b\u0438\u0434\u043d\u043e\u0441\u0442\u044c \u0434\u043d\u044f\n if day < 1 or day > days_in_month:\n return False\n\n # \u0412\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u043c True \u0442\u0430\u043a \u043a\u0430\u043a \u0432\u0441\u0435 \u0443\u0441\u043b\u043e\u0432\u0438\u044f \u043a\u043e\u0440\u0440\u0435\u043a\u0442\u043d\u043e\u0441\u0442\u0438 \u0441\u043e\u0431\u043b\u044e\u0434\u0435\u043d\u044b\n return True\n\n\n# \u0412\u044b\u0432\u043e\u0434 \u043f\u0440\u043e\u0432\u0435\u0440\u043a\u0438\nif is_currect_date(date):\n print(\"\u0414\u0430\u0442\u0430 \u043a\u043e\u0440\u0440\u0435\u043a\u0442\u043d\u0430\")\nelse:\n print(\"\u0414\u0430\u0442\u0430 \u043d\u0435\u043a\u043e\u0440\u0440\u0435\u043a\u0442\u043d\u0430\")\n\n# \u0417\u0430\u0434\u0430\u043d\u0438\u0435-3: \"\u041f\u0435\u0440\u0435\u0432\u0451\u0440\u043d\u0443\u0442\u0430\u044f \u0431\u0430\u0448\u043d\u044f\" (\u0417\u0430\u0434\u0430\u0447\u0430 \u043e\u043b\u0438\u043c\u043f\u0438\u0430\u0434\u043d\u043e\u0433\u043e \u0443\u0440\u043e\u0432\u043d\u044f)\n#\n# \u0412\u0430\u0432\u0438\u043b\u043e\u043d\u0446\u044b \u0440\u0435\u0448\u0438\u043b\u0438 \u043f\u043e\u0441\u0442\u0440\u043e\u0438\u0442\u044c \u0443\u0434\u0438\u0432\u0438\u0442\u0435\u043b\u044c\u043d\u0443\u044e \u0431\u0430\u0448\u043d\u044e \u2014\n# \u0440\u0430\u0441\u0448\u0438\u0440\u044f\u044e\u0449\u0443\u044e\u0441\u044f \u043a \u0432\u0435\u0440\u0445\u0443 \u0438 \u0441\u043e\u0434\u0435\u0440\u0436\u0430\u0449\u0443\u044e \u0431\u0435\u0441\u043a\u043e\u043d\u0435\u0447\u043d\u043e\u0435 \u0447\u0438\u0441\u043b\u043e \u044d\u0442\u0430\u0436\u0435\u0439 \u0438 \u043a\u043e\u043c\u043d\u0430\u0442.\n# \u041e\u043d\u0430 \u0443\u0441\u0442\u0440\u043e\u0435\u043d\u0430 \u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0438\u043c \u043e\u0431\u0440\u0430\u0437\u043e\u043c \u2014 \u043d\u0430 \u043f\u0435\u0440\u0432\u043e\u043c \u044d\u0442\u0430\u0436\u0435 \u043e\u0434\u043d\u0430 \u043a\u043e\u043c\u043d\u0430\u0442\u0430,\n# \u0437\u0430\u0442\u0435\u043c \u0438\u0434\u0435\u0442 \u0434\u0432\u0430 \u044d\u0442\u0430\u0436\u0430, \u043d\u0430 \u043a\u0430\u0436\u0434\u043e\u043c \u0438\u0437 \u043a\u043e\u0442\u043e\u0440\u044b\u0445 \u043f\u043e \u0434\u0432\u0435 \u043a\u043e\u043c\u043d\u0430\u0442\u044b, \n# \u0437\u0430\u0442\u0435\u043c \u0438\u0434\u0451\u0442 \u0442\u0440\u0438 \u044d\u0442\u0430\u0436\u0430, \u043d\u0430 \u043a\u0430\u0436\u0434\u043e\u043c \u0438\u0437 \u043a\u043e\u0442\u043e\u0440\u044b\u0445 \u043f\u043e \u0442\u0440\u0438 \u043a\u043e\u043c\u043d\u0430\u0442\u044b \u0438 \u0442\u0430\u043a \u0434\u0430\u043b\u0435\u0435:\n# ...\n# 12 13 14\n# 9 10 11\n# 6 7 8\n# 4 5\n# 2 3\n# 1\n#\n# \u042d\u0442\u0443 \u0431\u0430\u0448\u043d\u044e \u0440\u0435\u0448\u0438\u043b\u0438 \u043e\u0431\u043e\u0440\u0443\u0434\u043e\u0432\u0430\u0442\u044c \u043b\u0438\u0444\u0442\u043e\u043c --- \u0438 \u0432\u043e\u0442 \u0437\u0430\u0434\u0430\u0447\u0430:\n# \u043d\u0443\u0436\u043d\u043e \u043d\u0430\u0443\u0447\u0438\u0442\u044c\u0441\u044f \u043f\u043e \u043d\u043e\u043c\u0435\u0440\u0443 \u043a\u043e\u043c\u043d\u0430\u0442\u044b \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u044f\u0442\u044c,\n# \u043d\u0430 \u043a\u0430\u043a\u043e\u043c \u044d\u0442\u0430\u0436\u0435 \u043e\u043d\u0430 \u043d\u0430\u0445\u043e\u0434\u0438\u0442\u0441\u044f \u0438 \u043a\u0430\u043a\u0430\u044f \u043e\u043d\u0430 \u043f\u043e \u0441\u0447\u0435\u0442\u0443 \u0441\u043b\u0435\u0432\u0430 \u043d\u0430 \u044d\u0442\u043e\u043c \u044d\u0442\u0430\u0436\u0435.\n#\n# \u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435: \u0412 \u043f\u0435\u0440\u0432\u043e\u0439 \u0441\u0442\u0440\u043e\u0447\u043a\u0435 \u0437\u0430\u0434\u0430\u043d \u043d\u043e\u043c\u0435\u0440 \u043a\u043e\u043c\u043d\u0430\u0442\u044b N, 1 \u2264 N \u2264 2 000 000 000.\n#\n# \u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435: \u0414\u0432\u0430 \u0446\u0435\u043b\u044b\u0445 \u0447\u0438\u0441\u043b\u0430 \u2014 \u043d\u043e\u043c\u0435\u0440 \u044d\u0442\u0430\u0436\u0430 \u0438 \u043f\u043e\u0440\u044f\u0434\u043a\u043e\u0432\u044b\u0439 \u043d\u043e\u043c\u0435\u0440 \u0441\u043b\u0435\u0432\u0430 \u043d\u0430 \u044d\u0442\u0430\u0436\u0435.\n#\n# \u041f\u0440\u0438\u043c\u0435\u0440:\n# \u0412\u0445\u043e\u0434: 13\n# \u0412\u044b\u0445\u043e\u0434: 6 2\n#\n# \u0412\u0445\u043e\u0434: 11\n# \u0412\u044b\u0445\u043e\u0434: 5 3\n\n\ndef room_adress(num: int):\n \"\"\"\n \u0424\u0443\u043d\u043a\u0446\u0438\u044f \u043d\u0430\u0445\u043e\u0434\u0438\u0442 \u0438 \u0432\u044b\u0432\u043e\u0434\u0438\u0442 \u0430\u0434\u0440\u0435\u0441 \u043a\u043e\u043c\u043d\u0430\u0442\u044b \u0432 \u0412\u0430\u0432\u0438\u043b\u043e\u043d\u0441\u043a\u043e\u0439 \u0431\u0430\u0448\u043d\u0435 (\u044d\u0442\u0430\u0436, \u043f\u043e\u0440\u044f\u0434\u043a\u043e\u0432\u044b\u0439_\u043d\u043e\u043c\u0435\u0440)\n \u041b\u043e\u0433\u0438\u043a\u0430 \u043f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0430 \u043d\u0430 \u043e\u0441\u043d\u043e\u0432\u0435 \u043a\u043e\u043c\u043f\u044c\u044e\u0442\u0435\u0440\u043d\u043e\u0439 \u0438\u0433\u0440\u044b:\n \u0423\u0440\u043e\u0432\u0435\u043d\u044c - \u044d\u0442\u043e \u0434\u0432\u0443\u043c\u0435\u0440\u043d\u044b\u0439 \u043c\u0430\u0441\u0441\u0438\u0432 \u0412\u0430\u0432\u0438\u043b\u043e\u043d\u0441\u043a\u043e\u0439 \u0431\u0430\u0448\u043d\u0438 \u0433\u0434\u0435 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u044d\u0442\u0430\u0436\u0435\u0439 \u0440\u0430\u0432\u043d\u043e \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u0443 \u043d\u043e\u043c\u0435\u0440\u043e\u0432 \u043d\u0430 \u044d\u0442\u0430\u0436\u0435\n \u042d\u0442\u0430\u0436 - \u0441\u0442\u0440\u043e\u043a\u0430 \u043c\u0430\u0441\u0441\u0438\u0432\u0430\n \u0428\u0430\u0433 - \u0441\u043c\u0435\u0449\u0435\u043d\u0438\u0435 \u043f\u043e \u044d\u0442\u0430\u0436\u0443\n \u041f\u0440\u0438 \u0437\u0430\u0434\u0430\u043d\u0438\u0438 \u043d\u043e\u043c\u0435\u0440\u0430 \u043a\u043e\u043c\u043d\u0430\u0442\u044b \u043c\u044b \u0444\u0430\u043a\u0442\u0438\u0447\u0435\u0441\u043a\u0438 \u0433\u0435\u043d\u0435\u0440\u0438\u0440\u0443\u0435\u043c \u0438\u0440\u0433\u0443: \u043a\u0430\u043a \u0442\u043e\u043b\u044c\u043a\u043e \u0443\u0440\u043e\u0432\u0435\u043d\u044c \u043f\u0440\u043e\u0439\u0434\u0435\u043d - \u0433\u0435\u043d\u0435\u0440\u0438\u0440\u0443\u0435\u0442\u0441\u044f \u043d\u043e\u0432\u044b\u0439 \u0443\u0440\u043e\u0432\u0435\u043d\u044c\n \u0441 \u0440\u0430\u0437\u043c\u0435\u0440\u043e\u043c +1\n \u0410 \u043c\u0435\u0442\u043e\u0434 \u0440\u0435\u0448\u0435\u043d\u0438\u044f \u0437\u0430\u0434\u0430\u0447\u0438 - \u043f\u043e\u0434\u043d\u0438\u043c\u0430\u0442\u044c\u0441\u044f \u043f\u0435\u0448\u043a\u043e\u043c \u043f\u0440\u043e\u0445\u043e\u0434\u044f \u043a\u0430\u0436\u0434\u044b\u0439 \u043d\u043e\u043c\u0435\u0440 \u0434\u043e \u0442\u0435\u0445 \u043f\u043e\u0440, \u043f\u043e\u043a\u0430 \u043d\u0435 \u0432\u0441\u0442\u0440\u0435\u0442\u0438\u043c \u043a\u043e\u043d\u043a\u0440\u0435\u0442\u043d\u044b\u0439\n \"\"\"\n\n # \u041f\u0440\u043e\u0432\u0435\u0440\u043a\u0430 \u043d\u0430 \u0432\u0430\u043b\u0438\u0434\u043d\u043e\u0441\u0442\u044c \u0432\u0445\u043e\u0434\u043d\u044b\u0445 \u0434\u0430\u043d\u043d\u044b\u0445. \u041f\u043e\u043b\u043e\u0436\u0438\u043c, \u0447\u0442\u043e \u043d\u0430 \u0432\u0445\u043e\u0434 \u043f\u043e\u0434\u0430\u0435\u0442\u0441\u044f \u0446\u0435\u043b\u043e\u0435 \u0447\u0438\u0441\u043b\u043e\n if num < 1 or num > 2000000000:\n return \"Not in range\"\n\n # \u0410\u0431\u0441\u043e\u043b\u044e\u0442\u043d\u044b\u0435 \u043a\u043e\u043e\u0440\u0434\u0438\u043d\u0430\u0442\u044b \u043d\u0430\u0445\u043e\u0436\u0434\u0435\u043d\u0438\u044f \u0442\u043e\u0447\u043a\u0438 \u0432 \u0434\u0430\u043d\u043d\u044b\u0439 \u043c\u043e\u043c\u0435\u043d\u0442\n abs_num = 0\n abs_x = 0\n abs_y = 0\n\n # \u041a\u043e\u043e\u0440\u0434\u0438\u043d\u0430\u0442\u044b \u043f\u043e\u043b\u043e\u0436\u0435\u043d\u0438\u044f \u0442\u043e\u0447\u043a\u0438 \u043e\u0442\u043d\u043e\u0441\u0438\u0442\u0435\u043b\u044c\u043d\u043e \u0442\u0435\u043a\u0443\u0449\u0435\u0433\u043e \u0443\u0440\u043e\u0432\u043d\u044f\n current_x = 0\n current_y = 0\n\n # \u0420\u0430\u0437\u043c\u0435\u0440\u043d\u043e\u0441\u0442\u044c \u0443\u0440\u043e\u0432\u043d\u044f\n level_size = 0\n\n # \u0426\u0438\u043a\u043b \u0434\u043e \u0442\u0435\u0445 \u043f\u043e\u0440, \u043f\u043e\u043a\u0430 \u0442\u0435\u043a\u0443\u0449\u0438\u0439 \u043d\u043e\u043c\u0435\u0440 \u043d\u0435 \u0440\u0430\u0432\u0435\u043d \u0437\u0430\u0434\u0430\u043d\u043d\u043e\u043c\u0443\n while abs_num != num:\n \"\"\"\n \u041f\u0440\u043e\u0432\u0435\u0440\u044f\u0435\u043c, \u043f\u0440\u043e\u0448\u043b\u0438 \u043b\u0438 \u043c\u044b \u0443\u0440\u043e\u0432\u0435\u043d\u044c.\n \u0415\u0441\u043b\u0438 \u043f\u0440\u043e\u0448\u043b\u0438, \u043e\u0442\u0440\u0438\u0441\u043e\u0432\u044b\u0432\u0430\u0435\u043c \u043d\u043e\u0432\u044b\u0439 \u0438 \u0432\u0441\u0442\u0430\u0435\u043c \u0432 \u043d\u0430\u0447\u0430\u043b\u043e.\n \"\"\"\n if current_y == level_size and current_x == level_size:\n level_size += 1\n current_x = 1\n current_y = 1\n abs_x = 1\n abs_y += 1\n abs_num += 1\n continue\n\n \"\"\"\n \u041f\u0440\u043e\u0432\u0435\u0440\u044f\u0435\u043c, \u043f\u0440\u043e\u0448\u043b\u0438 \u043b\u0438 \u043c\u044b \u044d\u0442\u0430\u0436.\n \u0415\u0441\u043b\u0438 \u043f\u0440\u043e\u0448\u043b\u0438, \u0432\u0441\u0442\u0430\u0435\u043c \u043d\u0430 \u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0438\u0439.\n \"\"\"\n if current_x == level_size:\n current_y += 1\n current_x = 1\n abs_x = 1\n abs_y += 1\n abs_num += 1\n continue\n\n \"\"\"\u0414\u0435\u043b\u0430\u0435\u043c \u0448\u0430\u0433\"\"\"\n current_x += 1\n abs_x += 1\n abs_num += 1\n\n # \u0412\u044b\u0432\u043e\u0434 \u0444\u0443\u043d\u043a\u0446\u0438\u0438: \u044d\u0442\u0430\u0436, \u043f\u043e\u0440\u044f\u0434\u043a\u043e\u0432\u044b\u0439_\u043d\u043e\u043c\u0435\u0440\n print(\"{} {}\".format(abs_y, abs_x))\n\n\n# \u041f\u0440\u0438\u043c\u0435\u0440 \u0432\u044b\u0437\u043e\u0432\u0430 \u0444\u0443\u043d\u043a\u0446\u0438\u0438\nroom_adress(157)\n\n\n\n\n\n\n\n"} {"blob_id": "f2b34ba34d9bd086746cae95390ba540d457964f", "repo_name": "ledbagholberton/holbertonschool-machine_learning", "path": "/unsupervised_learning/0x02-hmm/0-markov_chain.py", "length_bytes": 1200, "score": 4.09375, "int_score": 4, "content": "#!/usr/bin/env python3\n\"\"\"\nP is a square 2D numpy.ndarray of shape (n, n) representing\nthe transition matrix\nP[i, j] is the probability of transitioning from state i to state j\nn is the number of states in the markov chain\ns is a numpy.ndarray of shape (1, n) representing\nthe probability of starting in each state\nt is the number of iterations that the markov chain has been through\nReturns: a numpy.ndarray of shape (1, n) representing\nprobability of being in a specific state after t iterations, or None on failure\n\"\"\"\nimport numpy as np\n\n\ndef markov_chain(P, s, t=1):\n \"\"\"\n determines the probability of a markov chain being in a particular state\n after a specified number of iterations\n \"\"\"\n try:\n if (not isinstance(P, np.ndarray) or\n not isinstance(s, np.ndarray)):\n return None\n if P.shape[0] is not P.shape[1]:\n return None\n if len(P.shape) is not 2:\n return None\n a = np.sum(P) / P.shape[0]\n if a != 1:\n return None\n if type(t) is not int or t <= 1:\n return None\n return np.matmul(s, np.linalg.matrix_power(P, t))\n except Exception:\n return None\n"} {"blob_id": "5c394bec1ca5a07213ed300953007b04f1f07869", "repo_name": "hshringeri/Guess-Master", "path": "/GuessMaster.py", "length_bytes": 36231, "score": 4.21875, "int_score": 4, "content": "# Guess Master 3.0\n# This program is a game where the user is presented with a 4 to 6 letter secret\n# word, and the user has 10 tries to guess the word. Each time the user guess\n# the word, a new round will begin and the user's score will increase by 1.\n#\n# 3 creative features are:\n# 1. Final guess which let the user type in the secret word, and goes to the\n# next round if they guessed it correctly.\n# 2. Hangman Mode, which let the user play the game in the style of hangman,\n# where the programs draw the hangman, instead of dropping polygons.\n# 3. Bonus scores, which lets the user play a minigame when they enter every\n# 10th round, and will be awarded with 20 points if they won.\n\n#importing all the libraries needed\nfrom graphics import *\nimport random\nfrom math import *\nfrom copy import deepcopy\nimport time\n#define control() function for the control panel\ndef control():\n\n #create the panel with the aspect of 300 x 250 and set its background to light grey\n panel = GraphWin(\"Welcome to:\",300,250)\n panel.setBackground(\"light grey\")\n\n #Create the header that says \"Gussmaster 2.0\"\n titleback = Rectangle(Point(0,0),Point(300,20))\n #set the background of the header black\n titleback.setFill(\"black\")\n #draw the header background\n titleback.draw(panel)\n\n #display the gold text on the black background\n title = Text(Point(150,10),\"GUESS MASTER 3.0\")\n #make it bold\n title.setStyle(\"bold\")\n #adjust the size\n title.setSize(16)\n #make the words gold\n title.setOutline(\"gold\")\n #draw it on the control panel\n title.draw(panel)\n\n #create the button that says new\n new = Rectangle(Point(20,40),Point(80,70))\n #make it gold\n new.setFill(\"gold\")\n new.draw(panel)\n #display the text on the button\n newtext = Text(Point(50,55),\"NEW\")\n #set it bold\n newtext.setStyle(\"bold\")\n #display it on the control panel\n newtext.draw(panel)\n\n #create the button that quits the game\n quitbox = Rectangle(Point(220,40),Point(280,70))\n #make the button black\n quitbox.setFill('black')\n quitbox.draw(panel)\n #put the text on the button\n quittext = Text(Point(250,55),\"QUIT\")\n #make it bold\n quittext.setStyle('bold')\n #make the color gold\n quittext.setOutline('gold')\n quittext.draw(panel)\n \n #create the white text box in the control panel\n whitebox = Rectangle(Point(25,120),Point(275,200))\n #make it white\n whitebox.setFill('white')\n whitebox.draw(panel)\n\n #create the hint button in the control panel\n hintbutton = Rectangle(Point(120,40),Point(180,70))\n hintbutton.setFill('light green')\n hintbutton.draw(panel)\n hint = Text(Point(150,55), \"HINT\")\n hint.setStyle('bold')\n hint.draw(panel)\n\n #create a button for the scrolling high score window\n highscorebutton = Rectangle(Point(50,80),Point(150,110))\n highscorebutton.setFill('light blue')\n highscorebutton.draw(panel)\n highscoretext = Text(Point(100,95),'HIGHSCORE')\n highscoretext.setStyle('bold')\n highscoretext.draw(panel)\n\n #create a button for Hangman mode\n hangman = Rectangle(Point(170,80),Point(270,110))\n hangman.setFill('red')\n hangman.draw(panel)\n hangmantext = Text(Point(220,95),'HANGMAN')\n hangmantext.setStyle('bold')\n hangmantext.draw(panel)\n \n #display the description in the white box\n desc1 = Text(Point(150,140),\"This is a game where your score is\")\n desc1.setSize(10)\n desc1.draw(panel)\n desc2 = Text(Point(150,160),\"based on the number 4-6 letter\")\n desc2.setSize(10)\n desc2.draw(panel)\n desc3 = Text(Point(150,180),\"words you can guess within 10 tries.\")\n desc3.setSize(10)\n desc3.draw(panel)\n\n #display the words at the bottom of the control panel\n bottomwords = Text(Point(150,230),\"Click NEW to start a game...\")\n bottomwords.setSize(10)\n bottomwords.draw(panel)\n\n #return all the graphics object needed for further coding\n return panel, new, quitbox, hintbutton, highscorebutton, hangman\n\n#defing the hang function\ndef hang(thing):\n #change the selected object into black\n thing.setOutline('black')\n thing.setFill('black')\n \n#defining the hangman game function\ndef hangmangame():\n #set up the graphics window for this mode\n hangmanwin = GraphWin('Hangman',500,500)\n hangmanwin.setBackground('purple')\n\n #assign empty variables that will be used\n rect_list = []\n circlelist = []\n alphabetlist = []\n textlist = []\n objectlist = []\n alpha = \"A\"\n\n #use a for loop to make the circles for the letters on screen\n for i in range (26):\n if i < 13:\n circle = Circle(Point(40+i*35,420),17)\n circle.setFill('black')\n circle.draw(hangmanwin)\n circlelist.append(circle)\n else:\n circle = Circle(Point(40+(i-13)*35,455),17)\n circle.setFill('black')\n circle.draw(hangmanwin)\n circlelist.append(circle)\n #using 2 for loops to type the letters in the circles\n for j in range(0, 26):\n alphabetlist.append(alpha)\n alpha = chr(ord(alpha) + 1)\n for i in range(len(circlelist)):\n alphabet = Text(circlelist[i].getCenter(),alphabetlist[i])\n alphabet.setSize(10)\n alphabet.setStyle('bold')\n alphabet.setFill('white')\n alphabet.draw(hangmanwin)\n textlist.append(alphabet)\n\n #creating the object call base and append to objectlist\n base = Rectangle(Point(150,350),Point(350,380))\n base.setFill('purple')\n base.setOutline('purple')\n base.draw(hangmanwin)\n objectlist.append(base)\n\n #creating an object call verticalrect and append to objectlist\n verticalrect = Rectangle(Point(180,150),Point(200,350))\n verticalrect.setFill('purple')\n verticalrect.setOutline('purple')\n verticalrect.draw(hangmanwin)\n objectlist.append(verticalrect)\n #creating an object call horizontalrect and append to objectlist\n horizontalrect = Rectangle(Point(200,150),Point(290,170))\n horizontalrect.setFill('purple')\n horizontalrect.setOutline('purple')\n horizontalrect.draw(hangmanwin)\n objectlist.append(horizontalrect)\n #creating an object call rope and append to objectlist\n rope = Rectangle(Point(260,170),Point(268,200))\n rope.setFill('purple')\n rope.setOutline('purple')\n rope.draw(hangmanwin)\n objectlist.append(rope)\n #creating an object call head and append to objectlist\n head = Circle(Point(265,216),16)\n head.setOutline('purple')\n head.draw(hangmanwin)\n objectlist.append(head)\n #creating an object call body and append to objectlist\n body = Line(Point(265,232),Point(265,282))\n body.setOutline('purple')\n body.draw(hangmanwin)\n objectlist.append(body)\n #creating an object call leftleg and append to objectlist\n leftleg = Line(Point(265,282),Point(255,320))\n leftleg.setOutline('purple')\n leftleg.draw(hangmanwin)\n objectlist.append(leftleg)\n #creating an object call rightleg and append to objectlist\n rightleg = Line(Point(265,282),Point(275,320))\n rightleg.setOutline('purple')\n rightleg.draw(hangmanwin)\n objectlist.append(rightleg)\n #creating an object call leftarm and append to objectlist\n leftarm = Line(Point(265,232),Point(255,280))\n leftarm.setOutline('purple')\n leftarm.draw(hangmanwin)\n objectlist.append(leftarm)\n #creating an object call rightarm and append to objectlist\n rightarm = Line(Point(265,232),Point(275,280))\n rightarm.setOutline('purple')\n rightarm.draw(hangmanwin)\n objectlist.append(rightarm)\n\n #opening data file\n infile = open(\"words.txt\", \"r\")\n #reading the words form file\n wordlist = infile.readlines()\n #closing the file\n infile.close()\n #randomly choosing a word\n randnum = random.randint(0,1201)\n #choosing the word from the list\n word = wordlist[randnum]\n #getting rid of the \\n\n word = word.strip(\"\\n\")\n #use a for loop to make the rectangles for the secret word at the top of the window\n for i in range(len(word)):\n rect = Rectangle(Point(225-50*int(len(word)/2)+i*50,60),Point(225-50*int(len(word)/2)+i*50+50,110))\n rect.setFill(\"pink\")\n rect.draw(hangmanwin)\n rect_list.append(rect)\n #return the variables that will be use in other functions\n return hangmanwin, circlelist, textlist, objectlist, rect_list, word\n\n#define game() function\ndef game():\n #create the game window and make the background gold\n win = GraphWin(\"Save the Block P\", 500,500)\n win.setBackground(\"gold\")\n\n #defining all the variables needed for later use\n circlelist = []\n plist = []\n rect_list = []\n alphabetlist = []\n textlist = []\n alpha = \"A\"\n\n #use a for loop to display the black circles\n for i in range (26):\n if i < 13:\n circle = Circle(Point(40+i*35,420),17)\n circle.setFill('black')\n circle.draw(win)\n circlelist.append(circle)\n else:\n circle = Circle(Point(40+(i-13)*35,455),17)\n circle.setFill('black')\n circle.draw(win)\n circlelist.append(circle)\n #use two for loop to make a list of the white letters that goes inside the black circle\n for j in range(0, 26):\n alphabetlist.append(alpha)\n alpha = chr(ord(alpha) + 1)\n for i in range(len(circlelist)):\n alphabet = Text(circlelist[i].getCenter(),alphabetlist[i])\n alphabet.setSize(10)\n alphabet.setStyle('bold')\n alphabet.setFill('white')\n alphabet.draw(win)\n textlist.append(alphabet)\n\n #use a for loop to make the P out of polygons\n for i in range(11):\n \n if i < 3:\n polygon = Polygon(Point(210+i*50,140),Point(260+i*50,140),Point(250+i*50,180),Point(200+i*50,180))\n polygon.draw(win)\n polygon1 = Polygon(Point(210+i*50,140),Point(260+i*50,140),Point(250+i*50,180),Point(200+i*50,180))\n polygon1.setFill('black')\n polygon1.draw(win)\n plist.append(polygon1)\n elif i >= 3 and i<6:\n polygon = Polygon(Point(200+(i-3)*50,180),Point(250+(i-3)*50,180),Point(240+(i-3)*50,220),Point(190+(i-3)*50,220))\n polygon.draw(win)\n if i != 4:\n polygon1 = Polygon(Point(200+(i-3)*50,180),Point(250+(i-3)*50,180),Point(240+(i-3)*50,220),Point(190+(i-3)*50,220))\n polygon1.setFill('black')\n polygon1.draw(win)\n plist.append(polygon1)\n elif i >= 6 and i<9:\n polygon = Polygon(Point(190+(i-6)*50,220),Point(240+(i-6)*50,220),Point(230+(i-6)*50,260),Point(180+(i-6)*50,260))\n polygon.draw(win)\n polygon1 = Polygon(Point(190+(i-6)*50,220),Point(240+(i-6)*50,220),Point(230+(i-6)*50,260),Point(180+(i-6)*50,260))\n polygon1.setFill('black')\n polygon1.draw(win)\n plist.append(polygon1)\n elif i == 9:\n polygon =Polygon(Point(180,260),Point(230,260),Point(220,300),Point(170,300))\n polygon.draw(win)\n polygon1 = Polygon(Point(180,260),Point(230,260),Point(220,300),Point(170,300))\n polygon1.setFill('black')\n polygon1.draw(win)\n plist.append(polygon1)\n else:\n polygon = Polygon(Point(160,300),Point(230,300),Point(220,340),Point(150,340))\n polygon.draw(win)\n polygon1 = Polygon(Point(160,300),Point(230,300),Point(220,340),Point(150,340))\n polygon1.setFill('black')\n polygon1.draw(win)\n plist.append(polygon1)\n\n \n #opening data file\n infile = open(\"words.txt\", \"r\")\n #reading the words form file\n wordlist = infile.readlines()\n #closing the file\n infile.close()\n #randomly choosing a word\n randnum = random.randint(0,1201)\n #choosing the word from the list\n word = wordlist[randnum]\n #getting rid of the \\n\n word = word.strip(\"\\n\")\n #use a for loop to make the rectangles for the secret word at the top of the window\n for i in range(len(word)):\n rect = Rectangle(Point(225-50*int(len(word)/2)+i*50,60),Point(225-50*int(len(word)/2)+i*50+50,110))\n rect.setFill(\"gold\")\n rect.draw(win)\n rect_list.append(rect)\n #return all the variables needed for later codes\n return win, circlelist, textlist,rect_list, plist, word\n\n#define the drop function with two arguements\ndef drop(polygon,win):\n #importing sleep from time library\n from time import sleep\n #make the polygon red\n polygon.setFill('red')\n #use a for loop to move the polygon downward at a certain speed\n for i in range(30):\n polygon.move(0,20)\n time.sleep(.05)\n\n#define clickedrect function to detect which rectangle was clicked \ndef clickedrect(point,rectangle):\n if point.getY() < rectangle.getP2().getY() and point.getY() > rectangle.getP1().getY() and point.getX()rectangle.getP1().getX():\n #return True if the point is within the rectangle\n return True\n else:\n #return False if the point is outside of the rectangle\n return False\n\n#defind clickedcirc functionn to detect which circle was clicked\ndef clickedcirc(point,circle):\n #get the radius\n radius = circle.getRadius()\n #get the center point of the circle\n cpoint_circle = circle.getCenter()\n #find the x of the centerpoint\n x = cpoint_circle.getX()\n #find the y of the centerpoint\n y = cpoint_circle.getY()\n #find the x of where the user clicks\n x1 = point.getX()\n #find the y of where the user clicks\n y1 = point.getY()\n #find the distance between the x of the point and the center point\n distance_x = x1 - x\n #find the distance between the y of the point and the center point\n distance_y = y1 - y\n #find the distance between the point and the center point of the circle\n hypotenuse = sqrt((distance_x)**2 + (distance_y)**2)\n #use the if statement to check whether the user clicked on the circle\n if hypotenuse <= radius:\n #returns true if they did\n return True\n else:\n #returns false if they did not\n return False\n\n#define colorchange function to change the color of the circle and text being clicked\ndef colorchange(circlelist,textlist,i):\n circlelist[i].setFill(\"gold\")\n textlist[i].setFill(\"black\")\n #return the letter that was clicked\n return textlist[i]\n#defining colorchanghangman only to change the color of the circle in hangman mode\ndef colorchangehangman(circlelist,textlist,i):\n circlelist[i].setFill(\"purple\")\n textlist[i].setFill(\"black\")\n #return the letter that was clicked\n return textlist[i]\n\n#defining hint function\ndef hint(plist,circlelist,textlist,win,wrong,chance,word1,score):\n #call the drop function\n drop(plist[chance[wrong]],win)\n #add 1 to wrong\n wrong += 1\n #call the drop function\n drop(plist[chance[wrong]],win)\n #add 1 to wrong\n wrong += 1\n #-2 in score\n score = score - 2\n #assign a list of letters\n hintlist = [\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\",\"H\",\"I\",\"J\",\"K\",\"L\",\"M\",\"N\",\"O\",\"P\",\"Q\",\"R\",\"S\",\"T\",\"U\",'V','W','X','Y','Z']\n #create another list that matches the letters index\n num = list(range(0,25))\n #assign an empty list\n indexlist= []\n #use a for loop to take out the correct letters from the list and append to indexlist\n for i in set(word1):\n index1 = hintlist.index(i)\n indexlist.append(index1)\n #use for loop to remove those the numbers that corresponds to the letters\n for i in indexlist:\n num.remove(i)\n #Use a for loop to randomly remove 3 wrong letters\n for i in range(3):\n change = random.choice(num)\n num.remove(change)\n colorchange(circlelist,textlist, change)\n #add it to word1 so it wouldnt be chosen twice\n word1 = word1 + textlist[change].getText()\n #return all the variables that will be needed in other function\n return plist,wrong,score,word1 \n\n#defining the move() function\ndef move(scorewin,scorelist,header,headerline):\n #use a while loop to keep the high scores moving while the window is still open\n while scorewin != '':\n #get the position of the header and the header line\n if header.getAnchor().getY()< 0:\n header.move(0,200)\n if headerline.getAnchor().getY()< 0:\n headerline.move(0,200)\n #move the header and the headerline\n header.move(0,-2)\n headerline.move(0,-2)\n #use for loopes to get the position of all the high scores\n for i in scorelist:\n #if it is out of the window then move it to the bottom of the window\n if i.getAnchor().getY()<0:\n i.move(0,200)\n i.move(0,-2)\n #sleep .05 secs to make the movement smoother\n time.sleep(.05)\n #If user clicks on the window then return to the main function\n if scorewin.checkMouse() != None:\n return\n#defining the save function\ndef save(win,roundno,score):\n #creating the graphics objects that is needed\n box = Rectangle(Point(50,200),Point(450,300))\n box.setFill('light grey')\n box.draw(win)\n nametext = Text(Point(100,250),'NAME: ')\n nametext.setOutline('blue')\n nametext.setStyle('bold')\n nametext.draw(win)\n endsave = Entry(Point(190,250),10)\n endsave.setFill('white')\n endsave.draw(win)\n saverect = Rectangle(Point(250,235),Point(320,265))\n saverect.setFill('black')\n saverect.draw(win)\n saveword = Text(Point(285,250),'SAVE')\n saveword.setOutline('white')\n saveword.setStyle('bold')\n saveword.draw(win)\n\n #use a while loop to check whether the user has entered a name and constantly check the mouse of the use\n while saveword != '':\n click = win.checkMouse()\n #if user clicks on the save button, then save it to the output\n if click != None and clickedrect(click,saverect) == True:\n name = endsave.getText()\n output = open('scores.txt','a')\n output.write('{0},{1},{2}\\n'.format(name,roundno,score))\n output.close()\n return True\n \n \n \n#defining the main function\ndef main():\n #calling the control function for the control panel\n panel, new, quitbox,hintbutton,highscorebutton, hangman = control()\n #assigning variables\n win, circlelist, textlist, rect_list, plist, word =('','','','','','')\n hangmanwin, circlelist, textlist, objectlist, rect_list, word = ('','','','','','')\n quitnotclick = True\n guessword = []\n \n #use a while loop for the code as long as quit was not clicked\n while quitnotclick == True:\n #continuously check mouse\n click = panel.checkMouse()\n #if quit was clicked then stop the while loop and close the windo\n if click != None and clickedrect(click,quitbox) == True:\n quitnotclick = False\n #if HANGMAN was clicked then open the hangman window\n if click != None and clickedrect(click,hangman)==True:\n #call the hangmangame() function\n hangmanwin, circlelist, textlist, objectlist, rect_list, word = hangmangame()\n #start with round 1\n roundno = 1\n #assigning the variables for later\n chance = [0,1,2,3,5,6,7,8,9,10]\n #score starts with 10 and 0 wrongs\n score = 10\n wrong = 0\n #setup the scoreboard\n #and display it on the window\n scoreboard = Text(Point(250, 30), \"Score : \" + str(score))\n scoreboard.draw(hangmanwin)\n\n if hangmanwin != '' and click == None:\n #continuously check for mouseclick in the game panel\n click2 = hangmanwin.checkMouse()\n #if user clicked on game window\n if click2 != None:\n #use a for loop to check whether the user clicked any of the circle\n for i in circlelist:\n #call clickedcirc to check\n clickcircle = clickedcirc(click2,i)\n #use if statement to change the color of the circle\n if clickcircle == True:\n #if a certain circle is clicked on, change the color of the circle and the text\n alphabet = colorchangehangman(circlelist, textlist,circlelist.index(i))\n #setup a variable to check whether the input is right or wrong\n choice = False\n #use a for loop to check the input\n for i in range(len(list(word))):\n if alphabet.getText() == word[i]:\n choice = True\n if choice == True:\n #display the letter in one of the rectangles at the top of the screen\n guess = Text(rect_list[i].getCenter(),alphabet.getText())\n guess.draw(hangmanwin)\n #put it into a list\n guessword.append(alphabet.getText())\n #if the user guessed the correct word\n if choice == True:\n if ''.join(sorted(list(set(guessword)))) == ''.join(sorted(list(set(list(word))))):\n #display text as in project2 manual\n end = Text(Point(250,250),\"You WIN! BOILER UP!\")\n end.setSize(34)\n end.setFill(\"orange\")\n continuetext = Text(Point(250,275),\"Click to continue.\")\n continuetext.setFill(\"grey\")\n continuetext.draw(hangmanwin)\n end.draw(hangmanwin)\n #wait for user to click\n hangmanwin.getMouse()\n #close the game window\n hangmanwin.close()\n #add 10 to the current score for next round\n score = score + 10\n\n #call the game function again\n hangmanwin, circlelist, textlist, objectlist, rect_list,word = hangmangame()\n #reset the number of wrong input\n wrong = 0\n roundno += 1\n guessword = []\n #display the scoreboard\n scoreboard = Text(Point(250, 30), \"Score : \" + str(score))\n scoreboard.draw(hangmanwin)\n #if the user guessed the wrong letter\n if choice == False:\n #decrease score by 1\n score = score - 1\n #update scoreboard\n scoreboard.setText(\"Score : \" + str(score))\n #call the hang function\n hang(objectlist[wrong])\n #increase the number of wrong inputs by 1\n wrong += 1\n #if number of wrong tries equals to 10, display the following\n if wrong == 10:\n endtext = Text(Point(250,250),'OH NO! THE MAN DIED!')\n endtext.setStyle('bold')\n endtext.setOutline('pink')\n endtext.setSize(30)\n endtext.draw(hangmanwin)\n hangmanwin.getMouse()\n hangmanwin.close()\n hangmanwin = ''\n \n #if new was clicked then call game function\n if click != None and clickedrect(click,new) == True:\n #if window exist\n if win != '':\n #close window\n win.close()\n #open new game window\n win, circlelist, textlist, rect_list, plist, word = game()\n roundno = 1\n word1 = word\n #assigning the variables for later\n chance = [0,1,2,3,5,6,7,8,9,10]\n score = 10\n wrong = 0\n #setup the scoreboard\n #and display it on the window\n scoreboard = Text(Point(250, 30), \"Score : \" + str(score))\n scoreboard.draw(win)\n \n\n if click != None and clickedrect(click,hintbutton)== True and win != '':\n plist,wrong,score,word1 = hint(plist,circlelist,textlist,win,wrong,chance,word1,score)\n scoreboard.setText(\"Score : \" + str(score))\n #if window exist and the user is not clicking on the control panel\n if win != '' and click == None:\n #continuously check for mouseclick in the game panel\n click1 = win.checkMouse()\n #if user clicked on game window\n if click1 != None:\n #use a for loop to check whether the user clicked any of the circle\n for i in circlelist:\n #call clickedcirc to check\n clickcircle = clickedcirc(click1,i)\n #use if statement to change the color of the circle\n if clickcircle == True:\n #if a certain circle is clicked on, change the color of the circle and the text\n alphabet = colorchange(circlelist, textlist,circlelist.index(i))\n #setup a variable to check whether the input is right or wrong\n choice = False\n #use a for loop to check the input\n for i in range(len(list(word))):\n if alphabet.getText() == word[i]:\n choice = True\n if choice == True:\n #display the letter in one of the rectangles at the top of the screen\n guess = Text(rect_list[i].getCenter(),alphabet.getText())\n guess.draw(win)\n #put it into a list\n guessword.append(alphabet.getText())\n \n #if the user guessed the correct word\n if choice == True:\n if ''.join(sorted(list(set(guessword)))) == ''.join(sorted(list(set(list(word))))):\n #display text as in project2 manual\n end = Text(Point(250,250),\"You win! BOILER UP!\")\n end.setSize(34)\n end.setFill(\"grey\")\n continuetext = Text(Point(250,275),\"Click to continue.\")\n continuetext.setFill(\"grey\")\n continuetext.draw(win)\n end.draw(win)\n #wait for user to click\n win.getMouse()\n #close the game window\n win.close()\n #add 10 to the current score for next round\n score = score + 10\n\n #call the game function again\n win, circlelist, textlist, rect_list, plist, word = game()\n #reset the number of wrong input\n wrong = 0\n roundno += 1\n # if it is the tenth round (20 or 30 or 40 etc.) run the tenth round game\n if roundno % 10 == 0:\n if tenthroundgame() is True:\n # if they win increase score by 20\n score = score + 20\n guessword = []\n print(word)\n #display the scoreboard\n scoreboard = Text(Point(250, 30), \"Score : \" + str(score))\n scoreboard.draw(win)\n #if the user guessed the wrong letter\n if choice == False:\n #decrease score by 1\n score = score - 1\n #update scoreboard\n scoreboard.setText(\"Score : \" + str(score))\n #call the drop function\n drop(plist[chance[wrong]],win)\n #increase the number of wrong inputs by 1\n wrong += 1\n #if number of wrong tries equals to 10\n if wrong == 10:\n if finalguess(win,word) == True:\n \n #call the game function again\n win, circlelist, textlist, rect_list, plist, word = game()\n #reset the number of wrong input\n wrong = 0\n roundno += 1\n guessword = []\n #display the scoreboard\n scoreboard = Text(Point(250, 30), \"Score : \" + str(score))\n scoreboard.draw(win)\n\n else:\n #call save() function to save the score\n saving = save(win,roundno,score)\n #close the window after saving\n if saving == True:\n win.close()\n win = ''\n \n #if the user clicked on the highscore button \n if click != None and clickedrect(click,highscorebutton) == True:\n #open the related file\n f = open('scores.txt',\"r\")\n #read the file and make it a list\n flist = f.readlines()\n #assign an empty list\n formatflist = []\n #format the list, and append it to formatlist\n for i in range(len(flist)):\n flist[i] = flist[i].strip('\\n')\n flist[i] = flist[i].split(',')\n flist[i][2] = int(flist[i][2])\n flist[i].reverse()\n formatflist.append(flist[i])\n #sort the format list\n formatflist.sort(reverse = True)\n #display the window with the header and the headerline\n scorewin = GraphWin('HIGH SCORES',240,200)\n header = Text(Point(120,17),'Player\\tRounds\\tScore')\n header.setStyle('bold')\n header.draw(scorewin)\n headerline = Text(Point(120,30),'=-=-=-=-=-=-=-=-=-=-=-=-=-=-=')\n headerline.draw(scorewin)\n #make an empty list for the top 7 scores\n scorelist = []\n #use a for loop to append the top 7 scores into scorelist[]\n for i in range(7):\n score = Text(Point(120,35 + (10*((i+1)*2))),'{0:<9}\\t{1:>4}\\t{2:>2}'.format(formatflist[i][2],formatflist[i][1],formatflist[i][0]))\n score.draw(scorewin)\n scorelist.append(score)\n #call move function\n move(scorewin,scorelist,header,headerline)\n #close the window after calling move function\n scorewin.close()\n \n \n #check to see if the user clicked on the quit button during the game\n if click != None and clickedrect(click,quitbox) == True and win != '' :\n if win != '':\n win.close()\n quitnotclick = False\n\n panel.close()\n hangmanwin.close()\n\n# define the final guess function\ndef finalguess(win,word):\n # create the objects used in the game the first being a check box\n check = Rectangle(Point(380,320), Point (450,350))\n check.setFill('red')\n checkword = Text(Point(415,335),\"check\")\n checkword.setStyle('bold')\n check.draw(win)\n checkword.draw(win)\n # Then create an entry \n fguess = Entry(Point(350,300),8)\n fguess.setFill(\"white\")\n # make sure user understands this is their final guess\n fguessheader = Text(Point(275,300), \"Final guess:\")\n # design it\n fguessheader.setOutline('red')\n fguessheader.setStyle('bold')\n fguessheader.setSize(10)\n # draw them into the windo\n fguess.draw(win)\n fguessheader.draw(win)\n\n # create an endless while loop my having a boolean variable\n f = True\n while f is True:\n # have a checkmouse\n point = win.checkMouse()\n # create a condition that only works if their is a click\n if point != None:\n # make sure the click is in the check box\n if clickedrect(point, check) == True:\n # create a variable for the text in the entry box\n txt = fguess.getText()\n # if that text is equal to the secret word\n if txt.upper() == word:\n # close the window and return true else make f false\n win.close()\n return True\n else:\n f = False\n # if no true is returned, return false\n return False\n\n\n# define the tenthroundgame round\ndef tenthroundgame():\n # create a window\n win = GraphWin(\"Rounds of ten\",300,300)\n # describle the rules and set the size for that\n inst = Text(Point(150,250),\"If you get u click on 2 blues u get twenty points\")\n inst.setSize(10)\n # draw this into the window\n inst.draw(win)\n # create a list of 2 colors\n listofcolors = [\"blue\",\"red\"]\n # assign them randomly to four different variables\n color1 = random.choice(listofcolors)\n color2 = random.choice(listofcolors)\n color3 = random.choice(listofcolors)\n color4 = random.choice(listofcolors)\n # make a list of these colors\n listofblockcolors = [color1,color2,color3,color4]\n # create 4 blocks of those colors\n block1 = Rectangle(Point(15,125),Point(65,175))\n block1.setFill(color1)\n block2 = Rectangle(Point(90,125),Point(140,175))\n block2.setFill(color2)\n block3 = Rectangle(Point(165,125),Point(215,175))\n block3.setFill(color3)\n block4 = Rectangle(Point(240,125),Point(290,175))\n block4.setFill(color4)\n # draw these blocks into the window\n block1.draw(win)\n block2.draw(win)\n block3.draw(win)\n block4.draw(win)\n # make a list of these blocks\n blocklist = [block1,block2,block3,block4]\n \n\n # do the same thing as before, but make sure the blocks are all black now and they cover those blocks\n bblock1 = Rectangle(Point(15,125),Point(65,175))\n bblock1.setFill(\"black\")\n bblock2 = Rectangle(Point(90,125),Point(140,175))\n bblock2.setFill(\"black\")\n bblock3 = Rectangle(Point(165,125),Point(215,175))\n bblock3.setFill(\"black\")\n bblock4 = Rectangle(Point(240,125),Point(290,175))\n bblock4.setFill(\"black\")\n bblock1.draw(win)\n bblock2.draw(win)\n bblock3.draw(win)\n bblock4.draw(win)\n blackblocklist = [bblock1,bblock2,bblock3,bblock4]\n\n # create 2 counts\n count = 0\n c = 0\n # zip these 2 lists so they are with theyre equivilent black blocks\n # create a for loop that goes through this zipped list\n for bb,color in zip(blackblocklist,listofblockcolors):\n # pause the game and wait for click\n click = win.getMouse()\n # if a black block is clicked:\n if clickedrect(click,bb):\n # undraw it\n bb.undraw()\n # if the color is blue up the count of \"count\"\n if color == \"blue\":\n count +=1\n # if count is 2 return true\n if count == 2:\n return True\n # make sure only 2 rounds are played by creating this variable\n c += 1\n # end the game if 2 rounds are up\n if c == 2:\n win.close()\n break\n # return false if true isnt returned\n return False \n\n\n \n#call main function\nmain()\n"} {"blob_id": "f5723625e2f2db2bfd3b14e6955bf20278235b30", "repo_name": "adingler711/School_Deep_Learning", "path": "/simple_MLP_fixed_size.py", "length_bytes": 65980, "score": 4.15625, "int_score": 4, "content": "# -*- coding: utf-8 -*-\nimport random # we randomly define initial values for connection weights, and also randomly select\n# which training data that we will use for a given run.\nfrom math import exp #the exp function (e to the x); it's part of our transfer function definition\nimport numpy as np\n\n\n####################################################################################################\n####################################################################################################\n#\n# This is a tutorial program, designed for those who are learning Python, and specifically using\n# Python for neural networks applications. It presents a feedforward Multilayer Perceptron (MLP).\n#\n# The focus is simply on defining the network, defining an initial set of connection and bias weights,\n# defining a set of training data (together with their desired outputs). Then, this code allows for\n# random selecting of one of the training data sets, presenting the selected training input data to\n# the network, and obtaining output. Then, the code computes the summed squared error (SSE) across\n# the output nodes that are activated in response to the input training data.\n#\n# By adjusting the \"maxNumIterations\" parameter, the user can control how many times this process\n# is repeated.\n#\n# There is no training in this particular code.\n#\n#\n# SPECIAL NOTE re/ Python code structure:\n# Python uses a 'main' module, which is typically located at the end of the code.\n# There is a short line after that which actual RUNS the 'main' module.\n# All supporting tasks are defined as various procedures and functions. They are stored higher in\n# the code.\n# Typically, the most general and global procedures and functions are at the bottom of the code, and\n# the more detail-specific ones are at the top.\n# Thus, if you want to understand a piece of code, you might want to read from bottom-to-top (or\n# from more general-to-specific), instead of top-to-bottom (detailed-specific-to-general).\n#\n# Notice that control (e.g., nesting) is defined by spacing.\n# You can define the number of spaces for a tab, but you have to be consistent.\n# Notice that once a function or procedure is defined, every command within it must be tabbed in.\n#\n####################################################################################################\n###################################################################################################\n#\n# A collection of worker-functions, designed to do specific small tasks\n#\n####################################################################################################\n####################################################################################################\n\n\n# ------------------------------------------------------#\n\n# Compute neuron activation using sigmoid transfer function\ndef computeTransferFnctn(summedNeuronInput, alpha):\n\n activation = 1.0 / (1.0 + exp(-alpha * summedNeuronInput))\n\n return activation\n\n\n# ------------------------------------------------------#\n\n# Compute derivative of transfer function\ndef computeTransferFnctnDeriv(NeuronOutput, alpha):\n\n return alpha * NeuronOutput * (1.0 - NeuronOutput)\n\n\n####################################################################################################\n####################################################################################################\n#\n# Function to obtain the neural network size specifications\n#\n####################################################################################################\n####################################################################################################\n\ndef obtainNeuralNetworkSizeSpecs():\n\n # This is a function, not a procedure, because it returns a single value (which really is a list of\n # three values). It is called directly from 'main.'\n #\n # This function specifies the size of the input (I), hidden (H),\n # and output (O) layers.\n # In a more general version of a neural network, this function should ask the user for the numbers\n # of nodes at each layer of the network.\n\n numInputNodes = 2\n numHiddenNodes = 2\n numOutputNodes = 2\n print ' '\n print 'This network is set up to run the X-OR problem.'\n print 'The numbers of nodes in the input, hidden, and output layers have been set to 2 each.'\n\n # We create a list containing the crucial SIZES for the connection weight arrays\n arraySizeList = (numInputNodes, numHiddenNodes, numOutputNodes)\n\n # We return this list to the calling procedure, 'main'.\n return arraySizeList\n\n\n####################################################################################################\n####################################################################################################\n#\n# Function to initialize a specific connection weight with a randomly-generated number between 0 & 1\n#\n####################################################################################################\n####################################################################################################\n\ndef InitializeWeight():\n\n randomNum = random.random()\n weight = 1 - 2 * randomNum\n\n return (weight)\n\n\n####################################################################################################\n####################################################################################################\n#\n# Function to initialize the connection weight arrays\n#\n####################################################################################################\n####################################################################################################\n\ndef initializeWeightArray(weightArraySizeList, debugInitializeOff):\n\n # This function takes in the two parameters, the number of nodes on the bottom (of any two layers),\n # and the number of nodes in the layer just above it.\n # It will use these two sizes to create a weight array.\n # The weights will initially be given randomly-assigned values, so that we can trace the creation and\n # transfer of this array back to the 'main' procedure.\n\n numBottomNodes = weightArraySizeList[0]\n numUpperNodes = weightArraySizeList[1]\n\n # Initialize the weight variables with random weights\n wt00 = InitializeWeight()\n wt01 = InitializeWeight()\n wt10 = InitializeWeight()\n wt11 = InitializeWeight()\n weightArray = np.array([[wt00, wt10], [wt01, wt11]])\n\n # Debug mode: if debug is set to False, then we DO NOT do the prints\n if not debugInitializeOff:\n # Print the weights\n print ' '\n print ' Inside initializeWeightArray'\n # The following two prints are commented out because we have fixed values for\n # the numbers of nodes in each layer for this version of the program\n # print ' The number of lower nodes is', numBottomNodes\n # print ' The number of upper nodes is', numUpperNodes\n print ' ' # to get a line space\n print ' The weights just initialized are: '\n print ' weight00 = %.4f,' % wt00\n print ' weight01 = %.4f,' % wt01\n print ' weight10 = %.4f,' % wt10\n print ' weight11 = %.4f,' % wt11\n\n\n # Debug mode: if debug is set to False, then we DO NOT do the prints\n if not debugInitializeOff:\n # Print the entire weights array.\n print ' '\n print ' The weightArray just established is: ', weightArray\n print ' '\n print ' Within this array: '\n print ' weight00 = %.4f weight10 = %.4f' % (weightArray[0, 0], weightArray[0, 1])\n print ' weight01 = %.4f weight11 = %.4f' % (weightArray[1, 0], weightArray[1, 1])\n print ' Returning to calling procedure'\n\n # We return the array to the calling procedure, 'main'.\n return weightArray\n\n\n####################################################################################################\n####################################################################################################\n#\n# Function to initialize the bias weight arrays\n#\n####################################################################################################\n####################################################################################################\n\ndef initializeBiasWeightArray(weightArray1DSize):\n\n # This procedure takes in a single parameters; the number of nodes in a given layer.\n\n\n # This will be more useful when we move to array operations; right now, it is a placeholder step\n numBiasNodes = weightArray1DSize\n\n # Hard-coding bias values for two nodes; this code really SHOULD be upgraded to deal with\n # the number of nodes specified by weightArray1DSize; see subsequent versions for that upgrade.\n\n # Initialize the bias weight variables with random weights\n biasWeight0 = InitializeWeight()\n biasWeight1 = InitializeWeight()\n\n # Store the two bias weights in a 1-D array\n biasWeightArray = np.array([biasWeight0, biasWeight1])\n\n return (biasWeightArray)\n\n\n####################################################################################################\n####################################################################################################\n#\n# Function to obtain a randomly-selected training data set list, which will contain the two input\n# values (each either 0 or 1), and two output values (see list below), and a third value which is\n# the number of the training data set, in the range of (0..3). (There are a total of four training\n# data sets.)\n#\n####################################################################################################\n####################################################################################################\n\ndef obtainRandomXORTrainingValues():\n\n # The training data list will have four values for the X-OR problem:\n # - First two valuea will be the two inputs (0 or 1 for each)\n # - Second two values will be the two outputs (0 or 1 for each)\n # There are only four combinations of 0 and 1 for the input data\n # Thus there are four choices for training data, which we'll select on random basis\n\n # The fifth element in the list is the NUMBER of the training set; setNumber = 1..3\n # The setNumber is used to assign the Summed Squared Error (SSE) with the appropriate\n # training set\n # This is because we need ALL the SSE's to get below a certain minimum before we stop\n # training the network\n\n trainingDataSetNum = random.randint(1, 4)\n\n if trainingDataSetNum > 3.1: # The selection is for training list 4\n trainingDataList = (1, 1, 0, 1, 3) # training data list 4 selected\n elif trainingDataSetNum > 2.1: # The selection is for training lists between 3 & 4\n trainingDataList = (1, 0, 1, 0, 2) # training data list 3 selected\n elif trainingDataSetNum > 1.1: # The selection is for training lists between 2 & 4\n trainingDataList = (0, 1, 1, 0, 1) # training data list 2 selected\n else:\n trainingDataList = (0, 0, 0, 1, 0) # training data list 1 selected\n\n return trainingDataList\n\n\n####################################################################################################\n####################################################################################################\n#\n# Compute neuron activation - this is the summed weighted inputs after passing through transfer fnctn\n#\n####################################################################################################\n####################################################################################################\n\ndef computeSingleNeuronActivation(alpha, wt0, wt1, input0, input1, bias, debugComputeSingleNeuronActivationOff):\n\n # Obtain the inputs into the neuron; this is the sum of weights times inputs\n summedNeuronInput = wt0 * input0 + wt1 * input1 + bias\n\n # Pass the summedNeuronActivation and the transfer function parameter alpha into the transfer function\n activation = computeTransferFnctn(summedNeuronInput, alpha)\n\n if not debugComputeSingleNeuronActivationOff:\n print ' '\n print ' In computeSingleNeuronActivation with input0, input 1 given as: ', input0, ', ', input1\n print ' The summed neuron input is %.4f' % summedNeuronInput\n print ' The activation (applied transfer function) for that neuron is %.4f' % activation\n\n return activation\n\n\n####################################################################################################\n####################################################################################################\n#\n# Perform a single feedforward pass\n#\n####################################################################################################\n####################################################################################################\n\n\ndef ComputeSingleFeedforwardPass(alpha, inputDataList, wWeightArray, vWeightArray,\n biasHiddenWeightArray, biasOutputWeightArray, debugComputeSingleNeuronActivationOff):\n\n input0 = inputDataList[0]\n input1 = inputDataList[1]\n\n # Assign the input-to-hidden weights to specific variables\n [wWt00, wWt10,\n wWt01, wWt11] = (wWeightArray[0, 0], wWeightArray[0, 1],\n wWeightArray[1, 0], wWeightArray[1, 1])\n\n # Assign the hidden-to-output weights to specific variables\n [vWt00, vWt10,\n vWt01, vWt11] = (vWeightArray[0, 0], vWeightArray[0, 1],\n vWeightArray[1, 0], vWeightArray[1, 1])\n\n # Assign the bias weights to specific variables\n [biasHidden0, biasHidden1,\n biasOutput0, biasOutput1] = (biasHiddenWeightArray[0], biasHiddenWeightArray[1],\n biasOutputWeightArray[0], biasOutputWeightArray[1])\n\n # Obtain the activations of the hidden nodes\n if not debugComputeSingleNeuronActivationOff:\n print ' '\n print ' For hiddenActivation0 from input0, input1 = ', input0, ', ', input1\n\n hiddenActivation0 = computeSingleNeuronActivation(alpha, wWt00, wWt10, input0, input1, biasHidden0,\n debugComputeSingleNeuronActivationOff)\n\n if not debugComputeSingleNeuronActivationOff:\n print ' '\n print ' For hiddenActivation1 from input0, input1 = ', input0, ', ', input1\n\n hiddenActivation1 = computeSingleNeuronActivation(alpha, wWt01, wWt11, input0, input1, biasHidden1,\n debugComputeSingleNeuronActivationOff)\n\n if not debugComputeSingleNeuronActivationOff:\n print ' '\n print ' In computeSingleFeedforwardPass: '\n print ' Input node values: ', input0, ', ', input1\n print ' The activations for the hidden nodes are:'\n print ' Hidden0 = %.4f' % hiddenActivation0, 'Hidden1 = %.4f' % hiddenActivation1\n\n # Obtain the activations of the output nodes\n outputActivation0 = computeSingleNeuronActivation(alpha, vWt00, vWt10, hiddenActivation0,\n hiddenActivation1, biasOutput0,\n debugComputeSingleNeuronActivationOff)\n\n outputActivation1 = computeSingleNeuronActivation(alpha, vWt01, vWt11, hiddenActivation0,\n hiddenActivation1, biasOutput1,\n debugComputeSingleNeuronActivationOff)\n if not debugComputeSingleNeuronActivationOff:\n print ' '\n print ' Computing the output neuron activations'\n print ' '\n print ' Back in ComputeSingleFeedforwardPass (for hidden-to-output computations)'\n print ' The activations for the output nodes are:'\n print ' Output0 = %.4f' % outputActivation0, 'Output1 = %.4f' % outputActivation1\n\n actualAllNodesOutputList = (hiddenActivation0, hiddenActivation1, outputActivation0, outputActivation1)\n\n return actualAllNodesOutputList\n\n\n####################################################################################################\n####################################################################################################\n#\n# Determine initial Summed Squared Error (SSE) and Total Summed Squared Error (TotalSSE) as an\n# array, SSE_Array (SSE[0], SSE[1], SSE[2], SSE[3], Total_SSE), return array to calling procedure\n# Note: This function returns the SSE_Array\n# Note: This function USES computeSingleFeedforwardPass\n#\n####################################################################################################\n####################################################################################################\n\ndef computeSSE_Values(alpha, SSE_InitialArray, wWeightArray, vWeightArray, biasHiddenWeightArray,\n biasOutputWeightArray, debugSSE_InitialComputationOff):\n\n if not debugSSE_InitialComputationOff:\n debugComputeSingleFeedforwardPassOff = False\n else:\n debugComputeSingleFeedforwardPassOff = True\n\n # Compute a single feed-forward pass and obtain the Actual Outputs for zeroth data set\n inputDataList = (0, 0)\n actualAllNodesOutputList = ComputeSingleFeedforwardPass(alpha, inputDataList, wWeightArray, vWeightArray,\n biasHiddenWeightArray, biasOutputWeightArray,\n debugComputeSingleFeedforwardPassOff)\n actualOutput0 = actualAllNodesOutputList[2]\n actualOutput1 = actualAllNodesOutputList[3]\n error0 = 0.0 - actualOutput0\n error1 = 1.0 - actualOutput1\n SSE_InitialArray[0] = error0 ** 2 + error1 ** 2\n\n # debug print for function:\n if not debugSSE_InitialComputationOff:\n print ' '\n print ' In computeSSE_Values'\n\n # debug print for (0,0):\n if not debugSSE_InitialComputationOff:\n input0 = inputDataList[0]\n input1 = inputDataList[1]\n print ' '\n print ' Actual Node Outputs for (0,0) training set:'\n print ' input0 = ', input0, ' input1 = ', input1\n print ' actualOutput0 = %.4f actualOutput1 = %.4f' % (actualOutput0, actualOutput1)\n print ' error0 = %.4f error1 = %.4f' % (error0, error1)\n print ' Initial SSE for (0,0) = %.4f' % SSE_InitialArray[0]\n\n # Compute a single feed-forward pass and obtain the Actual Outputs for first data set\n inputDataList = (0, 1)\n actualAllNodesOutputList = ComputeSingleFeedforwardPass(alpha, inputDataList, wWeightArray, vWeightArray,\n biasHiddenWeightArray, biasOutputWeightArray,\n debugComputeSingleFeedforwardPassOff)\n actualOutput0 = actualAllNodesOutputList[2]\n actualOutput1 = actualAllNodesOutputList[3]\n error0 = 1.0 - actualOutput0\n error1 = 0.0 - actualOutput1\n SSE_InitialArray[1] = error0 ** 2 + error1 ** 2\n\n # debug print for (0,1):\n if not debugSSE_InitialComputationOff:\n input0 = inputDataList[0]\n input1 = inputDataList[1]\n print ' '\n print ' Actual Node Outputs for (0,1) training set:'\n print ' input0 = ', input0, ' input1 = ', input1\n print ' actualOutput0 = %.4f actualOutput1 = %.4f' % (actualOutput0, actualOutput1)\n print ' error0 = %.4f error1 = %.4f' % (error0, error1)\n print ' Initial SSE for (0,1) = %.4f' % SSE_InitialArray[1]\n\n # Compute a single feed-forward pass and obtain the Actual Outputs for second data set\n inputDataList = (1, 0)\n actualAllNodesOutputList = ComputeSingleFeedforwardPass(alpha, inputDataList, wWeightArray, vWeightArray,\n biasHiddenWeightArray, biasOutputWeightArray,\n debugComputeSingleFeedforwardPassOff)\n actualOutput0 = actualAllNodesOutputList[2]\n actualOutput1 = actualAllNodesOutputList[3]\n error0 = 1.0 - actualOutput0\n error1 = 0.0 - actualOutput1\n SSE_InitialArray[2] = error0 ** 2 + error1 ** 2\n\n # debug print for (1,0):\n if not debugSSE_InitialComputationOff:\n input0 = inputDataList[0]\n input1 = inputDataList[1]\n print ' '\n print ' Actual Node Outputs for (1,0) training set:'\n print ' input0 = ', input0, ' input1 = ', input1\n print ' actualOutput0 = %.4f actualOutput1 = %.4f' % (actualOutput0, actualOutput1)\n print ' error0 = %.4f error1 = %.4f' % (error0, error1)\n print ' Initial SSE for (1,0) = %.4f' % SSE_InitialArray[2]\n\n # Compute a single feed-forward pass and obtain the Actual Outputs for third data set\n inputDataList = (1, 1)\n actualAllNodesOutputList = ComputeSingleFeedforwardPass(alpha, inputDataList, wWeightArray, vWeightArray,\n biasHiddenWeightArray, biasOutputWeightArray,\n debugComputeSingleFeedforwardPassOff)\n actualOutput0 = actualAllNodesOutputList[2]\n actualOutput1 = actualAllNodesOutputList[3]\n error0 = 0.0 - actualOutput0\n error1 = 1.0 - actualOutput1\n SSE_InitialArray[3] = error0 ** 2 + error1 ** 2\n\n # debug print for (1,1):\n if not debugSSE_InitialComputationOff:\n input0 = inputDataList[0]\n input1 = inputDataList[1]\n print ' '\n print ' Actual Node Outputs for (1,1) training set:'\n print ' input0 = ', input0, ' input1 = ', input1\n print ' actualOutput0 = %.4f actualOutput1 = %.4f' % (actualOutput0, actualOutput1)\n print ' error0 = %.4f error1 = %.4f' % (error0, error1)\n print ' Initial SSE for (1,1) = %.4f' % SSE_InitialArray[3]\n\n # Initialize an array of SSE values\n SSE_InitialTotal = SSE_InitialArray[0] + SSE_InitialArray[1] + SSE_InitialArray[2] + SSE_InitialArray[3]\n\n # debug print for SSE_InitialTotal:\n if not debugSSE_InitialComputationOff:\n print ' '\n print ' The initial total of the SSEs is %.4f' % SSE_InitialTotal\n\n SSE_InitialArray[4] = SSE_InitialTotal\n\n return SSE_InitialArray\n\n\n####################################################################################################\n# **************************************************************************************************#\n####################################################################################################\n#\n# Backpropagation Section\n#\n####################################################################################################\n# **************************************************************************************************#\n####################################################################################################\n\n# This section has been removed from this particular version of code.\n\n####################################################################################################\n#\n# Optional Debug and Code-Trace Print: Backpropagate the hidden-to-output connection weights\n#\n####################################################################################################\n\ndef PrintAndTraceBackpropagateOutputToHidden(alpha, eta, errorList,\n actualAllNodesOutputList, transFuncDerivList, deltaVWtArray, vWeightArray,\n newVWeightArray):\n\n [hiddenNode0, hiddenNode1,\n outputNode0, outputNode1] = (actualAllNodesOutputList[0], actualAllNodesOutputList[1],\n actualAllNodesOutputList[2], actualAllNodesOutputList[3])\n\n transFuncDeriv0, transFuncDeriv1 = transFuncDerivList[0], transFuncDerivList[1]\n\n # Pre Debug: These variables did not get the mirror image fix\n # deltaVWt00 = deltaVWtArray[0,0]\n # deltaVWt01 = deltaVWtArray[0,1]\n # deltaVWt10 = deltaVWtArray[1,0]\n # deltaVWt11 = deltaVWtArray[1,1]\n\n # New code:\n [deltaVWt00, deltaVWt01,\n deltaVWt10, deltaVWt11] = (deltaVWtArray[0, 0], deltaVWtArray[1, 0],\n deltaVWtArray[0, 1], deltaVWtArray[1, 1])\n\n error0, error1 = errorList[0], errorList[1]\n\n print ' '\n print 'In Print and Trace for Backpropagation: Hidden to Output Weights'\n print ' Assuming alpha = 1'\n print ' '\n print ' The hidden node activations are:'\n print ' Hidden node 0: ', ' %.4f' % hiddenNode0, ' Hidden node 1: ', ' %.4f' % hiddenNode1\n print ' '\n print ' The output node activations are:'\n print ' Output node 0: ', ' %.3f' % outputNode0, ' Output node 1: ', ' %.3f' % outputNode1\n print ' '\n print ' The transfer function derivatives are: '\n print ' Deriv-F(0): ', ' %.3f' % transFuncDeriv0, ' Deriv-F(1): ', ' %.3f' % transFuncDeriv1\n\n print ' '\n print 'The computed values for the deltas are: '\n print ' eta * error * trFncDeriv * hidden'\n print ' deltaVWt00 = ', ' %.2f' % eta, '* %.4f' % error0, ' * %.4f' % transFuncDeriv0, ' * %.4f' % hiddenNode0\n print ' deltaVWt01 = ', ' %.2f' % eta, '* %.4f' % error1, ' * %.4f' % transFuncDeriv1, ' * %.4f' % hiddenNode0\n print ' deltaVWt10 = ', ' %.2f' % eta, '* %.4f' % error0, ' * %.4f' % transFuncDeriv0, ' * %.4f' % hiddenNode1\n print ' deltaVWt11 = ', ' %.2f' % eta, '* %.4f' % error1, ' * %.4f' % transFuncDeriv1, ' * %.4f' % hiddenNode1\n print ' '\n print 'Values for the hidden-to-output connection weights:'\n print ' Old: New: eta*Delta:'\n print '[0,0]: %.4f' % vWeightArray[0, 0], ' %.4f' % newVWeightArray[0, 0], ' %.4f' % deltaVWtArray[0, 0]\n print '[0,1]: %.4f' % vWeightArray[1, 0], ' %.4f' % newVWeightArray[1, 0], ' %.4f' % deltaVWtArray[1, 0]\n print '[1,0]: %.4f' % vWeightArray[0, 1], ' %.4f' % newVWeightArray[0, 1], ' %.4f' % deltaVWtArray[0, 1]\n print '[1,1]: %.4f' % vWeightArray[1, 1], ' %.4f' % newVWeightArray[1, 1], ' %.4f' % deltaVWtArray[1, 1]\n\n\n####################################################################################################\n#\n# Optional Debug and Code-Trace Print: Backpropagate the input-to-hidden connection weights\n#\n####################################################################################################\n\ndef PrintAndTraceBackpropagateHiddenToInput(alpha, eta, inputDataList, errorList,\n actualAllNodesOutputList, transFuncDerivHiddenList,\n transFuncDerivOutputList, deltaWWtArray, vWeightArray, wWeightArray,\n newWWeightArray, biasWeightArray):\n\n inputNode0 = inputDataList[0]\n inputNode1 = inputDataList[1]\n hiddenNode0 = actualAllNodesOutputList[0]\n hiddenNode1 = actualAllNodesOutputList[1]\n outputNode0 = actualAllNodesOutputList[2]\n outputNode1 = actualAllNodesOutputList[3]\n transFuncDerivHidden0 = transFuncDerivHiddenList[0]\n transFuncDerivHidden1 = transFuncDerivHiddenList[1]\n transFuncDerivOutput0 = transFuncDerivOutputList[0]\n transFuncDerivOutput1 = transFuncDerivOutputList[1]\n\n # Pre Debug: These variables did not get the mirror image fix\n # deltaVWt00 = deltaVWtArray[0,0]\n # deltaVWt01 = deltaVWtArray[0,1]\n # deltaVWt10 = deltaVWtArray[1,0]\n # deltaVWt11 = deltaVWtArray[1,1]\n\n # New code:\n wWt00 = wWeightArray[0, 0]\n wWt01 = wWeightArray[1, 0]\n wWt10 = wWeightArray[0, 1]\n wWt11 = wWeightArray[1, 1]\n\n deltaWWt00 = deltaWWtArray[0, 0]\n deltaWWt01 = deltaWWtArray[1, 0]\n deltaWWt10 = deltaWWtArray[0, 1]\n deltaWWt11 = deltaWWtArray[1, 1]\n\n vWt00 = vWeightArray[0, 0]\n vWt01 = vWeightArray[1, 0]\n vWt10 = vWeightArray[0, 1]\n vWt11 = vWeightArray[1, 1]\n\n error0 = errorList[0]\n error1 = errorList[1]\n\n errorTimesTransD0 = error0 * transFuncDerivOutput0\n errorTimesTransD1 = error1 * transFuncDerivOutput1\n\n biasHidden0 = biasWeightArray[0, 0]\n biasHidden1 = biasWeightArray[0, 1]\n\n partialSSE_w_Wwt00 = -transFuncDerivHidden0 * inputNode0 * (vWt00 * error0 + vWt01 * error1)\n partialSSE_w_Wwt01 = -transFuncDerivHidden1 * inputNode0 * (vWt10 * error0 + vWt11 * error1)\n partialSSE_w_Wwt10 = -transFuncDerivHidden0 * inputNode1 * (vWt00 * error0 + vWt01 * error1)\n partialSSE_w_Wwt11 = -transFuncDerivHidden1 * inputNode1 * (vWt10 * error0 + vWt11 * error1)\n\n sumTermH0 = vWt00 * error0 + vWt01 * error1\n sumTermH1 = vWt10 * error0 + vWt11 * error1\n\n print ' '\n print 'In Print and Trace for Backpropagation: Input to Hidden Weights'\n print ' Assuming alpha = 1'\n print ' '\n print ' The hidden node activations are:'\n print ' Hidden node 0: ', ' %.4f' % hiddenNode0, ' Hidden node 1: ', ' %.4f' % hiddenNode1\n print ' '\n print ' The output node activations are:'\n print ' Output node 0: ', ' %.3f' % outputNode0, ' Output node 1: ', ' %.3f' % outputNode1\n print ' '\n print ' The transfer function derivatives at the hidden nodes are: '\n print ' Deriv-F(0): ', ' %.3f' % transFuncDeriv0, ' Deriv-F(1): ', ' %.3f' % transFuncDeriv1\n\n print ' '\n print 'The computed values for the deltas are: '\n print ' eta * error * trFncDeriv * input * SumTerm for given H'\n print ' deltaWWt00 = ', ' %.2f' % eta, '* %.4f' % error0, ' * %.4f' % transFuncDerivHidden0, ' * %.4f' % inputNode0, ' * %.4f' % sumTermH0\n print ' deltaWWt01 = ', ' %.2f' % eta, '* %.4f' % error1, ' * %.4f' % transFuncDerivHidden1, ' * %.4f' % inputNode0, ' * %.4f' % sumTermH1\n print ' deltaWWt10 = ', ' %.2f' % eta, '* %.4f' % error0, ' * %.4f' % transFuncDerivHidden0, ' * %.4f' % inputNode1, ' * %.4f' % sumTermH0\n print ' deltaWWt11 = ', ' %.2f' % eta, '* %.4f' % error1, ' * %.4f' % transFuncDerivHidden1, ' * %.4f' % inputNode1, ' * %.4f' % sumTermH1\n print ' '\n print 'Values for the input-to-hidden connection weights:'\n print ' Old: New: eta*Delta:'\n print '[0,0]: %.4f' % wWeightArray[0, 0], ' %.4f' % newWWeightArray[0, 0], ' %.4f' % deltaWWtArray[0, 0]\n print '[0,1]: %.4f' % wWeightArray[1, 0], ' %.4f' % newWWeightArray[1, 0], ' %.4f' % deltaWWtArray[1, 0]\n print '[1,0]: %.4f' % wWeightArray[0, 1], ' %.4f' % newWWeightArray[0, 1], ' %.4f' % deltaWWtArray[0, 1]\n print '[1,1]: %.4f' % wWeightArray[1, 1], ' %.4f' % newWWeightArray[1, 1], ' %.4f' % deltaWWtArray[1, 1]\n\n\n####################################################################################################\n####################################################################################################\n#\n# Backpropagate weight changes onto the hidden-to-output connection weights\n#\n####################################################################################################\n####################################################################################################\n\n\ndef BackpropagateOutputToHidden(alpha, eta, errorList, actualAllNodesOutputList, vWeightArray):\n # The first step here applies a backpropagation-based weight change to the hidden-to-output wts v.\n # Core equation for the first part of backpropagation:\n # d(SSE)/dv(h,o) = -alpha*Error*F(1-F)*Hidden(h)\n # where:\n # -- SSE = sum of squared errors, and only the error associated with a given output node counts\n # -- v(h,o) is the connection weight v between the hidden node h and the output node o\n # -- alpha is the scaling term within the transfer function, often set to 1\n # ---- (this is included in transfFuncDeriv)\n # -- Error = Error(o) or error at the output node o; = Desired(o) - Actual(o)\n # -- F = transfer function, here using the sigmoid transfer function\n # -- Hidden(h) = the output of hidden node h.\n\n # Note that the training rate parameter is assigned in main; Greek letter \"eta,\" looks like n,\n # scales amount of change to connection weight\n\n # Unpack the errorList and the vWeightArray\n\n # We will DECREMENT the connection weight v by a small amount proportional to the derivative eqn\n # of the SSE w/r/t the weight v.\n # This means, since there is a minus sign in that derivative, that we will add a small amount.\n # (Decrementing is -, applied to a (-), which yields a positive.)\n\n # For the actual derivation of this equation with MATCHING VARIABLE NAMES (easy to understand),\n # please consult: Brain-Based Computing, by AJ Maren (under development, Jan., 2017). Chpt. X.\n # (Meaning: exact chapter is still TBD.)\n # For the latest updates, etc., please visit: www.aliannajmaren.com\n\n # Unpack the errorList and the vWeightArray\n error0 = errorList[0]\n error1 = errorList[1]\n\n vWt00 = vWeightArray[0, 0]\n vWt01 = vWeightArray[1, 0]\n vWt10 = vWeightArray[0, 1]\n vWt11 = vWeightArray[1, 1]\n\n hiddenNode0 = actualAllNodesOutputList[0]\n hiddenNode1 = actualAllNodesOutputList[1]\n outputNode0 = actualAllNodesOutputList[2]\n outputNode1 = actualAllNodesOutputList[3]\n\n transFuncDeriv0 = computeTransferFnctnDeriv(outputNode0, alpha)\n transFuncDeriv1 = computeTransferFnctnDeriv(outputNode1, alpha)\n transFuncDerivList = (transFuncDeriv0, transFuncDeriv1)\n\n # Note: the parameter 'alpha' in the transfer function shows up in the transfer function derivative\n # and so is not included explicitly in these equations\n\n # The equation for the actual dependence of the Summed Squared Error on a given hidden-to-output weight v(h,o) is:\n # partial(SSE)/partial(v(h,o)) = -alpha*E(o)*F(o)*[1-F(o)]*H(h)\n # The transfer function derivative (transFuncDeriv) returned from computeTransferFnctnDeriv is given as:\n # transFuncDeriv = alpha*NeuronOutput*(1.0 -NeuronOutput)\n # Therefore, we can write the equation for the partial(SSE)/partial(v(h,o)) as\n # partial(SSE)/partial(v(h,o)) = E(o)*transFuncDeriv*H(h)\n # The parameter alpha is included in transFuncDeriv\n\n partialSSE_w_Vwt00 = -error0 * transFuncDeriv0 * hiddenNode0\n partialSSE_w_Vwt01 = -error1 * transFuncDeriv1 * hiddenNode0\n partialSSE_w_Vwt10 = -error0 * transFuncDeriv0 * hiddenNode1\n partialSSE_w_Vwt11 = -error1 * transFuncDeriv1 * hiddenNode1\n\n deltaVWt00 = -eta * partialSSE_w_Vwt00\n deltaVWt01 = -eta * partialSSE_w_Vwt01\n deltaVWt10 = -eta * partialSSE_w_Vwt10\n deltaVWt11 = -eta * partialSSE_w_Vwt11\n deltaVWtArray = np.array([[deltaVWt00, deltaVWt10], [deltaVWt01, deltaVWt11]])\n\n vWt00 = vWt00 + deltaVWt00\n vWt01 = vWt01 + deltaVWt01\n vWt10 = vWt10 + deltaVWt10\n vWt11 = vWt11 + deltaVWt11\n\n newVWeightArray = np.array([[vWt00, vWt10], [vWt01, vWt11]])\n\n #PrintAndTraceBackpropagateOutputToHidden(alpha, eta, errorList, actualAllNodesOutputList,\n # transFuncDerivList, deltaVWtArray, vWeightArray, newVWeightArray)\n\n return newVWeightArray\n\n\n####################################################################################################\n####################################################################################################\n#\n# Backpropagate weight changes onto the bias-to-output connection weights\n#\n####################################################################################################\n####################################################################################################\n\n\ndef BackpropagateBiasOutputWeights(alpha, eta, errorList, actualAllNodesOutputList,\n biasOutputWeightArray):\n\n # The first step here applies a backpropagation-based weight change to the hidden-to-output wts v.\n # Core equation for the first part of backpropagation:\n # d(SSE)/dv(h,o) = -alpha*Error*F(1-F)*Hidden(h)\n # where:\n # -- SSE = sum of squared errors, and only the error associated with a given output node counts\n # -- v(h,o) is the connection weight v between the hidden node h and the output node o\n # -- alpha is the scaling term within the transfer function, often set to 1\n # ---- (this is included in transfFuncDeriv)\n # -- Error = Error(o) or error at the output node o; = Desired(o) - Actual(o)\n # -- F = transfer function, here using the sigmoid transfer function\n # -- Hidden(h) = the output of hidden node h.\n\n # Note that the training rate parameter is assigned in main; Greek letter \"eta,\" looks like n,\n # scales amount of change to connection weight\n\n # We will DECREMENT the connection weight biasOutput by a small amount proportional to the derivative eqn\n # of the SSE w/r/t the weight biasOutput(o).\n # This means, since there is a minus sign in that derivative, that we will add a small amount.\n # (Decrementing is -, applied to a (-), which yields a positive.)\n\n # For the actual derivation of this equation with MATCHING VARIABLE NAMES (easy to understand),\n # please consult: Brain-Based Computing, by AJ Maren (under development, Jan., 2017). Chpt. X.\n # (Meaning: exact chapter is still TBD.)\n # For the latest updates, etc., please visit: www.aliannajmaren.com\n\n # Unpack the errorList\n error0 = errorList[0]\n error1 = errorList[1]\n\n # Unpack the biasOutputWeightArray, we will only be modifying the biasOutput terms\n biasOutputWt0 = biasOutputWeightArray[0]\n biasOutputWt1 = biasOutputWeightArray[1]\n\n # Unpack the outputNodes\n outputNode0 = actualAllNodesOutputList[2]\n outputNode1 = actualAllNodesOutputList[3]\n\n # Compute the transfer function derivatives as a function of the output nodes.\n # Note: As this is being done after the call to the backpropagation on the hidden-to-output weights,\n # the transfer function derivative computed there could have been used here; the calculations are\n # being redone here only to maintain module independence\n transFuncDeriv0 = computeTransferFnctnDeriv(outputNode0, alpha)\n transFuncDeriv1 = computeTransferFnctnDeriv(outputNode1, alpha)\n # This is actually an unnecessary step; we're not passing the list back.\n transFuncDerivList = (transFuncDeriv0, transFuncDeriv1)\n\n # Note: the parameter 'alpha' in the transfer function shows up in the transfer function derivative\n # and so is not included explicitly in these equations\n\n # The equation for the actual dependence of the Summed Squared Error on a given bias-to-output\n # weight biasOutput(o) is:\n # partial(SSE)/partial(biasOutput(o)) = -alpha*E(o)*F(o)*[1-F(o)]*1, as '1' is the input from the bias.\n # The transfer function derivative (transFuncDeriv) returned from computeTransferFnctnDeriv is given as:\n # transFuncDeriv = alpha*NeuronOutput*(1.0 -NeuronOutput), as with the hidden-to-output weights.\n # Therefore, we can write the equation for the partial(SSE)/partial(biasOutput(o)) as\n # partial(SSE)/partial(biasOutput(o)) = E(o)*transFuncDeriv\n # The parameter alpha is included in transFuncDeriv\n\n\n partialSSE_w_BiasOutput0 = -error0 * transFuncDeriv0\n partialSSE_w_BiasOutput1 = -error1 * transFuncDeriv1\n\n deltaBiasOutput0 = -eta * partialSSE_w_BiasOutput0\n deltaBiasOutput1 = -eta * partialSSE_w_BiasOutput1\n\n biasOutputWt0 = biasOutputWt0 + deltaBiasOutput0\n biasOutputWt1 = biasOutputWt1 + deltaBiasOutput1\n\n # Note that only the bias weights for the output nodes have been changed.\n newBiasOutputWeightArray = np.array([biasOutputWt0, biasOutputWt1])\n\n # A new procedure to debug trace this function has not been written yet.\n # PrintAndTraceBackpropagateOutputToHidden (alpha, eta, errorList, actualAllNodesOutputList,\n # transFuncDerivList, deltaVWtArray, vWeightArray, newVWeightArray)\n\n return newBiasOutputWeightArray\n\n\n####################################################################################################\n####################################################################################################\n#\n# Backpropagate weight changes onto the input-to-hidden connection weights\n#\n####################################################################################################\n####################################################################################################\n\n\ndef BackpropagateHiddenToInput(alpha, eta, errorList, actualAllNodesOutputList, inputDataList,\n vWeightArray, wWeightArray, biasHiddenWeightArray, biasOutputWeightArray):\n # The first step here applies a backpropagation-based weight change to the input-to-hidden wts w.\n # Core equation for the second part of backpropagation:\n # d(SSE)/dw(i,h) = -eta*alpha*F(h)(1-F(h))*Input(i)*sum(v(h,o)*Error(o))\n # where:\n # -- SSE = sum of squared errors, and only the error associated with a given output node counts\n # -- w(i,h) is the connection weight w between the input node i and the hidden node h\n # -- v(h,o) is the connection weight v between the hidden node h and the output node o\n # -- alpha is the scaling term within the transfer function, often set to 1\n # ---- (this is included in transfFuncDeriv)\n # -- Error = Error(o) or error at the output node o; = Desired(o) - Actual(o)\n # -- F = transfer function, here using the sigmoid transfer function\n # ---- NOTE: in this second step, the transfer function is applied to the output of the hidden node,\n # ------ so that F = F(h)\n # -- Hidden(h) = the output of hidden node h (used in computing the derivative of the transfer function).\n # -- Input(i) = the input at node i.\n\n # Note that the training rate parameter is assigned in main; Greek letter \"eta,\" looks like n,\n # scales amount of change to connection weight\n\n # Unpack the errorList and the vWeightArray\n\n # We will DECREMENT the connection weight v by a small amount proportional to the derivative eqn\n # of the SSE w/r/t the weight w.\n # This means, since there is a minus sign in that derivative, that we will add a small amount.\n # (Decrementing is -, applied to a (-), which yields a positive.)\n\n # For the actual derivation of this equation with MATCHING VARIABLE NAMES (easy to understand),\n # please consult: Brain-Based Computing, by AJ Maren (under development, Jan., 2017). Chpt. X.\n # (Meaning: exact chapter is still TBD.)\n # For the latest updates, etc., please visit: www.aliannajmaren.com\n\n # Note that the training rate parameter is assigned in main; Greek letter \"eta,\" looks like n,\n # scales amount of change to connection weight\n\n # Unpack the errorList and the vWeightArray\n error0 = errorList[0]\n error1 = errorList[1]\n\n vWt00 = vWeightArray[0, 0]\n vWt01 = vWeightArray[1, 0]\n vWt10 = vWeightArray[0, 1]\n vWt11 = vWeightArray[1, 1]\n\n wWt00 = wWeightArray[0, 0]\n wWt01 = wWeightArray[1, 0]\n wWt10 = wWeightArray[0, 1]\n wWt11 = wWeightArray[1, 1]\n\n inputNode0 = inputDataList[0]\n inputNode1 = inputDataList[1]\n hiddenNode0 = actualAllNodesOutputList[0]\n hiddenNode1 = actualAllNodesOutputList[1]\n outputNode0 = actualAllNodesOutputList[2]\n outputNode1 = actualAllNodesOutputList[3]\n\n # For the second step in backpropagation (computing deltas on the input-to-hidden weights)\n # we need the transfer function derivative is applied to the output at the hidden node\n transFuncDerivHidden0 = computeTransferFnctnDeriv(hiddenNode0, alpha)\n transFuncDerivHidden1 = computeTransferFnctnDeriv(hiddenNode1, alpha)\n transFuncDerivHiddenList = (transFuncDerivHidden0, transFuncDerivHidden1)\n\n # We also need the transfer function derivative applied to the output at the output node\n transFuncDerivOutput0 = computeTransferFnctnDeriv(outputNode0, alpha)\n transFuncDerivOutput1 = computeTransferFnctnDeriv(outputNode1, alpha)\n transFuncDerivOutputList = (transFuncDerivOutput0, transFuncDerivOutput1)\n\n errorTimesTransDOutput0 = error0 * transFuncDerivOutput0\n errorTimesTransDOutput1 = error1 * transFuncDerivOutput1\n\n # Note: the parameter 'alpha' in the transfer function shows up in the transfer function derivative\n # and so is not included explicitly in these equations\n partialSSE_w_Wwt00 = -transFuncDerivHidden0 * inputNode0 * (\n vWt00 * errorTimesTransDOutput0 + vWt01 * errorTimesTransDOutput1)\n partialSSE_w_Wwt01 = -transFuncDerivHidden1 * inputNode0 * (\n vWt10 * errorTimesTransDOutput0 + vWt11 * errorTimesTransDOutput1)\n partialSSE_w_Wwt10 = -transFuncDerivHidden0 * inputNode1 * (\n vWt00 * errorTimesTransDOutput0 + vWt01 * errorTimesTransDOutput1)\n partialSSE_w_Wwt11 = -transFuncDerivHidden1 * inputNode1 * (\n vWt10 * errorTimesTransDOutput0 + vWt11 * errorTimesTransDOutput1)\n\n deltaWWt00 = -eta * partialSSE_w_Wwt00\n deltaWWt01 = -eta * partialSSE_w_Wwt01\n deltaWWt10 = -eta * partialSSE_w_Wwt10\n deltaWWt11 = -eta * partialSSE_w_Wwt11\n deltaWWtArray = np.array([[deltaWWt00, deltaWWt10], [deltaWWt01, deltaWWt11]])\n\n wWt00 = wWt00 + deltaWWt00\n wWt01 = wWt01 + deltaWWt01\n wWt10 = wWt10 + deltaWWt10\n wWt11 = wWt11 + deltaWWt11\n\n newWWeightArray = np.array([[wWt00, wWt10], [wWt01, wWt11]])\n\n # PrintAndTraceBackpropagateHiddenToInput (alpha, eta, inputDataList, errorList, actualAllNodesOutputList,\n # transFuncDerivHiddenList, transFuncDerivOutputList, deltaWWtArray, vWeightArray, wWeightArray, newWWeightArray, biasWeightArray)\n\n return newWWeightArray\n\n\n####################################################################################################\n####################################################################################################\n#\n# Backpropagate weight changes onto the bias-to-hidden connection weights\n#\n####################################################################################################\n####################################################################################################\n\n\ndef BackpropagateBiasHiddenWeights(alpha, eta, errorList, actualAllNodesOutputList, vWeightArray,\n biasHiddenWeightArray, biasOutputWeightArray):\n # The first step here applies a backpropagation-based weight change to the hidden-to-output wts v.\n # Core equation for the first part of backpropagation:\n # d(SSE)/dv(h,o) = -alpha*Error*F(1-F)*Hidden(h)\n # where:\n # -- SSE = sum of squared errors, and only the error associated with a given output node counts\n # -- v(h,o) is the connection weight v between the hidden node h and the output node o\n # -- alpha is the scaling term within the transfer function, often set to 1\n # ---- (this is included in transfFuncDeriv)\n # -- Error = Error(o) or error at the output node o; = Desired(o) - Actual(o)\n # -- F = transfer function, here using the sigmoid transfer function\n # -- Hidden(h) = the output of hidden node h.\n\n # Note that the training rate parameter is assigned in main; Greek letter \"eta,\" looks like n,\n # scales amount of change to connection weight\n\n # We will DECREMENT the connection weight biasOutput by a small amount proportional to the derivative eqn\n # of the SSE w/r/t the weight biasOutput(o).\n # This means, since there is a minus sign in that derivative, that we will add a small amount.\n # (Decrementing is -, applied to a (-), which yields a positive.)\n\n # For the actual derivation of this equation with MATCHING VARIABLE NAMES (easy to understand),\n # please consult: Brain-Based Computing, by AJ Maren (under development, Jan., 2017). Chpt. X.\n # (Meaning: exact chapter is still TBD.)\n # For the latest updates, etc., please visit: www.aliannajmaren.com\n\n # Unpack the errorList and vWeightArray\n error0 = errorList[0]\n error1 = errorList[1]\n\n vWt00 = vWeightArray[0, 0]\n vWt01 = vWeightArray[1, 0]\n vWt10 = vWeightArray[0, 1]\n vWt11 = vWeightArray[1, 1]\n\n # Unpack the biasWeightArray, we will only be modifying the biasOutput terms, but need to have\n # all the bias weights for when we redefine the biasWeightArray\n biasHiddenWt0 = biasHiddenWeightArray[0]\n biasHiddenWt1 = biasHiddenWeightArray[1]\n biasOutputWt0 = biasOutputWeightArray[0]\n biasOutputWt1 = biasOutputWeightArray[1]\n\n # Unpack the outputNodes\n hiddenNode0 = actualAllNodesOutputList[0]\n hiddenNode1 = actualAllNodesOutputList[1]\n outputNode0 = actualAllNodesOutputList[2]\n outputNode1 = actualAllNodesOutputList[3]\n\n # Compute the transfer function derivatives as a function of the output nodes.\n # Note: As this is being done after the call to the backpropagation on the hidden-to-output weights,\n # the transfer function derivative computed there could have been used here; the calculations are\n # being redone here only to maintain module independence\n transFuncDerivOutput0 = computeTransferFnctnDeriv(outputNode0, alpha)\n transFuncDerivOutput1 = computeTransferFnctnDeriv(outputNode1, alpha)\n transFuncDerivHidden0 = computeTransferFnctnDeriv(hiddenNode0, alpha)\n transFuncDerivHidden1 = computeTransferFnctnDeriv(hiddenNode1, alpha)\n\n # This list will be used only if we call a print-and-trace debug function.\n transFuncDerivOutputList = (transFuncDerivOutput0, transFuncDerivOutput1)\n\n # Note: the parameter 'alpha' in the transfer function shows up in the transfer function derivative\n # and so is not included explicitly in these equations\n\n\n # ===>>> AJM needs to double-check these equations in the comments area\n # ===>>> The code should be fine.\n # The equation for the actual dependence of the Summed Squared Error on a given bias-to-output\n # weight biasOutput(o) is:\n # partial(SSE)/partial(biasOutput(o)) = -alpha*E(o)*F(o)*[1-F(o)]*1, as '1' is the input from the bias.\n # The transfer function derivative (transFuncDeriv) returned from computeTransferFnctnDeriv is given as:\n # transFuncDeriv = alpha*NeuronOutput*(1.0 -NeuronOutput), as with the hidden-to-output weights.\n # Therefore, we can write the equation for the partial(SSE)/partial(biasOutput(o)) as\n # partial(SSE)/partial(biasOutput(o)) = E(o)*transFuncDeriv\n # The parameter alpha is included in transFuncDeriv\n\n errorTimesTransDOutput0 = error0 * transFuncDerivOutput0\n errorTimesTransDOutput1 = error1 * transFuncDerivOutput1\n\n partialSSE_w_BiasHidden0 = -transFuncDerivHidden0 * (errorTimesTransDOutput0 * vWt00 +\n errorTimesTransDOutput1 * vWt01)\n partialSSE_w_BiasHidden1 = -transFuncDerivHidden1 * (errorTimesTransDOutput0 * vWt10 +\n errorTimesTransDOutput1 * vWt11)\n\n deltaBiasHidden0 = -eta * partialSSE_w_BiasHidden0\n deltaBiasHidden1 = -eta * partialSSE_w_BiasHidden1\n\n biasHiddenWt0 = biasHiddenWt0 + deltaBiasHidden0\n biasHiddenWt1 = biasHiddenWt1 + deltaBiasHidden1\n\n # Note that only the bias weights for the hidden nodes have been changed.\n newBiasHiddenWeightArray = np.array([biasHiddenWt0, biasHiddenWt1])\n\n # A new procedure to debug trace this function has not been written yet.\n # PrintAndTraceBackpropagateOutputToHidden (alpha, eta, errorList, actualAllNodesOutputList,\n # transFuncDerivList, deltaVWtArray, vWeightArray, newVWeightArray)\n\n return newBiasHiddenWeightArray\n\n\n####################################################################################################\n# **************************************************************************************************#\n####################################################################################################\nif __name__ == '__main__':\n\n import numpy as np\n\n # Parameter definitions, to be replaced with user inputs\n alpha = 1.0 # parameter governing steepness of sigmoid transfer function\n summedInput = 1\n maxNumIterations = 5 # You can adjust this parameter; 10,000 typically gives good results when training.\n eta = 0.5 # training rate\n\n # Establish some parameters just before we start training\n epsilon = 0.2 # epsilon determines when we are done training;\n # for each presentation of a training data set, we get a new value for the summed squared error (SSE)\n # and we will terminate the run when any ONE of these SSEs is < epsilon;\n # Note that this is a very crude stopping criterion, we can refine it in later versions.\n # must b\n iteration = 0 # This counts the number of iterations that we've made through the training cycle.\n SSE_InitialTotal = 0.0 # We initially set the SSE to be zero before any training pass; we accumulate inputs\n # into the SSE once we have a set of weights, and push the input data through the network,\n # generating a set of outputs.\n # We compare the generated outputs (actuals) with the desired, obtain errors, square them,\n # and sum across all the outputs. This gives our SSE for that particular data set, for that\n # particular training pass.\n # If the SSE is low enough (< epsilon), we stop training.\n\n # Set default values for debug parameters\n # We are setting the debug parameters to be \"Off\" (debugxxxOff = True)\n debugCallInitializeOff = True\n debugInitializeOff = True\n\n # Right now, for simplicity, we're going to hard-code the numbers of layers that we have in our\n # multilayer Perceptron (MLP) neural network.\n # We will have an input layer (I), an output layer (O), and a single hidden layer (H).\n\n # Obtain the array sizes (arraySizeList) by calling the appropriate function\n arraySizeList = obtainNeuralNetworkSizeSpecs()\n\n # Unpack the list; ascribe the various elements of the list to the sizes of different network layers\n inputArrayLength = arraySizeList[0]\n hiddenArrayLength = arraySizeList[1]\n outputArrayLength = arraySizeList[2]\n\n # In addition to connection weights, we also use bias weights:\n # - one bias term for each of the hidden nodes\n # - one bias term for each of the output nodes\n # This means that a 1-D array of bias weights for the hidden nodes will have the same dimension as\n # the hidden array length, and\n # also a 1-D array of bias weights for the output nodes will have the same dimension as\n # the output array length.\n biasHiddenWeightArraySize = hiddenArrayLength\n biasOutputWeightArraySize = outputArrayLength\n\n ####################################################################################################\n # Initialize the weight arrays for two sets of weights; w: input-to-hidden, and v: hidden-to-output\n ####################################################################################################\n\n #\n # The wWeightArray is for Input-to-Hidden\n # The vWeightArray is for Hidden-to-Output\n # The wWeightArray is for Input-to-Hidden\n # The vWeightArray is for Hidden-to-Output\n\n # We have a single function to initialize weights in a connection weight matrix (2-D array).\n # This function needs to know the sizes (lengths) of the lower and the upper sets of nodes.\n # These form the [row, column] size specifications for the returned weight matrices (2-D arrays).\n # We will store these sizes in each of two different lists.\n\n # Specify the sizes for the input-to-hidden connection weight matrix (2-D array)\n wWeightArraySizeList = (inputArrayLength, hiddenArrayLength)\n # print wWeightArraySizeList\n\n # Specify the sizes for the hidden-to-output connection weight matrix (2-D array)\n vWeightArraySizeList = (hiddenArrayLength, outputArrayLength)\n # print vWeightArraySizeList\n\n # Obtain the actual (randomly-initialized) values for the input-to-hidden connection weight matrix.\n wWeightArray = initializeWeightArray(wWeightArraySizeList, debugInitializeOff)\n\n # Obtain the actual (randomly-initialized) values for the hidden-to-output connection weight matrix.\n vWeightArray = initializeWeightArray(vWeightArraySizeList, debugInitializeOff)\n\n # Now, we similarly need to obtain randomly-initialized values for the two sets of bias weights.\n # Each set of bias weights is stored in its respective 1-D array\n # Recall that we have previously initialized the SIZE for each of these 1-D arrays.\n biasHiddenWeightArray = initializeBiasWeightArray(biasHiddenWeightArraySize)\n biasOutputWeightArray = initializeBiasWeightArray(biasOutputWeightArraySize)\n\n initialWWeightArray = wWeightArray[:]\n initialVWeightArray = vWeightArray[:]\n initialBiasHiddenWeightArray = biasHiddenWeightArray[:]\n initialBiasOutputWeightArray = biasOutputWeightArray[:]\n\n print\n print 'The initial weights for this neural network are:'\n print ' Input-to-Hidden Hidden-to-Output'\n print ' w(0,0) = %.4f w(1,0) = %.4f v(0,0) = %.4f v(1,0) = %.4f' % (initialWWeightArray[0, 0],\n initialWWeightArray[0, 1],\n initialVWeightArray[0, 0],\n initialVWeightArray[0, 1])\n print ' w(0,1) = %.4f w(1,1) = %.4f v(0,1) = %.4f v(1,1) = %.4f' % (initialWWeightArray[1, 0],\n initialWWeightArray[1, 1],\n initialVWeightArray[1, 0],\n initialVWeightArray[1, 1])\n print ' '\n print ' Bias at Hidden Layer Bias at Output Layer'\n print ' b(hidden,0) = %.4f b(output,0) = %.4f' % (biasHiddenWeightArray[0],\n biasOutputWeightArray[0])\n print ' b(hidden,1) = %.4f b(output,1) = %.4f' % (biasHiddenWeightArray[1],\n biasOutputWeightArray[1])\n\n ####################################################################################################\n # Next step - Get an initial value for the Total Summed Squared Error (Total_SSE)\n # The function will return an array of SSE values, SSE_Array[0] ... SSE_Array[3] are the initial SSEs\n # for training sets 0..3; SSE_Array[4] is the sum of the SSEs.\n ####################################################################################################\n\n\n # Initialize an array of SSE values\n # The first four SSE values are the SSE's for specific input/output pairs;\n # the fifth is the sum of all the SSE's.\n SSE_InitialArray = [0, 0, 0, 0, 0]\n\n # Before starting the training run, compute the initial SSE Total\n # (sum across SSEs for each training data set)\n debugSSE_InitialComputationOff = True\n\n SSE_InitialArray = computeSSE_Values(alpha, SSE_InitialArray, wWeightArray, vWeightArray,\n biasHiddenWeightArray, biasOutputWeightArray, debugSSE_InitialComputationOff)\n\n # Start the SSE_Array at the same values as the Initial SSE Array\n SSE_Array = SSE_InitialArray[:]\n SSE_InitialTotal = SSE_Array[4]\n\n # Optionally, print a summary of the initial SSE Total (sum across SSEs for each training data set)\n # and the specific SSE values\n # Set a local debug print parameter\n debugSSE_InitialComputationReportOff = True\n\n if not debugSSE_InitialComputationReportOff:\n print ' '\n print 'In main, SSE computations completed, Total of all SSEs = %.4f' % SSE_Array[4]\n print ' For input nodes (0,0), SSE_Array[0] = %.4f' % SSE_Array[0]\n print ' For input nodes (0,1), SSE_Array[1] = %.4f' % SSE_Array[1]\n print ' For input nodes (1,0), SSE_Array[2] = %.4f' % SSE_Array[2]\n print ' For input nodes (1,1), SSE_Array[3] = %.4f' % SSE_Array[3]\n\n print ' '\n print 'About to enter the while loop for ', maxNumIterations, ' iterations'\n print ' '\n\n while iteration < maxNumIterations:\n\n ####################################################################################################\n # Next step - Obtain a single set of input values for the X-OR problem; two integers - can be 0 or 1\n ####################################################################################################\n\n # Randomly select one of four training sets; the inputs will be randomly assigned to 0 or 1\n trainingDataList = obtainRandomXORTrainingValues()\n input0 = trainingDataList[0]\n input1 = trainingDataList[1]\n desiredOutput0 = trainingDataList[2]\n desiredOutput1 = trainingDataList[3]\n setNumber = trainingDataList[4] # obtain the number (0 ... 3) of the training data set.\n print ' '\n print 'Iteration number ', iteration\n print ' '\n print 'Randomly selected training data set number ', trainingDataList[4]\n print 'The inputs and desired outputs for the X-OR problem from this data set are:'\n print ' Input0 = ', input0, ' Input1 = ', input1\n print ' Desired Output0 = ', desiredOutput0, ' Desired Output1 = ', desiredOutput1\n print ' '\n\n ####################################################################################################\n # Compute a single feed-forward pass\n ####################################################################################################\n\n # Initialize the error list\n errorList = (0, 0)\n\n # Initialize the actualOutput list\n # Remember, we've hard-coded the number of hidden nodes and output nodes in this version;\n # numHiddenNodes = 2; numOutputNodes = 2.\n # We want to see the ACTUAL VALUES (\"activations\") of both the hidden AND the output nodes;\n # this is just to satisfy our own interest.\n # In just a few lines down, we will use the function \"ComputeSingleFeedforwardPass\" to get us all\n # of those activations.\n actualAllNodesOutputList = (0, 0, 0, 0)\n\n # Create the inputData list\n inputDataList = (input0, input1)\n\n # Compute a single feed-forward pass and obtain the Actual Outputs\n debugComputeSingleFeedforwardPassOff = True\n actualAllNodesOutputList = ComputeSingleFeedforwardPass(alpha, inputDataList,\n wWeightArray, vWeightArray, biasHiddenWeightArray,\n biasOutputWeightArray,\n debugComputeSingleFeedforwardPassOff)\n\n # Assign the hidden and output values to specific different variables\n actualHiddenOutput0 = actualAllNodesOutputList[0]\n actualHiddenOutput1 = actualAllNodesOutputList[1]\n actualOutput0 = actualAllNodesOutputList[2]\n actualOutput1 = actualAllNodesOutputList[3]\n\n # Determine the error between actual and desired outputs\n\n error0 = desiredOutput0 - actualOutput0\n error1 = desiredOutput1 - actualOutput1\n errorList = (error0, error1)\n\n # Compute the Summed Squared Error, or SSE\n SSE0 = error0 ** 2\n SSE1 = error1 ** 2\n SSEInitial = SSE0 + SSE1\n\n debugMainComputeForwardPassOutputsOff = True\n\n # Debug print: the actual outputs from the two output neurons\n if not debugMainComputeForwardPassOutputsOff:\n print ' '\n print 'In main; have just completed a feedfoward pass with training set inputs', input0, input1\n print ' The activations (actual outputs) for the two hidden neurons are:'\n print ' actualHiddenOutput0 = %.4f' % actualHiddenOutput0\n print ' actualHiddenOutput1 = %.4f' % actualHiddenOutput1\n print ' The activations (actual outputs) for the two output neurons are:'\n print ' actualOutput0 = %.4f' % actualOutput0\n print ' actualOutput1 = %.4f' % actualOutput1\n print ' Initial SSE (before backpropagation) = %.6f' % SSEInitial\n print ' Corresponding SSE (from initial SSE determination) = %.6f' % SSE_Array[setNumber]\n\n\n # Assign the SSE to the SSE for the appropriate training set\n SSE_Array[setNumber] = SSEInitial\n\n # Compute the new sum of SSEs (across all the different training sets)\n # ... this will be different because we've changed one of the SSE's\n newSSE_Total = SSE_Array[0] + SSE_Array[1] + SSE_Array[2] + SSE_Array[3]\n print ' For node 0: Desired Output = ', desiredOutput0, ' New Output = %.4f' % actualOutput0\n print ' For node 1: Desired Output = ', desiredOutput1, ' New Output = %.4f' % actualOutput1\n print ' Error(0) = %.4f, Error(1) = %.4f' % (error0, error1)\n print ' Squared Error (0) = %.4f, Squared Error(1) = %.4f' % (SSE0, SSE1)\n # Assign the new SSE to the final place in the SSE array\n SSE_Array[4] = newSSE_Total\n print ' '\n print ' The sum of these squared errors (SSE) for training set ', trainingDataList[\n 4], ' is %.4f' % newSSE_Total\n\n iteration = iteration + 1\n\n if newSSE_Total < epsilon:\n break\n print ' '\n print 'Out of while loop after ', maxNumIterations, ' iterations'"} {"blob_id": "dc8852ec69ad89119cb1012d086dabf910b969a0", "repo_name": "lukealbao/sicp", "path": "/Chapter_1/ex-1.12.py", "length_bytes": 1252, "score": 3.953125, "int_score": 4, "content": "#! /usr/bin/env python\n\n'''\nExercise: Create a recursive procedure for calculating Pascal's Triangle.\n\nI was able to create the function to calculate the value of a single cell, given its\nline and cell number, but creating the recursive call to concatenate these values into\na list was proving tricky in Scheme. Here is an implementation of the procedure in Python.\n\nFor fun, the third function will print the entire triangle given the number of rows.\nNot sure if there is a more idiomatic way of pulling off those ranges, since their values\nare integers to be calculated and not indexes.\n\n// Scheme Version of calculate_one //\n(define (calculate_one line place)\n (if (or (= place line)\n (= place 1))\n 1\n (+ (calculate_one (- line 1) place)\n (calculate_one (- line 1) (- place 1)))))\n\n'''\nimport sys\n\ndef calculate_one(line, place):\n if place == 1 or line == place:\n return 1\n else:\n return calculate_one(line - 1, place - 1) + calculate_one(line - 1, place)\n\ndef write_line(line):\n return [calculate_one(line, i) for i in range(1, line + 1)]\n\ndef write_triangle(lines):\n for i in range(1, lines +1):\n print write_line(i)\n\nif __name__ == '__main__':\n write_triangle(int(sys.argv[1]))\n"} {"blob_id": "d92b8e8d3690270997e0c672bd82d4605ac6596d", "repo_name": "gilovi/python-ex3", "path": "/GoogleRiddle.py", "length_bytes": 2335, "score": 3.796875, "int_score": 4, "content": "__author__ = 'PythonTeam 2015'\nfrom decimal import *\nfrom math import sqrt\nfrom random import randint\n\n\"\"\"\nThis file contains deceleration of methods that should assist solving to\nGoogle BillBoard Riddle.\n\nWritten for Python Programming Workshop (67557) at HUJI, 2015\n\"\"\"\n\ndef eularsNumber(n, p):\n \"\"\"\n Returns eular's number using evaluation of (1 + 1 / n)^n, where n is the\n given param, and p is the precision - that is p is the number of digits of\n e to return.\n The number should be returned as a string which contains only digits.\n \"\"\"\n getcontext().prec = p\n return str((1+1/Decimal(n))**n).replace('.','')\n\n\ndef prime_1(n):\n \"\"\"\n Returns True iff n is prime.\n This should be a simple algorithm to find if a number is prime.\n from wikipedia.\n \"\"\"\n if n <= 3:\n return n > 1\n if n%2 == 0 or n%3 == 0:\n return False\n for i in range(5, int(sqrt(n))+1, 6):\n if n % i == 0 or n % (i + 2) == 0:\n return False\n return True\n\n\n\ndef prime_2(s, e):\n \"\"\"\n Returns a list(!) of all primes between 's'(including) and 'e'(excluding)\n This method should be written using at most 2(!) lines of code\n \"\"\"\n return filter(prime_1,range(s,e))\n\n\ndef prime_3(n, k):\n \"\"\"\n Returns True iff n is a prime with probability of less than 4^(-k) for a mistake.\n This method should implement the probabilistic algorithm for primality testing\n as suggested by G. Miller and later modified by M. Rabin.\n \"\"\"\n (d,s) = factor (n-1)\n for i in xrange(k):\n a = randint(2,n-2)\n x = mod_pow(a,d,n)\n\n if not ( x == 1 or x == n - 1):\n for j in xrange(s-1):\n x = mod_pow(x,2,n)\n if x == 1 :\n return False\n if x == n-1:\n break\n else:\n return False\n return True\n\ndef factor(n):\n i = 0\n while (n)%2 == 0:\n n /= 2\n i += 1\n return [n,i]\n\n\ndef mod_pow(a, d, n):\n\n result = 1\n a = a % n\n while d > 0:\n if d % 2 == 1:\n result = (result * a) % n\n d >>= 1\n a = (a * a) % n\n return result\n\t# getcontext().prec = 1001\n\t# e = eularsNumber(10**Decimal(1000),1001)\n\t# ans = [p for p in map(long,[e[i:i+10] for i in range (990)]) if prime_3(p,2)][0]"} {"blob_id": "e86266d6665de81ce4e31d68280b738b2de6bd14", "repo_name": "Yobretaw/AlgorithmProblems", "path": "/EPI/Python/Greedy/18_10_search_pair_sum_in_abs_sorted_array.py", "length_bytes": 2934, "score": 3.890625, "int_score": 4, "content": "import sys\nimport math\n\n\"\"\"\n Design an algorithm that takes as abs-sorted array A and a number K, and\n returns a pair of indices of elements in A that sum up to K.\n\n An abs-sorted array is an array of numbers in which |A[i]| <= |A[j]| whenever\n i < j.\n\"\"\"\n# This algorithm takes O(n) time and O(n) space.\ndef search_pair_sum(A, k):\n n = len(A)\n if n < 2:\n return (-1, -1)\n\n m = { val: i for i, val in enumerate(A) }\n\n for i, v in enumerate(A):\n if k - v in m and m[k - v] != i:\n return (min(i, m[k-v]), max(i, m[k-v]))\n\n return (-1, -1)\n\n\"\"\"\n If the array is sorted in conventional sense, then there is an algorithm that\n solves this problem in O(n) time and O(1) space.\n\n In this instance, we consider three cases: \n\n (1) Both the numbers in the pair are negative. \n (2) Both the numbers in the pair are positive. \n (3) One is negative and the other is positive. \n\n For Cases (1) and (2), we can run the above algorithm separately by just\n limiting ourselves to either positive or negative numbers. For Case (3),\n we can use the same approach where we have on index for positive numbers,\n one index for negative numbers, and they both start from the highest possible\n index and then go down.\n\"\"\"\ndef search_pair_sum2(A, k):\n n = len(A)\n if n < 2:\n return (-1, -1)\n\n # first we handle the case where both numbers in the pair are positive\n if k > 0:\n i, j = 0, n - 1\n while i < j:\n while i < j and A[i] < 0:\n i += 1\n while i < j and A[j] < 0:\n j -= 1\n\n if i >= j:\n break\n\n s = A[i] + A[j]\n if s == k:\n return (i, j)\n elif s < k:\n i += 1\n else:\n j -= 1\n\n # next we handle the case where both numbers in the pair are negative\n if k < 0:\n i, j = 0, n - 1\n while i < j:\n while i < j and A[i] > 0:\n i += 1\n while i < j and A[j] > 0:\n j -= 1\n\n if i >= j:\n break\n\n s = A[i] + A[j]\n if s == k:\n return (i, j)\n elif s < k:\n j -= 1\n else:\n i += 1\n\n # next we handle the case where one is negative and one is positive\n i, j = n - 1, n - 1\n while i >= 0 and j >= 0:\n while i >= 0 and A[i] < 0:\n i -= 1\n while j >= 0 and A[j] > 0:\n j -= 1\n\n if i < 0 or j < 0:\n break\n\n s = A[i] + A[j]\n if s == k:\n return (min(i, j), max(i, j))\n elif s > k:\n i -= 1\n else:\n j -= 1\n\n return (-1, -1)\n\nif __name__ == '__main__':\n A = [-49, 75, 103, -147, 164, -197, -238, 314, 348, -422]\n k = 167\n print search_pair_sum(A, k)\n print search_pair_sum2(A, k)\n"} {"blob_id": "447c5574e40b4351eaef274e9d6573f1c23d778e", "repo_name": "achyudh/leetcode-solutions", "path": "/python/wordSearch.py", "length_bytes": 1398, "score": 3.65625, "int_score": 4, "content": "class Solution:\n def validCell(self, currentY, currentX, wordIndex) -> bool:\n return currentX >= 0 and currentY >= 0 \\\n and currentY < len(self.board) \\\n and currentX < len(self.board[0]) \\\n and self.board[currentY][currentX] == self.word[wordIndex]\n \n def search(self, currentY, currentX, wordIndex) -> bool: \n if wordIndex == len(self.word):\n return True\n \n result = False\n if self.validCell(currentY, currentX, wordIndex):\n currentChar = self.board[currentY][currentX]\n self.board[currentY][currentX] = '0'\n \n result = self.search(currentY + 1, currentX, wordIndex + 1) \\\n or self.search(currentY - 1, currentX, wordIndex + 1) \\\n or self.search(currentY, currentX + 1, wordIndex + 1) \\\n or self.search(currentY, currentX - 1, wordIndex + 1)\n \n self.board[currentY][currentX] = currentChar\n \n return result\n \n def exist(self, board: List[List[str]], word: str) -> bool:\n self.word = word\n self.board = board\n \n for startY in range(len(board)):\n for startX in range(len(board[0])):\n self.visited = set()\n if self.search(startY, startX, 0):\n return True\n \n return False\n"} {"blob_id": "10419eafad6202724a7b262047cea4f02c4b09ae", "repo_name": "VladislavPetrusenko/Python-codes", "path": "/Arithmetic Analysis/newton_method.py", "length_bytes": 709, "score": 3.703125, "int_score": 4, "content": "from typing import Callable\r\n\r\nRealFunc = Callable[[float], float]\r\n\r\ndef newton(function: RealFunc, derivative: RealFunc, starting_int: int) -> float:\r\n prev_guess = float(starting_int)\r\n while True:\r\n try:\r\n next_guess = prev_guess - function(prev_guess) / derivative(prev_guess)\r\n except ZeroDivisionError:\r\n raise ZeroDivisionError(\"Could not find root\") from None\r\n if abs(prev_guess - next_guess) < 10 ** -5:\r\n return next_guess\r\n prev_guess = next_guess\r\n\r\ndef f(x: float) -> float:\r\n return (x ** 3) - (2 * x) - 5\r\n\r\ndef f1(x: float) -> float:\r\n return 3 * (x ** 2) - 2\r\n\r\nif __name__ == \"__main__\":\r\n print(newton(f, f1, 3))"} {"blob_id": "81d431e4511bb6b97d38f2108aaa37bcba6174fd", "repo_name": "kaushikb258/PyNeuNetOCR", "path": "/PyNeuNet.py", "length_bytes": 3824, "score": 3.8125, "int_score": 4, "content": "\"\"\"\n-----------------------------------------\n NEURAL NETWORK WITH BACKPROPAGATION\n AUTHOR: KAUSHIK BALAKRISHNAN, PHD\n kaushikb258@gmail.com\n-----------------------------------------\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport random\nimport inputdata\nfrom inputdata import *\nfrom userinputs import *\nimport NeuNet\nfrom NeuNet import *\nimport sys\nimport matplotlib.pyplot as plt\nimport time\n#------------------------------------------------\n\nnhidden, max_neurons, beta, niters, ninputs, noutputs, update_procedure, num_neurons = set_inputs()\n\nprint \"-------------------------------------------\"\nprint \"nhidden: \", nhidden\nprint \"max_neurons: \", max_neurons\nprint \"beta: \", beta\nprint \"niters: \", niters\nprint \"ninputs: \", ninputs\nprint \"noutputs: \", noutputs\nprint \"update_procedure: \", update_procedure\nprint \"num_neurons: \", num_neurons\nprint \"-------------------------------------------\"\n\n# read raw data\nntrain, ntest, train_in, train_out, test_in, test_out = read_raw_data()\n\nprint \"ntrain: \", ntrain\nprint \"ntest: \", ntest\nsys.stdout.flush()\ntime.sleep(5)\n\n# weights: w[j,i,k] \n# weight from k-th neuron in level j-1 to i-th neuron in level j\n\nw = np.zeros((nhidden+2,max_neurons,max_neurons),dtype=np.float64)\nwnew = np.zeros((nhidden+2,max_neurons,max_neurons),dtype=np.float64)\ndw = np.zeros((nhidden+2,max_neurons,max_neurons),dtype=np.float64)\ndwold = np.zeros((nhidden+2,max_neurons,max_neurons),dtype=np.float64)\n\nbias = np.zeros((nhidden+2,max_neurons),dtype=np.float64)\nbiasnew = np.zeros((nhidden+2,max_neurons),dtype=np.float64)\ndbias = np.zeros((nhidden+2,max_neurons),dtype=np.float64)\ndbiasold = np.zeros((nhidden+2,max_neurons),dtype=np.float64)\n\nact = np.zeros((nhidden+2,max_neurons),dtype=np.float64)\ndelta = np.zeros((nhidden+2,max_neurons),dtype=np.float64)\nerror = np.zeros((niters,noutputs),dtype=np.float64)\n\n# initialize weights\nprint \"initializing weights \"\nsys.stdout.flush()\nw, bias = initialize_weights(max_neurons,nhidden,num_neurons)\n\n#---------------------------------------------------------------\nprint \"starting the training \"\nsys.stdout.flush()\n# start the neural net computations (niters iterations)\nfor it in range(niters):\n \n print \"iteration: \", it \n sys.stdout.flush() \n \n for ii in range(ntrain):\n act = np.zeros((nhidden+2,max_neurons),dtype=np.float64) \n act = forward_propagation(max_neurons,nhidden,num_neurons,train_in[ii,:],w,bias)\n \n# compute error for each neuron\n delta = np.zeros((nhidden+2,max_neurons),dtype=np.float64)\n delta = compute_error(max_neurons,nhidden,num_neurons,train_out[ii,:],act,w)\n\n# adjust weights\n w, bias = adjust_weights(update_procedure,max_neurons,nhidden,num_neurons,beta,act,w,bias,delta)\n \n for i in range(noutputs):\n error[it,i] = error[it,i] + ( train_out[ii,i] - act[nhidden+1,i] )**2.0\n\n#------------------------------- \nerror[:,:] = np.sqrt(error[:,:]/float(ntrain))\n\n# outout error to file\n\nerr1 = np.zeros((error.shape[0],error.shape[1]+1),dtype=np.float64)\nb = np.array([i for i in range(1,error.shape[0]+1)])\nb = b.astype(np.float64)\nerr1 = np.insert(error, 0, b, axis=1)\nnp.savetxt('error_out', err1, delimiter=',')\n\n# Plot error\nplt.plot(err1[:,0],np.log10(err1[:,1]))\nplt.xlabel('iteration #')\nplt.ylabel('log10 error')\nplt.show()\n\n#-------------------------------\nprint \"-------------------------\"\n\n# Apply on test set\n\ncorrect_pred = 0 \n\nfor ii in range(ntest):\n act = np.zeros((nhidden+2,max_neurons),dtype=np.float64) \n act = forward_propagation(max_neurons,nhidden,num_neurons,test_in[ii,:],w,bias) \n output = act[nhidden+1,:noutputs] \n k = np.argmax(output) \n if (test_out[ii,k]==1):\n correct_pred += 1\n \nprint \"# of correct predictions: \", correct_pred \nprint \"# on test sets: \", ntest \n \nprint \"-------------------------\"\n#-------------------------------"} {"blob_id": "6c7fb46e69e0e9890a0632bfcf70274bd023ced7", "repo_name": "TobynC/Regression", "path": "/project1.py", "length_bytes": 7938, "score": 3.625, "int_score": 4, "content": "import numpy as np\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn import preprocessing\nimport matplotlib.pyplot as plt\nimport os\n\n\ndef main():\n clear_terminal()\n #read in file\n data, row_count, col_count = load_data()\n \n #set up features and labels\n x_features = data[:, 0:col_count - 1]\n y_labels = data[:, col_count - 1]\n\n #remove id's\n x_features = np.hstack(\n (x_features[:, [1]], x_features[:, [2]], x_features[:, [3]], x_features[:, [4]], x_features[:, [5]], x_features[:, [6]])\n )\n\n #data transforms\n x_features[:,1] = np.sqrt(x_features[:,1])\n x_features[:,2] = np.log10(x_features[:,2])\n\n #create linear regression object and fit it against all features\n reg = LinearRegression()\n reg = reg.fit(x_features, y_labels)\n\n y_predicted = reg.predict(x_features)\n sse = reg._residues\n \n print('All features coefficients:')\n print_array(reg.coef_)\n print('Intercept:', reg.intercept_)\n print('SSE all features:', sse)\n print('MSE all features:', np.mean(np.square(np.subtract(y_labels, y_predicted))))\n\n #correlation coefficients\n correlation = np.corrcoef(x_features, rowvar=False)\n plt.imshow(correlation, cmap='hot', interpolation='nearest')\n plt.colorbar()\n\n for i in range(6):\n plt.figure()\n x = x_features[:, [i]]\n reg = LinearRegression().fit(x, y_labels)\n predictedY = reg.predict(x)\n plt.scatter(x, y_labels, color='g')\n plt.plot(x, predictedY, color='r')\n\n plt.show()\n \n betas = ordinary_least_squares(x_features, y_labels)\n y = np.matmul(x_features, betas)\n reg = LinearRegression().fit(x_features, y)\n y_predicted = reg.predict(x_features)\n sse = np.sum(np.power(y_predicted - y_labels, 2))\n mse = sse/np.size(y_predicted)\n\n print(\"\\nResults from OLS:\\n\")\n print(\"Coefficients:\")\n print_array(betas)\n print('SSE:', sse)\n print('MSE:', mse)\n\n thetas = bgd(x_features, y_labels, 1e-7, 100, 1000)\n m_bgd = x_features.shape[0]\n x_features_ones = np.hstack((np.ones((m_bgd, 1)), x_features))\n\n y = np.matmul(x_features_ones, thetas)\n reg = LinearRegression().fit(x_features_ones, y)\n y_predicted = reg.predict(x_features_ones)\n sse = np.sum(np.power(y_predicted - y_labels, 2))\n mse = sse/np.size(y_predicted)\n\n print(\"\\nResults from BGD:\\n\")\n print(\"Coefficients:\")\n print_array(thetas)\n print('SSE:', sse)\n print('MSE:', mse, '\\n')\n\n print('\\n########################second data set##########################\\n')\n\n #read in file\n data, row_count, col_count = load_secondary_data()\n\n #set up features and labels\n x_features = data[:, 0:col_count - 1]\n y_labels = data[:, col_count - 1]\n\n #data transforms\n #none\n\n #create linear regression object and fit it against all features\n reg = LinearRegression()\n reg = reg.fit(x_features, y_labels)\n\n y_predicted = reg.predict(x_features)\n sse = reg._residues\n\n print('All features coefficients:')\n print_array(reg.coef_)\n print('Intercept:', reg.intercept_)\n print('SSE all features:', sse)\n print('MSE all features:', np.mean(np.square(np.subtract(y_labels, y_predicted))))\n\n #correlation coefficients\n correlation = np.corrcoef(x_features, rowvar=False)\n plt.imshow(correlation, cmap='hot', interpolation='nearest')\n plt.colorbar()\n for i in range(11):\n plt.figure()\n x = x_features[:, [i]]\n reg = LinearRegression().fit(x, y_labels)\n predictedY = reg.predict(x)\n plt.scatter(x, y_labels, color='g')\n plt.plot(x, predictedY, color='r')\n\n betas = ordinary_least_squares(x_features, y_labels)\n y = np.matmul(x_features, betas)\n reg = LinearRegression().fit(x_features, y)\n y_predicted = reg.predict(x_features)\n sse = np.sum(np.power(y_predicted - y_labels, 2))\n mse = sse/np.size(y_predicted)\n\n print(\"\\nResults from OLS:\\n\")\n print(\"Coefficients:\")\n print_array(betas)\n print('SSE:', sse)\n print('MSE:', mse)\n\n plt.show()\n thetas = bgd(x_features, y_labels, 0.0001, 60, 30)\n m_bgd = x_features.shape[0]\n x_features_ones = np.hstack((np.ones((m_bgd, 1)), x_features))\n\n y = np.matmul(x_features_ones, thetas)\n reg = LinearRegression().fit(x_features_ones, y)\n y_predicted = reg.predict(x_features_ones)\n sse = np.sum(np.power(y_predicted - y_labels, 2))\n mse = sse/np.size(y_predicted)\n\n print(\"\\nResults from BGD:\\n\")\n print(\"Coefficients:\")\n print_array(thetas)\n print('SSE:', sse)\n print('MSE:', mse)\n\ndef load_data():\n data = np.loadtxt('reDataUCI.csv', delimiter=\",\", skiprows=1)\n #remove outliers to keep only within range\n data = remove_outliers_from_y(data, 10, 60)\n row_count = np.size(data, 0)\n col_count = np.size(data, 1)\n\n return (data, row_count, col_count)\n\ndef load_secondary_data():\n data = np.loadtxt('winequality-red.csv', delimiter=';', skiprows=1)\n row_count = np.size(data, 0)\n col_count = np.size(data, 1)\n\n return (data, row_count, col_count)\n\ndef generate_scatter(title, y_label, x_label, index, x_features, y_labels):\n plt.figure()\n plt.title(title)\n plt.ylabel(y_label)\n plt.xlabel(x_label)\n plt.scatter(x_features[:, index], y_labels)\n\ndef single_feature_plot(x_features, y_labels, column_index):\n #generate_scatter_all(x_features, y_labels)\n reg = LinearRegression().fit(x_features[:, [column_index]], y_labels)\n predictedY = reg.predict(x_features[:, [column_index]])\n\n print(\"Coefficent for single variable: \" + str(reg.coef_))\n print(\"SSE for single variable\", column_index, ':', reg._residues)\n\n plt.figure()\n plt.scatter(x_features[:, column_index], y_labels, color='g')\n plt.plot(x_features[:, column_index], predictedY, color='r')\n\ndef generate_scatter_all(x_features, y_labels):\n generate_scatter('ID Number vs.Y', 'Y label', 'ID Number', 0, x_features, y_labels)\n generate_scatter('Transaction Date vs.Y', 'Y label', 'Transaction Date', 1, x_features, y_labels)\n generate_scatter('House Age vs.Y', 'Y label', 'House Age', 2, x_features, y_labels)\n generate_scatter('Dist to MRT vs.Y', 'Y label', 'Dist to MRT', 3, x_features, y_labels)\n generate_scatter('Number of convenience stores vs.Y', 'Y label', 'Number of convenience stores', 4, x_features, y_labels)\n generate_scatter('Lat Coord vs.Y', 'Y label', 'Lat Coord', 5, x_features, y_labels)\n plt.show()\n\ndef clear_terminal():\n os.system('cls' if os.name == 'nt' else 'clear')\n\ndef print_array(arr):\n for i, item in enumerate(arr):\n print(str(i)+':', item)\n\ndef remove_outliers_from_y(data, low, high): \n i = 0\n loopcount = len(data)\n while i < loopcount:\n if(data[i][7] > high or data[i][7] < low):\n data = np.delete(data, i, axis=0)\n loopcount-=1\n i+=1\n return data\n\ndef ordinary_least_squares(training_data, labels):\n x_trans = np.transpose(training_data)\n betas = np.matmul(np.linalg.inv(np.matmul(x_trans, training_data)), np.matmul(x_trans, labels)) \n\n return betas\n\ndef bgd(training_data, labels, alpha, epsilon, epochs):\n m = training_data.shape[0]\n training_data = np.hstack((np.ones((m, 1)), training_data))\n\n thetas = np.random.random(training_data.shape[1])\n temp = []\n total_cost = 0\n\n for epoch in range(epochs):\n temp = []\n for theta in thetas:\n total_cost = 0\n for i, row in enumerate(training_data):\n predicted_y = np.dot(thetas, row)\n for j, data in enumerate(row):\n label = labels[i]\n total_cost += (predicted_y - label) * data\n tempi = theta - alpha * (1.0/m) * total_cost\n temp.append(tempi)\n\n #check for convergence \n thetas = temp \n if(abs(total_cost) <= epsilon): break\n\n return np.array(thetas)\n \nmain()\n"} {"blob_id": "acffd8b532807630b73b311131801b3a94a8fa09", "repo_name": "RakhimovSE/Python-Lessons", "path": "/4. September 2018/18. 2018_09_04/source_1.py", "length_bytes": 927, "score": 3.53125, "int_score": 4, "content": "# \u0438\u0442\u0435\u0440\u0430\u0442\u0438\u0432\u043d\u044b\u0439 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u0431\u0438\u043d\u0430\u0440\u043d\u043e\u0433\u043e \u043f\u043e\u0438\u0441\u043a\u0430 (\u0447\u0435\u0440\u0435\u0437 \u0446\u0438\u043a\u043b)\ndef bin_search(w, h, n):\n # l - \u0438\u043d\u0434\u0435\u043a\u0441 \u043b\u0435\u0432\u043e\u0439 \u0433\u0440\u0430\u043d\u0438\u0446\u044b\n # r - \u0438\u043d\u0434\u0435\u043a\u0441 \u043f\u0440\u0430\u0432\u043e\u0439 \u0433\u0440\u0430\u043d\u0438\u0446\u044b\n # m - \u0438\u043d\u0434\u0435\u043a\u0441 \u0441\u0440\u0435\u0434\u043d\u0435\u0433\u043e \u044d\u043b\u0435\u043c\u0435\u043d\u0442\u0430\n l = 0\n r = max(w * n, h * n)\n while l < r:\n m = (l + r) // 2\n # k - \u043c\u0430\u043a\u0441\u0438\u043c\u0430\u043b\u044c\u043d\u043e\u0435 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0434\u0438\u043f\u043b\u043e\u043c\u043e\u0432, \u043a\u043e\u0442\u043e\u0440\u043e\u0435 \u043c\u043e\u0436\u043d\u043e\n # \u0440\u0430\u0437\u043c\u0435\u0441\u0442\u0438\u0442\u044c \u043d\u0430 \u0434\u043e\u0441\u043a\u0435 \u0434\u043b\u0438\u043d\u043e\u0439 m\n k = (m // w) * (m // h)\n # \u0415\u0441\u043b\u0438 k (\u043c\u0430\u043a\u0441. \u043a\u043e\u043b-\u0432\u043e \u0434\u0438\u043f\u043b\u043e\u043c\u043e\u0432) = n\n if k == n:\n return m\n if k > n:\n r = m - 1\n else:\n l = m + 1\n k = (l // w) * (l // h)\n if k >= n:\n return l\n else:\n return l + 1\n\n\nif __name__ == '__main__':\n w, h, n = map(int, input().split())\n print(bin_search(w, h, n))\n"} {"blob_id": "80443a2631d22f703fd0f91939fdb7dd1699055c", "repo_name": "ShawnWuzh/algorithms", "path": "/\u6811-\u5bf9\u79f0\u7684\u4e8c\u53c9\u6811.py", "length_bytes": 1710, "score": 3.953125, "int_score": 4, "content": "'''\n\u8bf7\u5b9e\u73b0\u4e00\u4e2a\u51fd\u6570\uff0c\u7528\u6765\u5224\u65ad\u4e00\u9897\u4e8c\u53c9\u6811\u662f\u4e0d\u662f\u5bf9\u79f0\u7684\u3002\u6ce8\u610f\uff0c\u5982\u679c\u4e00\u4e2a\u4e8c\u53c9\u6811\u540c\u6b64\u4e8c\u53c9\u6811\u7684\u955c\u50cf\u662f\u540c\u6837\u7684\uff0c\u5b9a\u4e49\u5176\u4e3a\u5bf9\u79f0\u7684\u3002\n'''\n'''\n\u8fd9\u9053\u9898\u7684\u601d\u8def\u5f88\u663e\u7136\uff0c\u6211\u4eec\u9700\u8981\u91c7\u53d6\u5de6\u4e2d\u53f3\u7684\u4e2d\u5e8f\u904d\u5386\uff0c\u4ee5\u53ca\u53f3\u4e2d\u5de6\u7684\u4e2d\u5e8f\u904d\u5386\uff0c\u7136\u540e\u770b\u8fd9\u4e24\u79cd\u7684\u7684\u5148\u5e8f\u904d\u5386\u662f\u5426\u4e00\u81f4\uff0c\u5982\u679c\n\u4e00\u81f4\uff0c\u8bf4\u660e\u662f\u5bf9\u79f0\u7684\uff0c\u5982\u679c\u4e0d\u4e00\u81f4\uff0c\u8bf4\u660e\u4e0d\u4e00\u81f4\u3002\n'''\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Solution:\n def isSymmetrical(self, pRoot):\n curNode1 = pRoot\n curNode2 = pRoot\n stack1 = []\n stack2 = []\n while(curNode1):\n stack1.append(curNode1)\n curNode1 = curNode1.left\n while(curNode2):\n stack2.append(curNode2)\n curNode2 = curNode2.right\n if(len(stack1) != len(stack2)):\n return False\n while(len(stack1) and len(stack2)):\n curNode1 = stack1.pop()\n curNode2 = stack2.pop()\n if curNode1.val != curNode2.val:\n return False\n rightNode = curNode1.right\n while(rightNode):\n stack1.append(rightNode)\n rightNode = rightNode.left\n leftNode = curNode2.left\n while(leftNode):\n stack2.append(leftNode)\n leftNode = leftNode.right\n if len(stack1) or len(stack2):\n return False\n return True\n\nif __name__ == '__main__':\n node1 = TreeNode(2)\n node2 = TreeNode(3)\n node1.left = node2\n node3 = TreeNode(4)\n node1.right = node3\n s = Solution()\n print(s.isSymmetrical(node1))\n"} {"blob_id": "6d6adee24ebea7c28ce5ad80de7607910a184985", "repo_name": "jlutch/SeniorATCSFinalProject", "path": "/ATCSFINALPROJECT/TheChessBotExpirence.py", "length_bytes": 45464, "score": 3.546875, "int_score": 4, "content": "import pygame\r\nimport random\r\nfrom pygame.locals import (\r\n RLEACCEL,\r\n K_UP,\r\n K_DOWN,\r\n K_LEFT,\r\n K_RIGHT,\r\n K_ESCAPE,\r\n KEYDOWN,\r\n QUIT,)\r\n\r\npygame.init()\r\nSQUARE_HEIGHT = 64\r\nSQUARE_WIDTH = 64\r\nTURNCOUNT = 0\r\nWHITE = 0\r\nBLACK = 1\r\nmoving_piece = None\r\n\r\ndef BoardSetup():\r\n\t# Set up the drawing window\r\n\tscreen = pygame.display.set_mode([512, 512])\r\n\tboard = pygame.image.load(\"Assets/ChessBoard.jpg\").convert()\r\n\tscreen.blit(board,(0,0))\r\n\treturn screen\r\n\r\nclass King(pygame.sprite.Sprite):\r\n def __init__(self, png, pos, color):\r\n super(King, self).__init__()\r\n self.surf = pygame.image.load(png)\r\n self.surf.set_colorkey((0, 0, 0), RLEACCEL)\r\n self.clicked = False\r\n self.pos = pos\r\n self.rect = self.surf.get_rect(center = self.pos)\r\n self.color = color \r\n def GetCornerPos(self):\r\n \treturn (self.rect.x, self.rect.y)\r\n def UpdatePos(self, MousePosition):\r\n \tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n def PlacePiece(self, MousePosition):\r\n \t#checks if the move is valid\r\n \t#if is not...\r\n \tif (abs((MousePosition[0]) - (self.pos[0])) > (3*SQUARE_WIDTH/2)) or (abs((MousePosition[1]) - (self.pos[1])) > (3*SQUARE_HEIGHT/2)):\r\n \t\t#puts the piece back\r\n \t\tself.ResetPiece()\r\n \t#if it is valid\r\n \telse:\r\n \t\tfor Piece in AllPieces:\r\n \t\t\t#if this square is already occupied by a piece\r\n \t\t\tif (MousePosition[0] - SQUARE_WIDTH/2 == Piece.GetCornerPos()[0]) and (MousePosition[1] - SQUARE_HEIGHT/2 == Piece.GetCornerPos()[1]):\r\n \t\t\t\t#if it is a piece of the same color\r\n \t\t\t\tif self.color == Piece.color:\r\n \t\t\t\t\tself.ResetPiece()\r\n \t\t\t\t\treturn False\r\n \t\t\t\telse:\r\n \t\t\t\t\t#deletes the piece\r\n \t\t\t\t\tPiece.kill()\r\n \t\t#move the piece\r\n \t\tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n \t\tself.pos = MousePosition\r\n \t\treturn True\r\n \treturn False\r\n\r\n def ResetPiece(self):\r\n \tself.rect = self.surf.get_rect(center = self.pos)\r\n\r\nclass Pawn(pygame.sprite.Sprite):\r\n def __init__(self, png, pos, color, first):\r\n super(Pawn, self).__init__()\r\n self.surf = pygame.image.load(png)\r\n self.surf.set_colorkey((0, 0, 0), RLEACCEL)\r\n self.clicked = False\r\n self.pos = pos\r\n self.rect = self.surf.get_rect(center = self.pos)\r\n self.color = color \r\n def UpdatePos(self, MousePosition):\r\n \tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n def GetCornerPos(self):\r\n \treturn (self.rect.x, self.rect.y)\r\n def PlacePiece(self, MousePosition):\r\n \t#if white\r\n #checks if the move is valid\r\n #if this piece needs to be constantly going upwards\r\n if (self.color == 0):\r\n #going straight\r\n if (MousePosition[0] == self.pos[0]):\r\n if (MousePosition[1] == self.pos[1] - SQUARE_HEIGHT):\r\n if self.CollisionCheck(MousePosition[0], MousePosition[1]):\r\n self.ResetPiece()\r\n return False\r\n self.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n self.pos = MousePosition\r\n self.CheckPromotion(WHITE)\r\n return True\t\t\t\t\r\n \t\t\t#moving twice\r\n elif (MousePosition[1] == self.pos[1] - SQUARE_HEIGHT*2):\r\n if (self.pos[1] == 416):\r\n if self.CollisionCheck(MousePosition[0], MousePosition[1]):\r\n self.ResetPiece()\r\n return False\r\n if self.CollisionCheck(MousePosition[0], MousePosition[1]+SQUARE_HEIGHT):\r\n self.ResetPiece()\r\n return False \r\n self.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n self.pos = MousePosition\r\n self.first = False\r\n return True\r\n else:\r\n self.ResetPiece()\r\n return False\r\n self.ResetPiece()\r\n return False\r\n \t\t#diagnoally\r\n elif (MousePosition[1] == self.pos[1] - SQUARE_HEIGHT):\r\n \t\t\t#diagnoally right\r\n if (MousePosition[0] == self.pos[0] + SQUARE_WIDTH):\r\n for Piece in AllPieces:\r\n if (Piece.pos[0] == self.pos[0] + SQUARE_WIDTH) and (Piece.pos[1] == self.pos[1] - SQUARE_HEIGHT):\r\n if Piece.color != self.color:\r\n \tPiece.kill()\r\n \tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n \tself.pos = MousePosition\r\n \tself.CheckPromotion(WHITE)\r\n \treturn True\r\n else:\r\n \tself.ResetPiece()\r\n \treturn False\r\n self.ResetPiece()\r\n return False\r\n \t\t\t#diagnoally left\r\n if (MousePosition[0] == self.pos[0] - SQUARE_HEIGHT):\r\n for Piece in AllPieces:\r\n if (Piece.pos[0] == self.pos[0] - SQUARE_WIDTH) and (Piece.pos[1] == self.pos[1] - SQUARE_HEIGHT):\r\n if Piece.color != self.color:\r\n \tPiece.kill()\r\n \tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n \tself.pos = MousePosition\r\n \tself.CheckPromotion(WHITE)\r\n \treturn True\r\n else:\r\n \tself.ResetPiece()\r\n \treturn False\r\n self.ResetPiece()\r\n return False\r\n else:\r\n self.ResetPiece()\r\n return False\r\n \r\n if (self.color == 1):\r\n #going straight\r\n if (MousePosition[0] == self.pos[0]):\r\n if (MousePosition[1] == self.pos[1] + SQUARE_HEIGHT):\r\n if self.CollisionCheck(MousePosition[0], MousePosition[1]):\r\n self.ResetPiece()\r\n return False\r\n self.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n self.pos = MousePosition\r\n self.CheckPromotion(BLACK)\r\n return True \r\n #moving twice\r\n elif (MousePosition[1] == self.pos[1] + SQUARE_HEIGHT*2):\r\n if (self.pos[1] == 64+32):\r\n if self.CollisionCheck(MousePosition[0], MousePosition[1]):\r\n self.ResetPiece()\r\n return False\r\n elif self.CollisionCheck(MousePosition[0], MousePosition[1]-SQUARE_HEIGHT):\r\n self.ResetPiece()\r\n return False \r\n self.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n self.pos = MousePosition\r\n self.first = False\r\n return True\r\n else:\r\n self.ResetPiece()\r\n return False\r\n self.ResetPiece()\r\n return False\r\n #diagnoally\r\n elif (MousePosition[1] == self.pos[1] + SQUARE_HEIGHT):\r\n #diagnoally right\r\n if (MousePosition[0] == self.pos[0] + SQUARE_WIDTH):\r\n for Piece in AllPieces:\r\n if (Piece.pos[0] == self.pos[0] + SQUARE_WIDTH) and (Piece.pos[1] == self.pos[1] + SQUARE_HEIGHT):\r\n if self.color != Piece.color:\r\n \tPiece.kill()\r\n \tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n \tself.pos = MousePosition\r\n \tself.CheckPromotion(BLACK)\r\n \treturn True\r\n else:\r\n \tself.ResetPiece()\r\n \treturn False\r\n self.ResetPiece()\r\n return False\r\n #diagnoally left\r\n if (MousePosition[0] == self.pos[0] - SQUARE_HEIGHT):\r\n for Piece in AllPieces:\r\n if (Piece.pos[0] == self.pos[0] - SQUARE_WIDTH) and (Piece.pos[1] == self.pos[1] + SQUARE_HEIGHT):\r\n if self.color != Piece.color:\r\n \tPiece.kill()\r\n \tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n \tself.pos = MousePosition\r\n \tself.CheckPromotion(BLACK)\r\n \treturn True\r\n else:\r\n \tself.ResetPiece()\r\n \treturn False\r\n self.ResetPiece()\r\n return False\r\n else:\r\n self.ResetPiece()\r\n return False\r\n def CollisionCheck(self, MousePositionX, MousePositionY):\r\n MousePosition = (MousePositionX, MousePositionY)\r\n for Piece in AllPieces:\r\n if Piece.pos[0] == MousePosition[0] and Piece.pos[1] == MousePosition[1]:\r\n return True\r\n return False\r\n def ResetPiece(self):\r\n \tself.rect = self.surf.get_rect(center = self.pos)\r\n def CheckPromotion(self, color):\r\n \tif (self.pos[1] == SQUARE_HEIGHT/2 and color == WHITE) or (self.pos[1] == 512 - SQUARE_HEIGHT/2 and color == BLACK):\r\n \r\n UserInput = input(\"Enter R for a rook, N for a knight, B for bishop, Q for queen. (Default is queen)\")\r\n \r\n if UserInput == \"R\":\r\n if self.color == WHITE:\r\n \tx = Rook(\"Assets/WhitePieces/WhiteRook.png\", self.pos, color)\r\n \tWhitePieces.add(x)\r\n \tAllPieces.add(x)\r\n else:\r\n \tx = Rook(\"Assets/BlackPieces/BlackRook.png\", self.pos, color)\r\n \tBlackPieces.add(x)\r\n \tAllPieces.add(x)\r\n self.kill()\r\n elif UserInput == \"N\":\r\n if self.color == WHITE:\r\n \tx = Knight(\"Assets/WhitePieces/WhiteKnight.png\", self.pos, color)\r\n \tWhitePieces.add(x)\r\n \tAllPieces.add(x)\r\n else:\r\n \tx = Knight(\"Assets/BlackPieces/BlackKnight.png\", self.pos, color)\r\n \tBlackPieces.add(x)\r\n \tAllPieces.add(x)\r\n self.kill()\r\n elif UserInput == \"B\":\r\n if self.color == WHITE:\r\n \tx = Bishop(\"Assets/WhitePieces/WhiteBishop.png\", self.pos, color)\r\n \tWhitePieces.add(x)\r\n \tAllPieces.add(x)\r\n else:\r\n \tx = Bishop(\"Assets/BlackPieces/BlackBishop.png\", self.pos, color)\r\n \tBlackPieces.add(x)\r\n \tAllPieces.add(x)\r\n self.kill()\r\n else:\r\n if self.color == WHITE:\r\n \tx = Queen(\"Assets/WhitePieces/WhiteQueen.png\", self.pos, color)\r\n \tWhitePieces.add(x)\r\n \tAllPieces.add(x)\r\n else:\r\n \tx = Queen(\"Assets/BlackPieces/BlackQueen.png\", self.pos, color)\r\n \tBlackPieces.add(x)\r\n \tAllPieces.add(x)\r\n self.kill()\r\n \t\r\nclass Rook(pygame.sprite.Sprite):\r\n def __init__(self, png, pos, color):\r\n super(Rook, self).__init__()\r\n self.surf = pygame.image.load(png)\r\n self.surf.set_colorkey((0, 0, 0), RLEACCEL)\r\n self.clicked = False\r\n self.pos = pos\r\n self.rect = self.surf.get_rect(center = self.pos)\r\n self.color = color \r\n def GetCornerPos(self):\r\n return (self.rect.x, self.rect.y)\r\n def UpdatePos(self, MousePosition):\r\n self.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n def PlacePiece(self, MousePosition):\r\n ###NOTE####\r\n #this code seems to almost repeat itself four times\r\n #I tried to put it in a function for the sake of efficiency, but each time \r\n #the pygame window just crashed\r\n #this was a bug I was unable to solve\r\n\r\n #checking if vertical negative movment is legal\r\n if self.pos[0] == MousePosition[0] and self.pos[1] > MousePosition[1]:\r\n \t#we need to loop through every square here\r\n \tx = self.pos[1]\r\n \twhile x != MousePosition[1]:\r\n \t\tx -= SQUARE_HEIGHT\r\n \t\t#if we are on the last square\r\n \t\tif x == MousePosition[1]:\r\n \t\t\tfor Piece in AllPieces:\r\n \t\t\t\t#if a piece is occupying this square...\r\n \t\t\t\tif Piece.pos[0] == self.pos[0] and Piece.pos[1] == x:\r\n \t\t\t\t\tif Piece.color != self.color:\r\n \t\t\t\t\t\tPiece.kill()\r\n \t\t\t\t\t\tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n \t\t\t\t\t\tself.pos = MousePosition\r\n \t\t\t\t\t\treturn True\r\n \t\t\t\t\telse:\r\n \t\t\t\t\t\t#print(\"End piece collision!\")\r\n \t\t\t\t\t\tself.ResetPiece()\r\n \t\t\t\t\t\treturn False\r\n \t\t\t#No pieces occupy the end space\r\n \t\t\tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n \t\t\tself.pos = MousePosition\r\n \t\t\treturn True\r\n \t\t\r\n \t\t#check if any of the pieces...\r\n \t\tfor Piece in AllPieces:\r\n \t\t\t#...happen to be on this square\r\n \t\t\tif Piece.pos[0] == self.pos[0] and Piece.pos[1] == x:\r\n \t\t\t\t#this is a collision\r\n \t\t\t\t#print(\"intermediate collision\")\r\n \t\t\t\tself.ResetPiece()\r\n \t\t\t\treturn False\r\n\r\n #checking if vertical positive movment is legal\r\n elif self.pos[0] == MousePosition[0] and self.pos[1] < MousePosition[1]:\r\n \t#we need to loop through every square here\r\n \tx = self.pos[1]\r\n \twhile x != MousePosition[1]:\r\n \t\tx += SQUARE_HEIGHT\r\n \t\t#if we are on the last square\r\n \t\tif x == MousePosition[1]:\r\n \t\t\tfor Piece in AllPieces:\r\n \t\t\t\t#if a piece is occupying this square...\r\n \t\t\t\tif Piece.pos[0] == self.pos[0] and Piece.pos[1] == x:\r\n \t\t\t\t\tif Piece.color != self.color:\r\n \t\t\t\t\t\tPiece.kill()\r\n \t\t\t\t\t\tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n \t\t\t\t\t\tself.pos = MousePosition\r\n \t\t\t\t\t\treturn True\r\n \t\t\t\t\telse:\r\n \t\t\t\t\t\t#print(\"End piece collision!\")\r\n \t\t\t\t\t\tself.ResetPiece()\r\n \t\t\t\t\t\treturn False\r\n \t\t\t#No pieces occupy the end space\r\n \t\t\tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n \t\t\tself.pos = MousePosition\r\n \t\t\treturn True\r\n \t\t\r\n \t\t#check if any of the pieces...\r\n \t\tfor Piece in AllPieces:\r\n \t\t\t#...happen to be on this square\r\n \t\t\tif Piece.pos[0] == self.pos[0] and Piece.pos[1] == x:\r\n \t\t\t\t#this is a collision\r\n \t\t\t\t#print(\"intermediate collision\")\r\n \t\t\t\tself.ResetPiece()\r\n \t\t\t\treturn False\r\n #checking if horizontal positive movment is legal\r\n elif self.pos[1] == MousePosition[1] and self.pos[0] < MousePosition[0]:\r\n \t#we need to loop through every square here\r\n \tx = self.pos[0]\r\n \twhile x != MousePosition[0]:\r\n \t\tx += SQUARE_WIDTH\r\n \t\t#if we are on the last square\r\n \t\tif x == MousePosition[0]:\r\n \t\t\tfor Piece in AllPieces:\r\n \t\t\t\t#if a piece is occupying this square...\r\n \t\t\t\tif Piece.pos[1] == self.pos[1] and Piece.pos[0] == x:\r\n \t\t\t\t\tif Piece.color != self.color:\r\n \t\t\t\t\t\tPiece.kill()\r\n \t\t\t\t\t\tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n \t\t\t\t\t\tself.pos = MousePosition\r\n \t\t\t\t\t\treturn True\r\n \t\t\t\t\telse:\r\n \t\t\t\t\t\t#print(\"End piece collision!\")\r\n \t\t\t\t\t\tself.ResetPiece()\r\n \t\t\t\t\t\treturn False\r\n \t\t\t#No pieces occupy the end space\r\n \t\t\tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n \t\t\tself.pos = MousePosition\r\n \t\t\treturn True\r\n \t\t\r\n \t\t#check if any of the pieces...\r\n \t\tfor Piece in AllPieces:\r\n \t\t\t#...happen to be on this square\r\n \t\t\tif Piece.pos[1] == self.pos[1] and Piece.pos[0] == x:\r\n \t\t\t\t#this is a collision\r\n \t\t\t\t#print(\"intermediate collision\")\r\n \t\t\t\tself.ResetPiece()\r\n \t\t\t\treturn False\r\n elif self.pos[1] == MousePosition[1] and self.pos[0] > MousePosition[0]:\r\n \t#we need to loop through every square here\r\n \tx = self.pos[0]\r\n \twhile x != MousePosition[0]:\r\n \t\tx -= SQUARE_WIDTH\r\n \t\t#if we are on the last square\r\n \t\tif x == MousePosition[0]:\r\n \t\t\tfor Piece in AllPieces:\r\n \t\t\t\t#if a piece is occupying this square...\r\n \t\t\t\tif Piece.pos[1] == self.pos[1] and Piece.pos[0] == x:\r\n \t\t\t\t\tif Piece.color != self.color:\r\n \t\t\t\t\t\tPiece.kill()\r\n \t\t\t\t\t\tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n \t\t\t\t\t\tself.pos = MousePosition\r\n \t\t\t\t\t\treturn True\r\n \t\t\t\t\telse:\r\n \t\t\t\t\t\t#print(\"End piece collision!\")\r\n \t\t\t\t\t\tself.ResetPiece()\r\n \t\t\t\t\t\treturn False\r\n \t\t\t#No pieces occupy the end space\r\n \t\t\tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n \t\t\tself.pos = MousePosition\r\n \t\t\treturn True\r\n \t\t\r\n \t\t#check if any of the pieces...\r\n \t\tfor Piece in AllPieces:\r\n \t\t\t#...happen to be on this square\r\n \t\t\tif Piece.pos[1] == self.pos[1] and Piece.pos[0] == x:\r\n \t\t\t\t#this is a collision\r\n \t\t\t\t#print(\"intermediate collision\")\r\n \t\t\t\tself.ResetPiece()\r\n \t\t\t\treturn False\r\n self.ResetPiece()\r\n return False\r\n \r\n def ResetPiece(self):\r\n self.rect = self.surf.get_rect(center = self.pos)\r\n\r\nclass Bishop(pygame.sprite.Sprite):\r\n def __init__(self, png, pos, color):\r\n super(Bishop, self).__init__()\r\n self.surf = pygame.image.load(png)\r\n self.surf.set_colorkey((0, 0, 0), RLEACCEL)\r\n self.clicked = False\r\n self.pos = pos\r\n self.rect = self.surf.get_rect(center = self.pos)\r\n self.color = color \r\n def GetCornerPos(self):\r\n \treturn (self.rect.x, self.rect.y)\r\n def UpdatePos(self, MousePosition):\r\n \tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n def PlacePiece(self, MousePosition):\r\n \t#see note in rook class for reason that this is not broken up into smaller functions\r\n\r\n \t#if the move is even diagonal\r\n if abs(self.pos[0] - MousePosition[0]) == (abs(self.pos[1] - MousePosition[1])): \r\n \t#lets generate a list of valid moves for this piece\r\n \t#checking if diagonal negative negative movment is happening \r\n \tif self.pos[0] > MousePosition[0] and self.pos[1] > MousePosition[1]:\r\n \t\t#we need to loop through every square here\r\n \t\tx = self.pos[0]\r\n \t\ty = self.pos[1]\r\n \t\twhile x != MousePosition[0]:\r\n \t\t\tx -= SQUARE_WIDTH\r\n \t\t\ty -= SQUARE_HEIGHT\r\n \t\t\t#if we are on the last square\r\n \t\t\tif x == MousePosition[0]:\r\n \t\t\t\tfor Piece in AllPieces:\r\n \t\t\t\t\t#if a piece is occupying this square...\r\n \t\t\t\t\tif Piece.pos[1] == y and Piece.pos[0] == x:\r\n \t\t\t\t\t\tif Piece.color != self.color:\r\n \t\t\t\t\t\t\tPiece.kill()\r\n \t\t\t\t\t\t\tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n \t\t\t\t\t\t\tself.pos = MousePosition\r\n \t\t\t\t\t\t\treturn True\r\n \t\t\t\t\t\telse:\r\n \t\t\t\t\t\t\t#print(\"End piece collision!\")\r\n \t\t\t\t\t\t\tself.ResetPiece()\r\n \t\t\t\t\t\t\treturn False\r\n \t\t\t\t#No pieces occupy the end space\r\n \t\t\t\tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n \t\t\t\tself.pos = MousePosition\r\n \t\t\t\treturn True\r\n \t\t\r\n \t\t\t#check if any of the pieces...\r\n \t\t\tfor Piece in AllPieces:\r\n \t\t\t\t#...happen to be on this square\r\n \t\t\t\tif Piece.pos[1] == y and Piece.pos[0] == x:\r\n \t\t\t\t\t#this is a collision\r\n \t\t\t\t\t#print(\"intermediate collision\")\r\n \t\t\t\t\tself.ResetPiece()\r\n \t\t\t\t\treturn False\r\n \r\n \t#checking if diagonal positive negative movment is happening \r\n \tif self.pos[0] < MousePosition[0] and self.pos[1] > MousePosition[1]:\r\n \t\t#we need to loop through every square here\r\n \t\tx = self.pos[0]\r\n \t\ty = self.pos[1]\r\n \t\twhile x != MousePosition[0]:\r\n \t\t\tx += SQUARE_WIDTH\r\n \t\t\ty -= SQUARE_HEIGHT\r\n \t\t\t#if we are on the last square\r\n \t\t\tif x == MousePosition[0]:\r\n \t\t\t\tfor Piece in AllPieces:\r\n \t\t\t\t\t#if a piece is occupying this square...\r\n \t\t\t\t\tif Piece.pos[1] == y and Piece.pos[0] == x:\r\n \t\t\t\t\t\tif Piece.color != self.color:\r\n \t\t\t\t\t\t\tPiece.kill()\r\n \t\t\t\t\t\t\tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n \t\t\t\t\t\t\tself.pos = MousePosition\r\n \t\t\t\t\t\t\treturn True\r\n \t\t\t\t\t\telse:\r\n \t\t\t\t\t\t\t#print(\"End piece collision!\")\r\n \t\t\t\t\t\t\tself.ResetPiece()\r\n \t\t\t\t\t\t\treturn False\r\n \t\t\t\t#No pieces occupy the end space\r\n \t\t\t\tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n \t\t\t\tself.pos = MousePosition\r\n \t\t\t\treturn True\r\n \t\t\r\n \t\t\t#check if any of the pieces...\r\n \t\t\tfor Piece in AllPieces:\r\n \t\t\t\t#...happen to be on this square\r\n \t\t\t\tif Piece.pos[1] == y and Piece.pos[0] == x:\r\n \t\t\t\t\t#this is a collision\r\n \t\t\t\t\t#print(\"intermediate collision\")\r\n \t\t\t\t\tself.ResetPiece()\r\n \t\t\t\t\treturn False\r\n\r\n\t\t\t#checking if diagonal negative positive movment is happening \r\n \tif self.pos[0] > MousePosition[0] and self.pos[1] < MousePosition[1]:\r\n \t\t#we need to loop through every square here\r\n \t\tx = self.pos[0]\r\n \t\ty = self.pos[1]\r\n \t\twhile x != MousePosition[0]:\r\n \t\t\tx -= SQUARE_WIDTH\r\n \t\t\ty += SQUARE_HEIGHT\r\n \t\t\t#if we are on the last square\r\n \t\t\tif x == MousePosition[0]:\r\n \t\t\t\tfor Piece in AllPieces:\r\n \t\t\t\t\t#if a piece is occupying this square...\r\n \t\t\t\t\tif Piece.pos[1] == y and Piece.pos[0] == x:\r\n \t\t\t\t\t\tif Piece.color != self.color:\r\n \t\t\t\t\t\t\tPiece.kill()\r\n \t\t\t\t\t\t\tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n \t\t\t\t\t\t\tself.pos = MousePosition\r\n \t\t\t\t\t\t\treturn True\r\n \t\t\t\t\t\telse:\r\n \t\t\t\t\t\t\t#print(\"End piece collision!\")\r\n \t\t\t\t\t\t\tself.ResetPiece()\r\n \t\t\t\t\t\t\treturn False\r\n \t\t\t\t#No pieces occupy the end space\r\n \t\t\t\tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n \t\t\t\tself.pos = MousePosition\r\n \t\t\t\treturn True\r\n \t\t\r\n \t\t\t#check if any of the pieces...\r\n \t\t\tfor Piece in AllPieces:\r\n \t\t\t\t#...happen to be on this square\r\n \t\t\t\tif Piece.pos[1] == y and Piece.pos[0] == x:\r\n \t\t\t\t\t#this is a collision\r\n \t\t\t\t\t#print(\"intermediate collision\")\r\n \t\t\t\t\tself.ResetPiece()\r\n \t\t\t\t\treturn False\r\n \r\n \t#checking if diagonal positive positive movment is happening \r\n \tif self.pos[0] < MousePosition[0] and self.pos[1] < MousePosition[1]:\r\n \t\t#we need to loop through every square here\r\n \t\tx = self.pos[0]\r\n \t\ty = self.pos[1]\r\n \t\twhile x != MousePosition[0]:\r\n \t\t\tx += SQUARE_WIDTH\r\n \t\t\ty += SQUARE_HEIGHT\r\n \t\t\t#if we are on the last square\r\n \t\t\tif x == MousePosition[0]:\r\n \t\t\t\tfor Piece in AllPieces:\r\n \t\t\t\t\t#if a piece is occupying this square...\r\n \t\t\t\t\tif Piece.pos[1] == y and Piece.pos[0] == x:\r\n \t\t\t\t\t\tif Piece.color != self.color:\r\n \t\t\t\t\t\t\tPiece.kill()\r\n \t\t\t\t\t\t\tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n \t\t\t\t\t\t\tself.pos = MousePosition\r\n \t\t\t\t\t\t\treturn True\r\n \t\t\t\t\t\telse:\r\n \t\t\t\t\t\t\t#print(\"End piece collision!\")\r\n \t\t\t\t\t\t\tself.ResetPiece()\r\n \t\t\t\t\t\t\treturn False\r\n \t\t\t\t#No pieces occupy the end space\r\n \t\t\t\tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n \t\t\t\tself.pos = MousePosition\r\n \t\t\t\treturn True\r\n \t\t\r\n \t\t\t#check if any of the pieces...\r\n \t\t\tfor Piece in AllPieces:\r\n \t\t\t\t#...happen to be on this square\r\n \t\t\t\tif Piece.pos[1] == y and Piece.pos[0] == x:\r\n \t\t\t\t\t#this is a collision\r\n \t\t\t\t\t#print(\"intermediate collision\")\r\n \t\t\t\t\tself.ResetPiece()\r\n \t\t\t\t\treturn False\r\n else:\r\n \tself.ResetPiece()\r\n \treturn False\r\n \t\t\r\n def ResetPiece(self):\r\n \tself.rect = self.surf.get_rect(center = self.pos) \t\r\n\r\nclass Queen(pygame.sprite.Sprite):\r\n def __init__(self, png, pos, color):\r\n super(Queen, self).__init__()\r\n self.surf = pygame.image.load(png)\r\n self.surf.set_colorkey((0, 0, 0), RLEACCEL)\r\n self.clicked = False\r\n self.pos = pos\r\n self.rect = self.surf.get_rect(center = self.pos)\r\n self.color = color \r\n def GetCornerPos(self):\r\n \treturn (self.rect.x, self.rect.y)\r\n def UpdatePos(self, MousePosition):\r\n \tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n def PlacePiece(self, MousePosition):\r\n \t#if the move is even diagonal\r\n if abs(self.pos[0] - MousePosition[0]) == (abs(self.pos[1] - MousePosition[1])): \r\n \t#lets generate a list of valid moves for this piece\r\n \t#checking if diagonal negative negative movment is happening \r\n \tif self.pos[0] > MousePosition[0] and self.pos[1] > MousePosition[1]:\r\n \t\t#we need to loop through every square here\r\n \t\tx = self.pos[0]\r\n \t\ty = self.pos[1]\r\n \t\twhile x != MousePosition[0]:\r\n \t\t\tx -= SQUARE_WIDTH\r\n \t\t\ty -= SQUARE_HEIGHT\r\n \t\t\t#if we are on the last square\r\n \t\t\tif x == MousePosition[0]:\r\n \t\t\t\tfor Piece in AllPieces:\r\n \t\t\t\t\t#if a piece is occupying this square...\r\n \t\t\t\t\tif Piece.pos[1] == y and Piece.pos[0] == x:\r\n \t\t\t\t\t\tif Piece.color != self.color:\r\n \t\t\t\t\t\t\tPiece.kill()\r\n \t\t\t\t\t\t\tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n \t\t\t\t\t\t\tself.pos = MousePosition\r\n \t\t\t\t\t\t\treturn True\r\n \t\t\t\t\t\telse:\r\n \t\t\t\t\t\t\t#print(\"End piece collision!\")\r\n \t\t\t\t\t\t\tself.ResetPiece()\r\n \t\t\t\t\t\t\treturn False\r\n \t\t\t\t#No pieces occupy the end space\r\n \t\t\t\tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n \t\t\t\tself.pos = MousePosition\r\n \t\t\t\treturn True\r\n \t\t\r\n \t\t\t#check if any of the pieces...\r\n \t\t\tfor Piece in AllPieces:\r\n \t\t\t\t#...happen to be on this square\r\n \t\t\t\tif Piece.pos[1] == y and Piece.pos[0] == x:\r\n \t\t\t\t\t#this is a collision\r\n \t\t\t\t\t#print(\"intermediate collision\")\r\n \t\t\t\t\tself.ResetPiece()\r\n \t\t\t\t\treturn False\r\n \r\n \t#checking if diagonal positive negative movment is happening \r\n \tif self.pos[0] < MousePosition[0] and self.pos[1] > MousePosition[1]:\r\n \t\t#we need to loop through every square here\r\n \t\tx = self.pos[0]\r\n \t\ty = self.pos[1]\r\n \t\twhile x != MousePosition[0]:\r\n \t\t\tx += SQUARE_WIDTH\r\n \t\t\ty -= SQUARE_HEIGHT\r\n \t\t\t#if we are on the last square\r\n \t\t\tif x == MousePosition[0]:\r\n \t\t\t\tfor Piece in AllPieces:\r\n \t\t\t\t\t#if a piece is occupying this square...\r\n \t\t\t\t\tif Piece.pos[1] == y and Piece.pos[0] == x:\r\n \t\t\t\t\t\tif Piece.color != self.color:\r\n \t\t\t\t\t\t\tPiece.kill()\r\n \t\t\t\t\t\t\tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n \t\t\t\t\t\t\tself.pos = MousePosition\r\n \t\t\t\t\t\t\treturn True\r\n \t\t\t\t\t\telse:\r\n \t\t\t\t\t\t\t#print(\"End piece collision!\")\r\n \t\t\t\t\t\t\tself.ResetPiece()\r\n \t\t\t\t\t\t\treturn False\r\n \t\t\t\t#No pieces occupy the end space\r\n \t\t\t\tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n \t\t\t\tself.pos = MousePosition\r\n \t\t\t\treturn True\r\n \t\t\r\n \t\t\t#check if any of the pieces...\r\n \t\t\tfor Piece in AllPieces:\r\n \t\t\t\t#...happen to be on this square\r\n \t\t\t\tif Piece.pos[1] == y and Piece.pos[0] == x:\r\n \t\t\t\t\t#this is a collision\r\n \t\t\t\t\t#print(\"intermediate collision\")\r\n \t\t\t\t\tself.ResetPiece()\r\n \t\t\t\t\treturn False\r\n\r\n\t\t\t#checking if diagonal negative positive movment is happening \r\n \tif self.pos[0] > MousePosition[0] and self.pos[1] < MousePosition[1]:\r\n \t\t#we need to loop through every square here\r\n \t\tx = self.pos[0]\r\n \t\ty = self.pos[1]\r\n \t\twhile x != MousePosition[0]:\r\n \t\t\tx -= SQUARE_WIDTH\r\n \t\t\ty += SQUARE_HEIGHT\r\n \t\t\t#if we are on the last square\r\n \t\t\tif x == MousePosition[0]:\r\n \t\t\t\tfor Piece in AllPieces:\r\n \t\t\t\t\t#if a piece is occupying this square...\r\n \t\t\t\t\tif Piece.pos[1] == y and Piece.pos[0] == x:\r\n \t\t\t\t\t\tif Piece.color != self.color:\r\n \t\t\t\t\t\t\tPiece.kill()\r\n \t\t\t\t\t\t\tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n \t\t\t\t\t\t\tself.pos = MousePosition\r\n \t\t\t\t\t\t\treturn True\r\n \t\t\t\t\t\telse:\r\n \t\t\t\t\t\t\t#print(\"End piece collision!\")\r\n \t\t\t\t\t\t\tself.ResetPiece()\r\n \t\t\t\t\t\t\treturn False\r\n \t\t\t\t#No pieces occupy the end space\r\n \t\t\t\tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n \t\t\t\tself.pos = MousePosition\r\n \t\t\t\treturn True\r\n \t\t\r\n \t\t\t#check if any of the pieces...\r\n \t\t\tfor Piece in AllPieces:\r\n \t\t\t\t#...happen to be on this square\r\n \t\t\t\tif Piece.pos[1] == y and Piece.pos[0] == x:\r\n \t\t\t\t\t#this is a collision\r\n \t\t\t\t\t#print(\"intermediate collision\")\r\n \t\t\t\t\tself.ResetPiece()\r\n \t\t\t\t\treturn False\r\n \r\n \t#checking if diagonal positive positive movment is happening \r\n \tif self.pos[0] < MousePosition[0] and self.pos[1] < MousePosition[1]:\r\n \t\t#we need to loop through every square here\r\n \t\tx = self.pos[0]\r\n \t\ty = self.pos[1]\r\n \t\twhile x != MousePosition[0]:\r\n \t\t\tx += SQUARE_WIDTH\r\n \t\t\ty += SQUARE_HEIGHT\r\n \t\t\t#if we are on the last square\r\n \t\t\tif x == MousePosition[0]:\r\n \t\t\t\tfor Piece in AllPieces:\r\n \t\t\t\t\t#if a piece is occupying this square...\r\n \t\t\t\t\tif Piece.pos[1] == y and Piece.pos[0] == x:\r\n \t\t\t\t\t\tif Piece.color != self.color:\r\n \t\t\t\t\t\t\tPiece.kill()\r\n \t\t\t\t\t\t\tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n \t\t\t\t\t\t\tself.pos = MousePosition\r\n \t\t\t\t\t\t\treturn True\r\n \t\t\t\t\t\telse:\r\n \t\t\t\t\t\t\t#print(\"End piece collision!\")\r\n \t\t\t\t\t\t\tself.ResetPiece()\r\n \t\t\t\t\t\t\treturn False\r\n \t\t\t\t#No pieces occupy the end space\r\n \t\t\t\tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n \t\t\t\tself.pos = MousePosition\r\n \t\t\t\treturn True\r\n \t\t\r\n \t\t\t#check if any of the pieces...\r\n \t\t\tfor Piece in AllPieces:\r\n \t\t\t\t#...happen to be on this square\r\n \t\t\t\tif Piece.pos[1] == y and Piece.pos[0] == x:\r\n \t\t\t\t\t#this is a collision\r\n \t\t\t\t\t#print(\"intermediate collision\")\r\n \t\t\t\t\tself.ResetPiece()\r\n \t\t\t\t\treturn False\r\n \r\n #checking if vertical negative movment is legal\r\n elif self.pos[0] == MousePosition[0] and self.pos[1] > MousePosition[1]:\r\n \t#we need to loop through every square here\r\n \tx = self.pos[1]\r\n \twhile x != MousePosition[1]:\r\n \t\tx -= SQUARE_HEIGHT\r\n \t\t#if we are on the last square\r\n \t\tif x == MousePosition[1]:\r\n \t\t\tfor Piece in AllPieces:\r\n \t\t\t\t#if a piece is occupying this square...\r\n \t\t\t\tif Piece.pos[0] == self.pos[0] and Piece.pos[1] == x:\r\n \t\t\t\t\tif Piece.color != self.color:\r\n \t\t\t\t\t\tPiece.kill()\r\n \t\t\t\t\t\tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n \t\t\t\t\t\tself.pos = MousePosition\r\n \t\t\t\t\t\treturn True\r\n \t\t\t\t\telse:\r\n \t\t\t\t\t\t#print(\"End piece collision!\")\r\n \t\t\t\t\t\tself.ResetPiece()\r\n \t\t\t\t\t\treturn False\r\n \t\t\t#No pieces occupy the end space\r\n \t\t\tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n \t\t\tself.pos = MousePosition\r\n \t\t\treturn True\r\n \t\t\r\n \t\t#check if any of the pieces...\r\n \t\tfor Piece in AllPieces:\r\n \t\t\t#...happen to be on this square\r\n \t\t\tif Piece.pos[0] == self.pos[0] and Piece.pos[1] == x:\r\n \t\t\t\t#this is a collision\r\n \t\t\t\t#print(\"intermediate collision\")\r\n \t\t\t\tself.ResetPiece()\r\n \t\t\t\treturn False\r\n #checking if vertical positive movment is legal\r\n elif self.pos[0] == MousePosition[0] and self.pos[1] < MousePosition[1]:\r\n \t#we need to loop through every square here\r\n \tx = self.pos[1]\r\n \twhile x != MousePosition[1]:\r\n \t\tx += SQUARE_HEIGHT\r\n \t\t#if we are on the last square\r\n \t\tif x == MousePosition[1]:\r\n \t\t\tfor Piece in AllPieces:\r\n \t\t\t\t#if a piece is occupying this square...\r\n \t\t\t\tif Piece.pos[0] == self.pos[0] and Piece.pos[1] == x:\r\n \t\t\t\t\tif Piece.color != self.color:\r\n \t\t\t\t\t\tPiece.kill()\r\n \t\t\t\t\t\tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n \t\t\t\t\t\tself.pos = MousePosition\r\n \t\t\t\t\t\treturn True\r\n \t\t\t\t\telse:\r\n \t\t\t\t\t\t#print(\"End piece collision!\")\r\n \t\t\t\t\t\tself.ResetPiece()\r\n \t\t\t\t\t\treturn False\r\n \t\t\t#No pieces occupy the end space\r\n \t\t\tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n \t\t\tself.pos = MousePosition\r\n \t\t\treturn True\r\n \t\t\r\n \t\t#check if any of the pieces...\r\n \t\tfor Piece in AllPieces:\r\n \t\t\t#...happen to be on this square\r\n \t\t\tif Piece.pos[0] == self.pos[0] and Piece.pos[1] == x:\r\n \t\t\t\t#this is a collision\r\n \t\t\t\t#print(\"intermediate collision\")\r\n \t\t\t\tself.ResetPiece()\r\n \t\t\t\treturn False\r\n #checking if horizontal positive movment is legal\r\n elif self.pos[1] == MousePosition[1] and self.pos[0] < MousePosition[0]:\r\n \t#we need to loop through every square here\r\n \tx = self.pos[0]\r\n \twhile x != MousePosition[0]:\r\n \t\tx += SQUARE_WIDTH\r\n \t\t#if we are on the last square\r\n \t\tif x == MousePosition[0]:\r\n \t\t\tfor Piece in AllPieces:\r\n \t\t\t\t#if a piece is occupying this square...\r\n \t\t\t\tif Piece.pos[1] == self.pos[1] and Piece.pos[0] == x:\r\n \t\t\t\t\tif Piece.color != self.color:\r\n \t\t\t\t\t\tPiece.kill()\r\n \t\t\t\t\t\tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n \t\t\t\t\t\tself.pos = MousePosition\r\n \t\t\t\t\t\treturn True\r\n \t\t\t\t\telse:\r\n \t\t\t\t\t\t#print(\"End piece collision!\")\r\n \t\t\t\t\t\tself.ResetPiece()\r\n \t\t\t\t\t\treturn False\r\n \t\t\t#No pieces occupy the end space\r\n \t\t\tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n \t\t\tself.pos = MousePosition\r\n \t\t\treturn True\r\n \t\t\r\n \t\t#check if any of the pieces...\r\n \t\tfor Piece in AllPieces:\r\n \t\t\t#...happen to be on this square\r\n \t\t\tif Piece.pos[1] == self.pos[1] and Piece.pos[0] == x:\r\n \t\t\t\t#this is a collision\r\n \t\t\t\t#print(\"intermediate collision\")\r\n \t\t\t\tself.ResetPiece()\r\n \t\t\t\treturn False\r\n #checking if horizontal negative movment is legal\r\n elif self.pos[1] == MousePosition[1] and self.pos[0] > MousePosition[0]:\r\n \t#we need to loop through every square here\r\n \tx = self.pos[0]\r\n \twhile x != MousePosition[0]:\r\n \t\tx -= SQUARE_WIDTH\r\n \t\t#if we are on the last square\r\n \t\tif x == MousePosition[0]:\r\n \t\t\tfor Piece in AllPieces:\r\n \t\t\t\t#if a piece is occupying this square...\r\n \t\t\t\tif Piece.pos[1] == self.pos[1] and Piece.pos[0] == x:\r\n \t\t\t\t\tif Piece.color != self.color:\r\n \t\t\t\t\t\tPiece.kill()\r\n \t\t\t\t\t\tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n \t\t\t\t\t\tself.pos = MousePosition\r\n \t\t\t\t\t\treturn True\r\n \t\t\t\t\telse:\r\n \t\t\t\t\t\t#print(\"End piece collision!\")\r\n \t\t\t\t\t\tself.ResetPiece()\r\n \t\t\t\t\t\treturn False\r\n \t\t\t#No pieces occupy the end space\r\n \t\t\tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n \t\t\tself.pos = MousePosition\r\n \t\t\treturn True\r\n \t\t\r\n \t\t#check if any of the pieces...\r\n \t\tfor Piece in AllPieces:\r\n \t\t\t#...happen to be on this square\r\n \t\t\tif Piece.pos[1] == self.pos[1] and Piece.pos[0] == x:\r\n \t\t\t\t#this is a collision\r\n \t\t\t\t#print(\"intermediate collision\")\r\n \t\t\t\tself.ResetPiece()\r\n \t\t\t\treturn False\r\n else:\r\n \tself.ResetPiece()\r\n \treturn False\r\n \t\t\r\n def ResetPiece(self):\r\n \tself.rect = self.surf.get_rect(center = self.pos)\r\n\r\nclass Knight(pygame.sprite.Sprite):\r\n def __init__(self, png, pos, color):\r\n super(Knight, self).__init__()\r\n self.surf = pygame.image.load(png)\r\n self.surf.set_colorkey((0, 0, 0), RLEACCEL)\r\n self.clicked = False\r\n self.pos = pos\r\n self.rect = self.surf.get_rect(center = self.pos)\r\n self.color = color \r\n def GetCornerPos(self):\r\n \treturn (self.rect.x, self.rect.y)\r\n def UpdatePos(self, MousePosition):\r\n \tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n def PlacePiece(self, MousePosition):\r\n \t#the knight has 8 possible moves... hard code?\r\n \t#top and bottom two moves\r\n \tif (self.pos[1] + SQUARE_HEIGHT*2 == MousePosition[1] or self.pos[1] - SQUARE_HEIGHT*2 == MousePosition[1]):\r\n \t\tif (self.pos[0] + SQUARE_WIDTH == MousePosition[0] or self.pos[0] - SQUARE_WIDTH == MousePosition[0]):\r\n \t\t\tfor Piece in AllPieces:\r\n \t\t\t\tif MousePosition[0] == Piece.pos[0] and MousePosition[1] == Piece.pos[1]:\r\n \t\t\t\t\tif Piece.color != self.color:\r\n \t\t\t\t\t\tPiece.kill()\r\n \t\t\t\t\telse:\r\n \t\t\t\t\t\tself.ResetPiece()\r\n \t\t\t\t\t\treturn False\r\n \t\t\tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n \t\t\tself.pos = MousePosition\r\n \t\t\treturn True\r\n\r\n #left and right two moves\r\n \tif (self.pos[0] + SQUARE_WIDTH*2 == MousePosition[0] or self.pos[0] - SQUARE_WIDTH*2 == MousePosition[0]):\r\n \t\tif (self.pos[1] + SQUARE_HEIGHT == MousePosition[1] or self.pos[1] - SQUARE_HEIGHT == MousePosition[1]):\r\n \t\t\tfor Piece in AllPieces:\r\n \t\t\t\tif MousePosition[0] == Piece.pos[0] and MousePosition[1] == Piece.pos[1]:\r\n \t\t\t\t\tif Piece.color != self.color:\r\n \t\t\t\t\t\tPiece.kill()\r\n \t\t\t\t\telse:\r\n \t\t\t\t\t\tself.ResetPiece()\r\n \t\t\t\t\t\treturn False\r\n \t\t\tself.rect = self.surf.get_rect(center = (MousePosition[0],MousePosition[1]))\r\n \t\t\tself.pos = MousePosition\r\n \t\t\treturn True\r\n\r\n \tself.ResetPiece()\r\n \treturn False\r\n def ResetPiece(self):\r\n \tself.rect = self.surf.get_rect(center = self.pos)\r\n#######UNATTRACTIVE INITILIZATION!#######################\r\nscreen = BoardSetup()\r\nAllPieces = pygame.sprite.Group()\r\nWhitePieces = pygame.sprite.Group()\r\nBlackPieces = pygame.sprite.Group()\r\n###Kings###\r\ndef PieceInit(WRookImg, WKnightImg, WBishopImg, WQueenImg, WKingImg, WPawnImg, BRookImg, BKnightImg, BBishopImg, BQueenImg, BKingImg, BPawnImg):\r\n\tWKing = King(WKingImg, (288,480), WHITE)\r\n\tWhitePieces.add(WKing)\r\n\tAllPieces.add(WKing)\r\n\tBKing = King(BKingImg, (288,32), BLACK)\r\n\tBlackPieces.add(BKing)\r\n\tAllPieces.add(BKing)\r\n\t###Queens###\r\n\tWQueen = Queen(WQueenImg, (224,480), WHITE)\r\n\tWhitePieces.add(WQueen)\r\n\tAllPieces.add(WQueen)\r\n\tBQueen = Queen(BQueenImg, (224,32), BLACK)\r\n\tBlackPieces.add(BQueen)\r\n\tAllPieces.add(BQueen)\r\n\t###all pawns#######\r\n\tfor square in range(0,8):\r\n\t\tx = Pawn(BPawnImg, (SQUARE_HEIGHT*square +32 ,96), BLACK, True)\r\n\t\tBlackPieces.add(x)\r\n\t\tAllPieces.add(x)\r\n\r\n\t\tx = Pawn(WPawnImg, (SQUARE_HEIGHT*square + 32,416), WHITE, True)\r\n\t\tWhitePieces.add(x)\r\n\t\tAllPieces.add(x)\r\n\t###Rook###\r\n\tfor square in range(0,2):\r\n\t\tx = Rook(BRookImg, (((512-SQUARE_HEIGHT)*square + 32), 32), BLACK)\r\n\t\tBlackPieces.add(x)\r\n\t\tAllPieces.add(x)\r\n\r\n\t\tx = Rook(WRookImg, (((512-SQUARE_HEIGHT)*square + 32), (512-32)), WHITE)\r\n\t\tWhitePieces.add(x)\r\n\t\tAllPieces.add(x)\r\n\t###Knight###\r\n\tfor square in range(0,2):\r\n\t\tx = Knight(BKnightImg, (((512-SQUARE_HEIGHT*3)*square + 32 + SQUARE_HEIGHT), 32), BLACK)\r\n\t\tBlackPieces.add(x)\r\n\t\tAllPieces.add(x)\r\n\r\n\t\tx = Knight(WKnightImg, (((512-SQUARE_HEIGHT*3)*square + 32 + SQUARE_HEIGHT), (512-32)), WHITE)\r\n\t\tWhitePieces.add(x)\r\n\t\tAllPieces.add(x)\r\n\t\t###all bishops###\r\n\tfor square in range(0,2):\r\n\t\tx = Bishop(BBishopImg, (SQUARE_HEIGHT*3*square +32 + SQUARE_HEIGHT*2 ,32), BLACK)\r\n\t\tBlackPieces.add(x)\r\n\t\tAllPieces.add(x)\r\n\r\n\t\tx = Bishop(WBishopImg, (SQUARE_HEIGHT*3*square +32 + SQUARE_HEIGHT*2 ,480), WHITE)\r\n\t\tWhitePieces.add(x)\r\n\t\tAllPieces.add(x)\r\n\treturn (WKing, BKing)\r\n#################################################################\r\nprint(\"Welcome to chess ui - a CS Project!\")\r\nlolSkin = input(\"Would you like to play with a league skin? (y/n)\")\r\nif lolSkin == \"y\":\r\n\tWRookImg = \"Assets/WhiteLeaguePieces/FioraSquare.png\"\r\n\tWKnightImg = \"Assets/WhiteLeaguePieces/QuinnSquare.png\"\r\n\tWBishopImg = \"Assets/WhiteLeaguePieces/LuxSquare.png\"\r\n\tWQueenImg = \"Assets/WhiteLeaguePieces/GarenSquare.png\"\r\n\tWKingImg = \"Assets/WhiteLeaguePieces/Jarvan_IVSquare.png\"\r\n\tWPawnImg = \"Assets/WhiteLeaguePieces/GalioSquare.png\"\r\n\tBRookImg = \"Assets/BlackLeaguePieces/SionSquare.png\"\r\n\tBKnightImg = \"Assets/BlackLeaguePieces/KledSquare.png\"\r\n\tBBishopImg = \"Assets/BlackLeaguePieces/DravenSquare.png\"\r\n\tBQueenImg = \"Assets/BlackLeaguePieces/DariusSquare.png\"\r\n\tBKingImg = \"Assets/BlackLeaguePieces/SwainSquare.png\"\r\n\tBPawnImg = \"Assets/BlackLeaguePieces/UrgotSquare.png\"\r\nelse:\r\n\tWRookImg = \"Assets/WhitePieces/WhiteRook.png\"\r\n\tWKnightImg = \"Assets/WhitePieces/WhiteKnight.png\"\r\n\tWBishopImg = \"Assets/WhitePieces/WhiteBishop.png\"\r\n\tWQueenImg = \"Assets/WhitePieces/WhiteQueen.png\"\r\n\tWKingImg = \"Assets/WhitePieces/WhiteKing.png\"\r\n\tWPawnImg = \"Assets/WhitePieces/WhitePawn.png\"\r\n\tBRookImg = \"Assets/BlackPieces/BlackRook.png\"\r\n\tBKnightImg = \"Assets/BlackPieces/BlackKnight.png\"\r\n\tBBishopImg = \"Assets/BlackPieces/BlackBishop.png\"\r\n\tBQueenImg = \"Assets/BlackPieces/BlackQueen.png\"\r\n\tBKingImg = \"Assets/BlackPieces/BlackKing.png\"\r\n\tBPawnImg = \"Assets/BlackPieces/BlackPawn.png\"\r\nkings = PieceInit(WRookImg, WKnightImg, WBishopImg, WQueenImg, WKingImg, WPawnImg, BRookImg, BKnightImg, BBishopImg, BQueenImg, BKingImg, BPawnImg)\r\nWKing = kings[0]\r\nBKing = kings[1] \r\nRunning = True\r\nwhile Running:\r\n\tLegalMove = False\r\n\tBoardSetup()\r\n\t#starts by assuming that checkmate has been delivered.\r\n\tKingAlive = False\r\n\tfor Piece in AllPieces:\r\n\t\tscreen.blit(Piece.surf, Piece.rect)\r\n\t\tif TURNCOUNT % 2 == 0 and Piece == WKing:\r\n\t\t\tKingAlive = True\r\n\t\telif TURNCOUNT % 2 == 1 and Piece == BKing:\r\n\t\t\tKingAlive = True\r\n\tif not KingAlive:\r\n\t\tif TURNCOUNT % 2 == 0:\r\n\t\t\tprint(\"Black Wins!\")\r\n\t\t\tRunning = False\r\n\t\telse:\r\n\t\t\tprint(\"White Wins!\")\r\n\t\t\tRunning = False\r\n\t\r\n # Did the user click the window close button\r\n\tfor event in pygame.event.get():\r\n\t\tif pygame.mouse.get_pressed()[0]:\r\n\t\t\tfor Piece in AllPieces:\r\n\t\t\t\tif moving_piece == Piece or moving_piece == None:\r\n\t\t\t\t\t#if mouse is hovering over piece\r\n\t\t\t\t\tif ((pygame.mouse.get_pos()[0] > Piece.GetCornerPos()[0])\r\n\t\t\t\t\tand (pygame.mouse.get_pos()[0] < Piece.GetCornerPos()[0] + SQUARE_WIDTH)\r\n\t\t\t\t\tand ((pygame.mouse.get_pos()[1] > Piece.GetCornerPos()[1])\r\n\t\t\t\t\tand (pygame.mouse.get_pos()[1] < Piece.GetCornerPos()[1] + SQUARE_HEIGHT))\r\n\t\t\t\t\tand TURNCOUNT%2 == Piece.color):\r\n\t\t\t\t\t\tPiece.UpdatePos(pygame.mouse.get_pos())\r\n\t\t\t\t\t\tmoving_piece = Piece\r\n\t\t#realese off mouse button\r\n\t\telif pygame.MOUSEBUTTONUP and (moving_piece != None):\r\n\r\n\t\t\tpos = pygame.mouse.get_pos()\r\n\t\t\tLegalMove = moving_piece.PlacePiece(((int(pos[0]/SQUARE_WIDTH)*SQUARE_WIDTH+SQUARE_WIDTH/2),\r\n\t\t\t\t\t\t\t\t(int(pos[1]/SQUARE_HEIGHT)*SQUARE_HEIGHT+SQUARE_HEIGHT/2)))\r\n\t\t\t\r\n\t\t\t#this returns the coordinate of the center!\r\n \t\r\n\t\t\tmoving_piece = None\r\n\t\telif event.type == pygame.QUIT:\r\n\t\t\tRunning = False\t\t\r\n\tif LegalMove == True:\r\n\t\tTURNCOUNT += 1\r\n # Flip the display\r\n\tpygame.display.update()\r\n\tpygame.display.flip()\r\n\t\r\n# Done! Time to quit.\r\npygame.quit()"} {"blob_id": "0a92482958ef8d95000e67c1464b1b08989dd114", "repo_name": "rbenua/AdventOfCode", "path": "/2018/9/part2.py", "length_bytes": 1547, "score": 3.734375, "int_score": 4, "content": "#!/usr/bin/env python3\n\nimport sys\n\nclass Node:\n def __init__(self, value):\n self.prev = self\n self.next = self\n self.value = value\n\n def insert(self, value):\n new = Node(value)\n new.prev = self\n new.next = self.next\n self.next.prev = new\n self.next = new\n return new\n \n def remove(self):\n self.next.prev = self.prev\n self.prev.next = self.next\n return (self.next, self.value)\n\n def fseek(self, i):\n if i == 0:\n return self\n return self.next.fseek(i-1)\n\n def bseek(self, i):\n if i == 0:\n return self\n return self.prev.bseek(i-1)\n\nplayers = int(sys.argv[1])\nmarbles = int(sys.argv[2]) + 1\n\nscores = [0] * players\n\ncurr = Node(0)\nzero = curr\n\ndef printlist():\n n = zero\n print(\"{:2}{}\".format(n.value, (\" \",\"*\")[n == curr]), end=\"\")\n n = n.next\n while n != zero:\n print(\"{:2}{}\".format(n.value, (\" \",\"*\")[n == curr]), end=\"\")\n n = n.next\n print()\n\nfor marble in range(1, marbles):\n if marble % 1000 == 0:\n pass\n #print(\"processed {} marbles\".format(marble))\n player = marble % players\n if marble % 23 == 0:\n curr = curr.bseek(7)\n (curr, removed) = curr.remove()\n scores[player] += removed + marble\n #print(\"player {} kept {} and removed {}, total score {}\".format(player, marble, removed, scores[player]))\n else:\n curr = curr.fseek(1)\n curr = curr.insert(marble)\n #printlist()\n\nprint(max(scores))\n"} {"blob_id": "019beaae8157ed24ea6949a88dace15d17304d10", "repo_name": "valegui/redes_neuronales", "path": "/tarea1/Perceptrons/NeuralNetwork.py", "length_bytes": 4596, "score": 3.59375, "int_score": 4, "content": "import numpy as np\nfrom utils import *\nfrom Perceptron import Perceptron\nfrom NeuronLayer import NeuronLayer\nfrom Activation import Step, Sigmoid, Tanh\n\n\nclass NeuralNetwork:\n \"\"\"\n NeuralNetwork class\n \"\"\"\n def __init__(self, f, n_n_porcapa, n_capas, o):\n \"\"\"\n class constructor\n :param f: number of inputs\n :param n_n_porcapa: number of neurons per hidden layer\n :param n_capas: number of hidden layers\n :param o: number of outputs\n \"\"\"\n assert len(n_n_porcapa) == n_capas, \\\n \"Wrong input for the Neural Network\"\n\n layers = [NeuronLayer(n=n_n_porcapa[0], ni=f)]\n\n for n, ni in zip(n_n_porcapa[1:], n_n_porcapa):\n layers.append(NeuronLayer(n=n, ni=ni))\n layers.append(NeuronLayer(n=o, ni=n_n_porcapa[-1]))\n\n self.f = f\n self.n_layers = n_capas + 1\n self.layers = np.asarray(layers)\n\n self.set_last_layer()\n self.set_sibling_layers()\n\n def set_sibling_layers(self):\n \"\"\"\n sets next end previous layer for every layer\n :return:\n \"\"\"\n for i in range(self.n_layers - 1):\n self.layers[i].set_next_layer(self.layers[i + 1])\n self.layers[i + 1].set_prev_layer(self.layers[i])\n\n def set_last_layer(self):\n \"\"\"\n sets is_output value as True in the output layer\n :return:\n \"\"\"\n self.layers[-1].is_output = True\n\n def feed(self, inputs):\n \"\"\"\n feeds the neural network, starting from the first hidden\n layer\n :param inputs: input of the network\n :return: the output value\n \"\"\"\n assert len(inputs) == self.f,\\\n f'Mismatched lengths: expected {self.f}, got {len(inputs)}'\n assert np.issubdtype(np.asarray(inputs).dtype, np.number),\\\n \"Input type not numeric\"\n return self.layers[0].feed(np.asarray(inputs))\n\n def train(self, inputs, expected):\n \"\"\"\n trains the neural network, with the feed forward and\n the backpropagation stage\n :param inputs: input of the neural network\n :param expected: expected output of the network\n :return: square error after one forward and backward\n \"\"\"\n _ = self.feed(inputs)\n self.backpropagate_error(np.asarray(expected))\n self.update_weights(inputs)\n\n err = np.asarray(expected) - self.feed(inputs)\n return np.sum(err**2)\n\n def backpropagate_error(self, expected):\n \"\"\"\n backpropagates the error, starting in the output layer\n :param expected: expected output of the network\n :return:\n \"\"\"\n self.layers[-1].backpropagate_error(expected)\n\n def update_weights(self, inputs):\n \"\"\"\n updates the weights, starting in the first layer, for the\n backpropagation stage\n :param inputs: input of the neural network\n :return:\n \"\"\"\n self.layers[0].update_weights(inputs)\n\n def load_weights(self, weights):\n \"\"\"\n load pre computed weights for every layer of the network\n :param weights: new weights\n :return:\n \"\"\"\n assert len(weights) == self.n_layers,\\\n \"Length of weights does not match the number of layers\"\n\n for layer, w in zip(self.layers, weights):\n layer.load_weights(w)\n\n def set_activation(self, activations):\n \"\"\"\n sets the corresponding activation function to every layer\n of the network\n :param activations: list of activation functions\n :return:\n \"\"\"\n assert len(activations) == self.n_layers,\\\n \"Length of activations does not match the number of layers\"\n for layer, act in zip(self.layers, activations):\n layer.set_activation(act)\n\n def set_learning_rate(self, learning_rates):\n \"\"\"\n sets the corresponding learning rate to every layer of the\n network\n :param learning_rates: list of learning rates\n :return:\n \"\"\"\n assert len(learning_rates) == self.n_layers,\\\n \"Length of learning rates does not match the number of layers\"\n assert np.issubdtype(np.asarray(learning_rates).dtype, np.number), \\\n \"Input type not numeric\"\n for layer, lr in zip(self.layers, learning_rates):\n layer.set_learning_rate(lr)\n\n def get_last_activation(self):\n \"\"\"\n gets the activation object of the output layer\n :return: the activation object\n \"\"\"\n return self.layers[-1].get_activation()\n"} {"blob_id": "6e83c0ca10ad51d8347fe4398ed02b3590937ac9", "repo_name": "kgisl/pythonFDP", "path": "/code/mergesort.py", "length_bytes": 1184, "score": 4.1875, "int_score": 4, "content": "import itertools\n\n# http://j.mp/zipLongest\n\n\ndef mergesort(series):\n '''iterative mergesort implementation\n\n @author kgashok\n @param series is a sequence of unsorted elements\n\n @returns a list containing sorted elements\n\n Testable docstring? https://docs.python.org/2/library/doctest.html\n\n >>> mergesort([5, 4, 2, 8, 1, 3, 7, 6])\n [[5], [4], [2], [8], [1], [3], [7], [6]]\n [[4, 5], [2, 8], [1, 3], [6, 7]]\n [[2, 4, 5, 8], [1, 3, 6, 7]]\n [1, 2, 3, 4, 5, 6, 7, 8]\n '''\n def merge(A, B):\n merged = [\n (A if A[0] < B[0] else B).pop(0)\n for _ in A + B if len(A) and len(B)\n ] + A + B\n return merged\n\n iseries = iseries = [[i] for i in series]\n while len(iseries) > 1:\n # print(\"\\n\", iseries)\n print(iseries)\n ilist = iter(iseries)\n iseries = [merge(a, b) if b else a\n for a, b in itertools.zip_longest(ilist, ilist)]\n\n return iseries[0]\n\n\nprint(\"1st test\")\nprint(mergesort([5, 4, 2, 8, 1, 3, 7, 6]))\nprint(\"2nd test\")\nprint(mergesort([1, 2, 3, 4, -1, -100, 290, 22, 5]))\n\n\nif __name__ == \"__main__\":\n # import doctest\n # doctest.testmod()\n pass\n"} {"blob_id": "975073430e7e3c71b57ab4a6dac6c00d494891ae", "repo_name": "smallt-TAO/LeetCode-On-The-Way", "path": "/Binary Search/Recover Binary Search Tree/Solution.py", "length_bytes": 1211, "score": 3.765625, "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\nclass Solution(object):\n def recoverTree(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: void Do not return anything, modify root in-place instead.\n \"\"\"\n prev = None\n first = None\n second = None\n if root.left:\n buf = root.left\n while buf.right != root and buf.right:\n buf = buf.right\n if buf.right:\n buf.right = root\n root = root.left\n else:\n if prev and prev.val > root.val:\n if not first:\n first = prev\n second = root\n prev = root\n buf.right = None\n root = root.right\n else:\n if prev and prev.val > root.val:\n if not first:\n first = prev\n second = root\n prev = root\n root = root.right\n \n if first:\n first.val, second.val = second.val, first.val\n \n"} {"blob_id": "278eb36608b1c4dab02b99c46c75316925683eef", "repo_name": "arnabs542/DS-AlgoPrac", "path": "/queues/sumMinMaxWindow.py", "length_bytes": 1202, "score": 3.8125, "int_score": 4, "content": "\"\"\"Sum of minimum and maximum elements of all subarrays of size k\nGiven an array A of both positive and negative integers. Your task is to compute sum of minimum and maximum elements of all sub-array of size B. Note: Since the answer can be very large, you are required to return the sum module 1000000007. \nInput Format\nThe first argument denotes the array A.\nThe second argument denotes the value B\nOutput Format\nReturn an integer that denotes the required value.\nConstraints\n1 <= size of array A <= 100000\n-1000000000 <= A[i] <= 1000000000\n1 <= B <= size of array\n** Example**\nExample Input 1:\n A[] = {2, 5, -1, 7, -3, -1, -2}\n B = 4\n\nExample Output 1:\n 18\nExplanation : \n Subarrays of size 4 are : \n {2, 5, -1, 7}, min + max = -1 + 7 = 6\n {5, -1, 7, -3}, min + max = -3 + 7 = 4 \n {-1, 7, -3, -1}, min + max = -3 + 7 = 4\n {7, -3, -1, -2}, min + max = -3 + 7 = 4 \n Sum of all min & max = 6 + 4 + 4 + 4 \n = 18 \n\"\"\"\n\nfrom maxEleWindow import maxEleWindow\nfrom minEleWindow import minEleWindow\ndef solve(A, B):\n first = maxEleWindow(A,B)\n second = minEleWindow(A,B)\n return (sum(first)+sum(second))%1000000007"} {"blob_id": "6e607f8c597d08ac6224d9e69c443ccf2ac1fd23", "repo_name": "ritwiktiwari/AlgorithmsDataStructures", "path": "/Graph/ShortestPathAlgorithms/Dijkstra.py", "length_bytes": 1970, "score": 3.65625, "int_score": 4, "content": "import heapq\nfrom collections import defaultdict\nfrom sys import maxsize\n\n\nclass Graph:\n def __init__(self, n):\n self.graph = defaultdict(list)\n self.n = n\n\n def add_edge(self, u, v, weight):\n self.graph[u].append((v, weight))\n\n def printer(self):\n print(f\"U\\tV\\tW\")\n print(f\"-\" * 10)\n n = max(self.graph) + 1\n for i in range(n):\n for j in self.graph[i]:\n print(f\"{i}\\t{j[0]}\\t{j[1]}\")\n print(f\"-\" * 10)\n\n def dijkstra(self, start, end):\n visited = [False] * self.n\n previous = [None] * self.n\n distance = [maxsize] * self.n\n\n distance[start] = 0\n q = []\n heapq.heappush(q, (start, 0))\n\n while len(q) != 0:\n index, min_value = heapq.heappop(q)\n visited[index] = True\n if distance[index] < min_value:\n continue\n for edge in self.graph[index]:\n if visited[edge[0]]:\n continue\n new_distance = distance[index] + edge[1]\n if new_distance < distance[edge[0]]:\n distance[edge[0]] = new_distance\n previous[edge[0]] = index\n try:\n heapq.heapreplace(q, (edge[0], new_distance))\n except IndexError:\n heapq.heappush(q, (edge[0], new_distance))\n if index == end:\n return distance, previous\n return distance, previous\n\n def find_shortest_path(self, start, end):\n distance, previous = self.dijkstra(start, end)\n path = []\n if distance[end] == maxsize:\n return path\n at = end\n while at is not None:\n path.append(at)\n at = previous[at]\n\n return list(reversed(path))\n\n\ng = Graph(3)\ng.add_edge(0, 1, 1)\ng.add_edge(0, 2, 2)\ng.add_edge(1, 2, 3)\n\ng.printer()\nprint(g.find_shortest_path(0, 2))\n"} {"blob_id": "7c03880d193285cf1237fdc99619833fdbb7d216", "repo_name": "K753951/UCSanDiego-Advanced-Algorithms", "path": "/Bipartite_Matching/bipartitematch.py", "length_bytes": 10210, "score": 4.03125, "int_score": 4, "content": "import sys\r\nimport numpy as np\r\n\r\n\r\nclass Node:\r\n def __init__(self, index, start, end, capacity, flow, pointer, parent):\r\n self.index = index\r\n self.start = start\r\n self.end = end\r\n self.capacity = capacity\r\n self.flow = flow\r\n self.pointer = pointer\r\n self.parent = parent\r\n\r\n\r\nclass MasterList:\r\n \"\"\" Stores information for all roads. A static data structure. \"\"\"\r\n def __init__(self):\r\n self.master = []\r\n\r\n def add_node(self, index, start, end, capacity):\r\n new_node = Node(index=index, start=start, end=end, capacity=capacity, flow=0, pointer=index + 1, parent=None)\r\n self.master.append(new_node)\r\n residual = Node(index=index + 1, start=end, end=start, capacity=0, flow=0, pointer=index, parent=None)\r\n self.master.append(residual)\r\n\r\n\r\nclass QueueFrontier:\r\n \"\"\" A dynamic data structure used to repeatedly find paths between cities. \"\"\"\r\n def __init__(self):\r\n self.queue = []\r\n\r\n def add_to_queue(self, pointer):\r\n self.queue.append(pointer)\r\n\r\n def pop(self):\r\n node = self.queue[0]\r\n self.queue = self.queue[1:]\r\n return node\r\n\r\n\r\nclass EasyAccess:\r\n \"\"\" A 2D numpy array to hold pointers to roads that start/end at particular cities. Row index corresponds to\r\n index of starting city. Column index corresponds to index of ending city. \"\"\"\r\n def __init__(self, n):\r\n self.numpy_array = np.empty(n, dtype=list)\r\n\r\n def add_entry(self, start, pointer):\r\n if self.numpy_array[start] is None:\r\n new_list = [pointer]\r\n self.numpy_array[start] = new_list\r\n else:\r\n list_pointer = self.numpy_array[start]\r\n list_pointer.append(pointer)\r\n\r\n\r\ndef get_path(node_pointer, m_list):\r\n \"\"\" Finds the road with the max (capacity - flow) along the path from road_pointer to capitol. Updates flows\r\n of all roads along path. Updates capacity of residual roads. Returns the flow that has been added. \"\"\"\r\n\r\n # Make a list to hold remaining capacities of roads along the path.\r\n capacity = []\r\n\r\n # Make a list to hold path.\r\n path = []\r\n\r\n # Make a list to hold path indexes.\r\n path_indexes = []\r\n\r\n while True:\r\n # First, find the entry for road in the master list.\r\n node = m_list.master[node_pointer]\r\n\r\n # Add the remaining capacity of the terminal node to the capacity list.\r\n remaining_capacity = node.capacity - node.flow\r\n capacity.append(remaining_capacity)\r\n\r\n # Add the node to the path list.\r\n path.append(node)\r\n path_indexes.append(node.index)\r\n\r\n # Find if the node has a parent. If yes, set road_pointer to point to this entry in the master list\r\n # and continue looping. If no, break.\r\n if node.parent is not None:\r\n p = m_list.master[node.parent]\r\n if p.capacity - p.flow > 0:\r\n node_pointer = node.parent\r\n\r\n # If we have reached this point without moving to the parent, there is no path. Return 0.\r\n else:\r\n return None\r\n else:\r\n break\r\n\r\n # Find the max remaining capacity.\r\n maximum = min(capacity)\r\n\r\n # Update the flows of all nodes along the path and their residual nodes.\r\n for x in path:\r\n\r\n # Update the flow.\r\n x.flow += maximum\r\n\r\n # Update the capacity of the residual.\r\n res = m_list.master[x.pointer]\r\n res.capacity += maximum\r\n\r\n return path_indexes\r\n\r\n\r\ndef find_path_capacity(masterlist, ez, n):\r\n \"\"\" Finds the maximum capacity of a path through the graph and updates flows to utilize this path.\r\n Returns the amount of flow added. \"\"\"\r\n # Make an instance of the QueueFrontier class to find shortest paths.\r\n queue = QueueFrontier()\r\n\r\n # Make a list to hold previously explored roads to avoid loops.\r\n explored = []\r\n\r\n # Use a BFS algorithm to explore paths.\r\n # Add all edges beginning at start to the queue.\r\n if ez.numpy_array[0] is not None:\r\n for edge in ez.numpy_array[0]:\r\n r = masterlist.master[edge]\r\n if r.capacity - r.flow > 0:\r\n queue.add_to_queue(edge)\r\n\r\n # Add the road to the explored list.\r\n explored.append(edge)\r\n\r\n # Ensure the parent of these nodes is None.\r\n masterlist.master[edge].parent = None\r\n\r\n # Pop roads from the queue. If the road does not lead the the final destination, add its children to the queue.\r\n while True:\r\n # If the queue is empty and we haven't returned a path, return 0 - no path exists.\r\n if len(queue.queue) is 0:\r\n return None\r\n\r\n # Pop a node from the queue.\r\n popped = queue.pop()\r\n\r\n # Find the road record for the index that was popped.\r\n current_edge = masterlist.master[popped]\r\n\r\n # If the road ends at the evacuation site, find the max capacity that can be added. Add this to total capacity.\r\n if current_edge.end == n:\r\n pathway = get_path(popped, masterlist)\r\n return pathway\r\n\r\n # Add all outgoing roads from end city to the queue. Update their parent pointers to point to popped.\r\n elif ez.numpy_array[current_edge.end] is not None:\r\n for element in ez.numpy_array[current_edge.end]:\r\n\r\n # Check if element has a capacity and has not previously been explored.\r\n record = masterlist.master[element]\r\n if record.capacity is not 0 and record.index not in explored:\r\n\r\n # Check if element's capacity has not been used up. If some capacity left, add index to queue.\r\n if record.capacity - record.flow > 0:\r\n queue.add_to_queue(element)\r\n\r\n # Update parent of added node.\r\n record.parent = popped\r\n\r\n # Add the new node to the explored list.\r\n explored.append(record.index)\r\n\r\n\r\n# Read data from input file.\r\nwith open(sys.argv[1]) as input_file:\r\n\r\n # Get the number of flights and crews from the first line.\r\n first_line = input_file.readline()\r\n first_space = first_line.find(\" \")\r\n backslashn = first_line.find(\"\\n\")\r\n global flights\r\n flights = int(first_line[:first_space])\r\n global crews\r\n crews = int(first_line[first_space + 1:backslashn])\r\n\r\n # Check for proper usage.\r\n if flights < 1 or flights > 100:\r\n raise Exception(\"Invalid number of flights\")\r\n if crews < 1 or crews > 100:\r\n raise Exception(\"Invalid number of crews\")\r\n\r\n # Create edges from data.\r\n global data\r\n data = np.empty([flights, crews], dtype=int)\r\n for i in range(flights):\r\n next_line = input_file.readline()\r\n previous_space = -1\r\n for j in range(crews):\r\n if j < crews - 1:\r\n space = next_line.find(\" \", previous_space + 1)\r\n integer = int(next_line[previous_space + 1:space])\r\n previous_space = space\r\n data[i][j] = integer\r\n elif j == crews - 1:\r\n backslash = next_line.find(\"\\n\")\r\n integer = int(next_line[previous_space + 1:backslash])\r\n data[i][j] = integer\r\n\r\n# Make a masterlist to hold flight data.\r\nmaster_list = MasterList()\r\n\r\n# Make an easyaccess array to hold node data.\r\nnum_nodes = flights + crews + 2\r\neasy = EasyAccess(num_nodes)\r\n\r\n# Add edges to graph and to easyaccess array.\r\ncounter = 0\r\nfor i in range(flights):\r\n for j in range(crews):\r\n if data[i][j] == 1:\r\n master_list.add_node(index=counter, start=i + 1, end=j + flights + 1, capacity=1)\r\n easy.add_entry(start=i + 1, pointer=counter)\r\n easy.add_entry(start=j + flights + 1, pointer=counter + 1)\r\n counter += 2\r\n\r\n# Add paths connecting start (index=0) to all flights. Add paths connecting all crews to\r\n# end (index=flights*crews).\r\ns = 0\r\ne = flights + crews + 1\r\n\r\nfor i in range(flights):\r\n master_list.add_node(index=counter, start=s, end=i + 1, capacity=1)\r\n easy.add_entry(start=s, pointer=counter)\r\n easy.add_entry(start=i + 1, pointer=counter + 1)\r\n counter += 2\r\n\r\nfor j in range(crews):\r\n master_list.add_node(index=counter, start=j + flights + 1, end=e, capacity=1)\r\n easy.add_entry(start=j + flights + 1, pointer=counter)\r\n easy.add_entry(start=e, pointer=counter + 1)\r\n counter += 2\r\n\r\n# Make a list to hold paths.\r\npath_list = []\r\n\r\n# Continue to find paths between flights and crews until no more paths found.\r\nreturned = -1\r\nwhile returned is not None:\r\n returned = find_path_capacity(master_list, easy, e)\r\n if returned is not None:\r\n path_list.extend(returned)\r\n\r\n# Make an array initialized to -1 to hold output data (crew numbers).\r\noutput = np.full(flights, -1)\r\n\r\n# Make a new list to hold valid paths.\r\nnew_list = []\r\n\r\nfor current_edge in path_list:\r\n crew = master_list.master[current_edge].end\r\n crew_id = master_list.master[current_edge].end - flights\r\n flight = master_list.master[current_edge].start\r\n\r\n # First, only consider edges between valid flights and crews (no edges connecting to source or sink).\r\n if flight != 0 and crew != 0 and flight != e and crew != e:\r\n\r\n # Only consider true edges (not residual edges).\r\n if 0 < flight <= flights < crew < e:\r\n\r\n # Find if edge has been cancelled by residual flow.\r\n edge_count = path_list.count(current_edge)\r\n r = master_list.master[current_edge].pointer\r\n residual_count = path_list.count(r)\r\n\r\n # Add edge to new list only if it has not been cancelled by the presence of residual edge(s).\r\n if edge_count > residual_count and current_edge not in new_list:\r\n new_list.append(current_edge)\r\n\r\n# Convert\r\nfor y in new_list:\r\n f = master_list.master[y].start\r\n c = master_list.master[y].end\r\n output[f - 1] = c - flights\r\n\r\n# Convert output to correct format.\r\nfor i in range(flights):\r\n print(output[i], end=\" \")\r\nprint(\"\\n\")\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n"} {"blob_id": "629386bfc5ad5235b353ddd6742370d669309fc3", "repo_name": "harshjohar/unacademy_a", "path": "/assignment_11/pairpr1.py", "length_bytes": 712, "score": 3.53125, "int_score": 4, "content": "# returns a binary string which tells a number in prime or not\n# 1 means prime, 0 means not prime\ndef sieve(n):\n\t# index in the returning array tells the number\n\tprime = [1 for i in range(n+1)]\n\tprime[0], prime[1] = 0, 0\n\tp = 2\n\twhile p*p <=n:\n\t\tif prime[p] == 1:\n\t\t\tfor i in range(p*p, n+1, p):\n\t\t\t\tprime[i] = 0\n\t\tp+=1\n\t# print(prime)\n\tans = []\n\tfor i in range(len(prime)):\n\t\tif prime[i]==1:\n\t\t\tans.append(i)\n\treturn ans\n\nt = int(input())\nall_primes = sieve(10000)\nfor _ in range(t):\n\tn = int(input())\n\t# print(all_primes)\n\tmil_gya = False\n\tfor i in range(len(all_primes)):\n\t\tif n-all_primes[i] in all_primes:\n\t\t\tprint(all_primes[i], n-all_primes[i])\n\t\t\tmil_gya = True\n\t\t\tbreak\n\tif not mil_gya:\n\t\tprint('-1 -1')"} {"blob_id": "1df7d1245fc8c4359b7c08ece9c99c52efef58a5", "repo_name": "No-Life-King/school_stuff", "path": "/CSC 231 - Data Structures/BigO_Practice.py", "length_bytes": 2216, "score": 3.96875, "int_score": 4, "content": "__author__ = 'guinnc'\n'''\nFor use in Lab 3.\n'''\n\nimport time, random, math\n\ndef mystery1(n):\n '''What is it's big O?'''\n sum = 0\n for i in range(0, 10):\n sum += n\n return sum\n\ndef mystery2(n):\n '''What is it's big O?'''\n sum = 0\n for i in range(0, n):\n sum += i\n return sum\n\n\ndef mystery3(n):\n '''What is it's big O?'''\n sum = 0\n for i in range(0, n):\n for j in range(0, n):\n sum += i + j\n return sum\n\ndef mystery4(n):\n '''What is it's big O?'''\n sum = 0\n for i in range(0, n):\n for j in range(0, 25):\n sum += i + j\n return sum\n\ndef mystery5(n):\n '''What is it's big O?'''\n sum = 0\n while n > 0:\n sum += n\n n = n // 2 \n return sum\n\ndef mystery6(n):\n '''What is it's big O?'''\n sum = 0\n for i in range(0, n):\n while n > 0:\n sum += n\n n = n // 2 \n return sum\n\ndef mystery7(n):\n '''What is it's big O?'''\n if n == 2:\n return True\n if n % 2 == 0:\n return False\n div = 3\n while div < math.sqrt(n):\n if n % div == 0:\n return False\n div += 2 \n return True\n\ndef mystery8(n):\n '''What is it's big O?'''\n sum = 0\n for i in range(0, n):\n sum += mystery2(i)\n return sum\n\n# let's generate some experimental times\nprint(\"N\\tM1\\tM2\\tM3\\tM4\\tM5\\tM6\\tM7\\tM8\")\nfor n in range(100, 1001, 25):\n start = time.clock()\n result = mystery1(n)\n time1 = time.clock() - start\n\n start = time.clock()\n result = mystery2(n)\n time2 = time.clock() - start\n\n start = time.clock()\n result = mystery3(n)\n time3 = time.clock() - start\n\n start = time.clock()\n result = mystery4(n)\n time4 = time.clock() - start\n\n start = time.clock()\n result = mystery5(n)\n time5 = time.clock() - start\n\n start = time.clock()\n result = mystery6(n)\n time6 = time.clock() - start\n\n start = time.clock()\n result = mystery7(n)\n time7 = time.clock() - start\n\n start = time.clock()\n result = mystery8(n)\n time8 = time.clock() - start\n\n print(n, \"\\t\", time1, \"\\t\", time2, \"\\t\", time3, \"\\t\", time4, \"\\t\", time5, \"\\t\", time6, \"\\t\", time7, \"\\t\", time8)\n"} {"blob_id": "854e2829d4abc15add765a22b7276aa01a308ffb", "repo_name": "harshmalviya7/LeetCode_Coding_Questions", "path": "/reverseNodesInKGroup.py", "length_bytes": 977, "score": 3.640625, "int_score": 4, "content": "# 25. Reverse Nodes in k-Group\n# https://leetcode.com/problems/reverse-nodes-in-k-group/\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def reverseKGroup(self, head: ListNode, k: int) -> ListNode:\n def length(root):\n itr = root\n a = 0\n while (itr):\n itr = itr.next\n a += 1\n return a\n\n def reverse(head, k, l):\n if l < k:\n return head\n c = 0\n prev = None\n curr = head\n while (c < k and curr != None):\n nex = curr.next\n curr.next = prev\n prev = curr\n curr = nex\n c += 1\n if curr != None:\n head.next = reverse(curr, k, l - k)\n return prev\n\n return reverse(head, k, length(head))\n"} {"blob_id": "f3d2729ec1a49c3fe85b6f08af152d6174e484ad", "repo_name": "vaaishalijain/Leetcode", "path": "/July-LeetCode-Challenge-Solutions/8_3Sum.py", "length_bytes": 1360, "score": 3.640625, "int_score": 4, "content": "\"\"\"\n 3Sum\n\n Q. Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique\n triplets in the array which gives the sum of zero.\n\n Note:\n\n The solution set must not contain duplicate triplets.\n\n Example:\n\n Given array nums = [-1, 0, 1, 2, -1, -4],\n\n A solution set is:\n [\n [-1, 0, 1],\n [-1, -1, 2]\n ]\n\"\"\"\n\n\nclass Solution:\n def threeSum(self, nums: List[int]) -> List[List[int]]:\n ans = []\n nums.sort()\n if not nums or nums[0] > 0 or nums[len(nums) - 1] < 0:\n return []\n for a in range(len(nums) - 2):\n if nums[a] > 0:\n break\n if a > 0 and nums[a] == nums[a - 1]:\n continue\n i, j = a + 1, len(nums) - 1\n while i < j:\n val = nums[a] + nums[i] + nums[j]\n if val < 0:\n i += 1\n elif val > 0:\n j -= 1\n else:\n ans.append([nums[a], nums[i], nums[j]])\n while i < j and nums[i] == nums[i + 1]:\n i += 1\n while i < j and nums[j] == nums[j - 1]:\n j -= 1\n i += 1\n j -= 1\n return ans\n"} {"blob_id": "d2a1816a83cb7238ca3029fb62fafcb2c10d02b8", "repo_name": "ddz-mark/LeetCode", "path": "/other/\u968f\u673a\u6570.py", "length_bytes": 435, "score": 3.671875, "int_score": 4, "content": "# -*- coding: utf-8 -*-\n# @Time : 2020/5/13 12:23 \u4e0b\u5348\n# @Author : ddz\n\n# \u7531 \u968f\u673a\u65701-5\uff0c\u751f\u6210\u968f\u673a\u65701-7\n# \u601d\u8def\uff1arang5() + (rand5() - 1) * 5 ---> (1,2,3,4,5) + (0, 5, 10, 15, 20)\n# \u751f\u6210\u7b49\u6982\u7387\u7684 1-25\n\nimport random\n\n\ndef rand5():\n return random.randint(1, 5)\n\n\ndef rand7():\n x = 22\n while (x > 21):\n x = rand5() + (rand5() - 1) * 5\n\n return 1 + x % 7\n\n\nif __name__ == '__main__':\n print(rand7())\n"} {"blob_id": "1e5f0087dd01063f9ad8bcc2d192b5601097d0f5", "repo_name": "dundunmao/lint_leet", "path": "/mycode/leetcode2017/Hash/266 Palindrome Permutation\u00a0.py", "length_bytes": 970, "score": 3.59375, "int_score": 4, "content": "# -*- encoding: utf-8 -*-\n# \u56de\u6587\u5168\u6392\u5217\n# \u8fd9\u9053\u9898\u8ba9\u6211\u4eec\u5224\u65ad\u4e00\u4e2a\u5b57\u7b26\u4e32\u7684\u5168\u6392\u5217\u6709\u6ca1\u6709\u662f\u56de\u6587\u5b57\u7b26\u4e32\u7684\uff0c\u6211\u4eec\u5206\u5b57\u7b26\u4e32\u7684\u4e2a\u6570\u662f\u5947\u5076\u7684\u60c5\u51b5\u6765\u8ba8\u8bba\uff0c\n# \u5982\u679c\u662f\u5076\u6570\u7684\u8bdd\uff0c\u7531\u4e8e\u56de\u6587\u5b57\u7b26\u4e32\u7684\u7279\u6027\uff0c\u6bcf\u4e2a\u5b57\u6bcd\u51fa\u73b0\u7684\u6b21\u6570\u4e00\u5b9a\u662f\u5076\u6570\u6b21\uff0c\n# \u5f53\u5b57\u7b26\u4e32\u662f\u5947\u6570\u957f\u5ea6\u65f6\uff0c\u53ea\u6709\u4e00\u4e2a\u5b57\u6bcd\u51fa\u73b0\u7684\u6b21\u6570\u662f\u5947\u6570\uff0c\u5176\u4f59\u5747\u4e3a\u5076\u6570\uff0c\n# eg:\"code\" -> False, \"aab\" -> True, \"carerac\" -> True.\n# \u89e3\u6cd5\uff1a\u7528set\uff0c\u904d\u5386\uff0c\u5982\u679c\u4e0d\u5728set\u91cc\uff0c\u5c31\u52a0\u5165\uff0c\u5982\u679c\u5728set\u91cc\uff0c\u5c31delete\u3002\u6700\u540e\u6216\u8005\u8fd9\u4e2aset\u662f\u7a7a\uff0c\u6216\u8005\u53ea\u6709\u4e00\u4e2a\u5b57\u6bcd\nclass Solution(object):\n def canPermutePalindrome(self, n):\n array= []\n for ele in n:\n if ele in array:\n array.remove(ele)\n else:\n array.append(ele)\n return len(array) == 1 or len(array) == 0\nif __name__ == \"__main__\":\n a = \"carerac\"\n x = Solution()\n print x.canPermutePalindrome(a)\n\n"} {"blob_id": "2173e189cb4a7ed314ff4e2c5fb55282e16ffb3f", "repo_name": "harshitsoni05/AI-ML", "path": "/8puzzlefixedpath.py", "length_bytes": 21715, "score": 3.6875, "int_score": 4, "content": "# Hello World program in Python\r\n \r\n#print \"Hello World!\\n\"\r\ngoal =[1,2,3,4,5,6,7,8,0]\r\nclass graph :\r\n target=int()\r\n stop=0\r\n n = -1\r\n c = 1\r\n #visited = {1 : [3,2,6,0,8,4,7,5,1]}\r\n node = int()\r\n parent = int()\r\n a = {}\r\n a[1] = int ()\r\n a[2] = int ()\r\n a[3] = int ()\r\n a[4] = int ()\r\n a[5] = int ()\r\n a[6] = int ()\r\n a[7] = int ()\r\n a[8] = int ()\r\n a[9] = int () \r\n b = int()\r\n lock = []\r\ndef up(obb = graph(),p = int()) :\r\n #print(\"up\")\r\n #test=0\r\n #graph.n = obb.node\r\n #print(p)\r\n #print(graph.visited)\r\n '''graph.n = graph.n+1\r\n print(graph.n)\r\n obj[graph.n] = graph()\r\n obj[graph.n].node = graph.n\r\n obj[graph.n].a[1]=obj[p].a[1]\r\n obj[graph.n].a[2]=obj[p].a[2]\r\n obj[graph.n].a[3]=obj[p].a[3]\r\n obj[graph.n].a[4]=obj[p].a[4]\r\n obj[graph.n].a[5]=obj[p].a[5]\r\n obj[graph.n].a[6]=obj[p].a[6]\r\n obj[graph.n].a[7]=obj[p].a[7]\r\n obj[graph.n].a[8]=obj[p].a[8]\r\n obj[graph.n].a[9]=obj[p].a[9]\r\n obj[graph.n].b=obj[p].b\r\n print(obj[graph.n].b)\r\n obj[graph.n].parent = p'''\r\n check=0\r\n size=len(graph.lock)\r\n if(size!=0):\r\n for i in range(size):\r\n y=graph.lock[i]\r\n y=y+3\r\n if(y>0):\r\n if obj[graph.n].a[y]==0:\r\n check=1\r\n if obj[graph.n].a[1]!=0 and obj[graph.n].a[2]!=0 and obj[graph.n].a[3]!=0 and check==0:\r\n #print(obj[graph.n].b)\r\n #obj[graph.n].b=obj[graph.n]-3\r\n #print(obj[graph.n].a[7])\r\n print(\"up\")\r\n temp=obj[graph.n].b\r\n temp=temp-3\r\n #print(obj[graph.n].a[obj[graph.n].b])\r\n obj[graph.n].a[obj[graph.n].b]=obj[graph.n].a[temp]\r\n obj[graph.n].a[temp]=0\r\n obj[graph.n].b=temp\r\n print(obj[graph.n].a[1] , obj[graph.n].a[2],obj[graph.n].a[3],obj[graph.n].a[4],obj[graph.n].a[5],obj[graph.n].a[6] , obj[graph.n].a[7],obj[graph.n].a[8],obj[graph.n].a[9])\r\n #test=1\r\n #print(obj[graph.n].a[obj[graph.n].b])\r\n #print(obj[graph.n].a[7])\r\n #pp = obj[graph.n].node\r\n #temp = []\r\n #temp = [obj[graph.n].a[1] , obj[graph.n].a[2],obj[graph.n].a[3],obj[graph.n].a[4],obj[graph.n].a[5],obj[graph.n].a[6] , obj[graph.n].a[7],obj[graph.n].a[8],obj[graph.n].a[9]]\r\n #print(temp)\r\n #print(obj[graph.n].b)\r\n #check = 0\r\n '''for i in graph.visited:\r\n if graph.visited[i] == temp :\r\n check = 1\r\n if obj[graph.n].a[1]==1 and obj[graph.n].a[2]==3 and obj[graph.n].a[5]==2 :\r\n #check =1\r\n print(\"done!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\")\r\n graph.target=graph.c\r\n graph.stop=1\r\n #print(obj[graph.n].a1)\r\n #print(obj[graph.n].b1)\r\n #print(obj[graph.n].a2)\r\n #print(obj[graph.n].b2)\r\n if check == 0 :\r\n #visited = {}\r\n graph.c = graph.c+1\r\n graph.visited[graph.c] = []\r\n graph.visited[graph.c].append(obj[graph.n].a[1])\r\n graph.visited[graph.c].append(obj[graph.n].a[2])\r\n graph.visited[graph.c].append(obj[graph.n].a[3])\r\n graph.visited[graph.c].append(obj[graph.n].a[4])\r\n graph.visited[graph.c].append(obj[graph.n].a[5])\r\n graph.visited[graph.c].append(obj[graph.n].a[6])\r\n graph.visited[graph.c].append(obj[graph.n].a[7])\r\n graph.visited[graph.c].append(obj[graph.n].a[8])\r\n graph.visited[graph.c].append(obj[graph.n].a[9])\r\n #print(\"updated \")\r\n #print(graph.visited)\r\n #graph.visited[graph.c].append(obj[n].b)\r\n #print(\"test\")\r\n #twoMB(obj[graph.n],pp)\r\n if graph.stop==0:\r\n right(obj[pp],pp)\r\n if graph.stop==0:\r\n left(obj[pp],pp)\r\n if graph.stop==0:\r\n up(obj[pp],pp)'''\r\n '''if test==1:\r\n temp=obj[graph.n].b\r\n temp=temp+3\r\n obj[graph.n].a[obj[graph.n].b]=obj[graph.n].a[temp]\r\n obj[graph.n].a[temp]=0\r\n obj[graph.n].b=temp\r\n obj[graph.n].a[1]=obb.a[1]\r\n obj[graph.n].a[2]=obb.a[2]\r\n obj[graph.n].a[3]=obb.a[3]\r\n obj[graph.n].a[4]=obb.a[4]\r\n obj[graph.n].a[5]=obb.a[5]\r\n obj[graph.n].a[6]=obb.a[6]\r\n obj[graph.n].a[7]=obb.a[7]\r\n obj[graph.n].a[8]=obb.a[8]\r\n obj[graph.n].a[9]=obb.a[9]\r\n obj[graph.n].b=obb.b'''\r\n\r\n \r\n \r\ndef down(obb = graph(),p = int()) :\r\n #print(\"down\")\r\n '''test=0\r\n #graph.n = obb.node\r\n print(p)\r\n graph.n = graph.n+1\r\n print(graph.n)\r\n obj[graph.n] = graph()\r\n obj[graph.n].node = graph.n\r\n obj[graph.n].a[1]=obj[p].a[1]\r\n obj[graph.n].a[2]=obj[p].a[2]\r\n obj[graph.n].a[3]=obj[p].a[3]\r\n obj[graph.n].a[4]=obj[p].a[4]\r\n obj[graph.n].a[5]=obj[p].a[5]\r\n obj[graph.n].a[6]=obj[p].a[6]\r\n obj[graph.n].a[7]=obj[p].a[7]\r\n obj[graph.n].a[8]=obj[p].a[8]\r\n obj[graph.n].a[9]=obj[p].a[9]\r\n obj[graph.n].b=obj[p].b\r\n print(obj[graph.n].b)\r\n obj[graph.n].parent = p'''\r\n check=0\r\n size=len(graph.lock)\r\n if(size!=0):\r\n for i in range(size):\r\n y=graph.lock[i]\r\n #y=y+1\r\n y=y-3\r\n if(y>0):\r\n if obj[graph.n].a[y]==0:\r\n check=1\r\n if obj[graph.n].a[7]!=0 and obj[graph.n].a[8]!=0 and obj[graph.n].a[9]!=0 and check==0:\r\n #obj[graph.n].b=obj[graph.n]-3\r\n print(\"down\")\r\n temp=obj[graph.n].b\r\n temp=temp+3\r\n obj[graph.n].a[obj[graph.n].b]=obj[graph.n].a[temp]\r\n obj[graph.n].a[temp]=0\r\n obj[graph.n].b=temp\r\n print(obj[graph.n].a[1] , obj[graph.n].a[2],obj[graph.n].a[3],obj[graph.n].a[4],obj[graph.n].a[5],obj[graph.n].a[6] , obj[graph.n].a[7],obj[graph.n].a[8],obj[graph.n].a[9])\r\n '''test=1\r\n pp = obj[graph.n].node\r\n print(pp)\r\n temp = []\r\n temp = [obj[graph.n].a[1] , obj[graph.n].a[2],obj[graph.n].a[3],obj[graph.n].a[4],obj[graph.n].a[5],obj[graph.n].a[6] , obj[graph.n].a[7],obj[graph.n].a[8],obj[graph.n].a[9]]\r\n print(temp)\r\n #print(obj[graph.n].b)\r\n check = 0\r\n for i in graph.visited:\r\n if graph.visited[i] == temp:\r\n check = 1\r\n if obj[graph.n].a[1]==1 and obj[graph.n].a[2]==3 and obj[graph.n].a[5]==2:\r\n #check =1\r\n print(\"done!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\")\r\n graph.target=graph.c\r\n graph.stop=1\r\n #print(obj[graph.n].a1)\r\n #print(obj[graph.n].b1)\r\n #print(obj[graph.n].a2)\r\n #print(obj[graph.n].b2)\r\n if check == 0 :\r\n #visited = {}\r\n graph.c = graph.c+1\r\n graph.visited[graph.c] = []\r\n graph.visited[graph.c].append(obj[graph.n].a[1])\r\n graph.visited[graph.c].append(obj[graph.n].a[2])\r\n graph.visited[graph.c].append(obj[graph.n].a[3])\r\n graph.visited[graph.c].append(obj[graph.n].a[4])\r\n graph.visited[graph.c].append(obj[graph.n].a[5])\r\n graph.visited[graph.c].append(obj[graph.n].a[6])\r\n graph.visited[graph.c].append(obj[graph.n].a[7])\r\n graph.visited[graph.c].append(obj[graph.n].a[8])\r\n graph.visited[graph.c].append(obj[graph.n].a[9])\r\n #print(\"updated \")\r\n #print(graph.visited)\r\n #graph.visited[graph.c].append(obj[n].b)\r\n #print(\"test\")\r\n #twoMB(obj[graph.n],pp)\r\n #up(obj[graph.n],pp)\r\n #if graph.stop==0:\r\n left(obj[pp],pp)\r\n #if graph.stop==0:\r\n down(obj[pp],pp)\r\n #if graph.stop==0:\r\n right(obj[pp],pp)\r\n if test==1:\r\n temp=obj[graph.n].b\r\n temp=temp-3\r\n #print(obj[graph.n].a[obj[graph.n].b])\r\n obj[graph.n].a[obj[graph.n].b]=obj[graph.n].a[temp]\r\n obj[graph.n].a[temp]=0\r\n obj[graph.n].b=temp\r\n obj[graph.n].a[1]=obb.a[1]\r\n obj[graph.n].a[2]=obb.a[2]\r\n obj[graph.n].a[3]=obb.a[3]\r\n obj[graph.n].a[4]=obb.a[4]\r\n obj[graph.n].a[5]=obb.a[5]\r\n obj[graph.n].a[6]=obb.a[6]\r\n obj[graph.n].a[7]=obb.a[7]\r\n obj[graph.n].a[8]=obb.a[8]\r\n obj[graph.n].a[9]=obb.a[9]\r\n obj[graph.n].b=obb.b'''\r\n\r\n\r\ndef right(obb = graph(),p = int()) :\r\n #print(\"right\")\r\n '''test=0\r\n #graph.n = obb.node\r\n print(p)\r\n graph.n = graph.n+1\r\n print(graph.n)\r\n obj[graph.n] = graph()\r\n obj[graph.n].node = graph.n\r\n obj[graph.n].a[1]=obj[p].a[1]\r\n obj[graph.n].a[2]=obj[p].a[2]\r\n obj[graph.n].a[3]=obj[p].a[3]\r\n obj[graph.n].a[4]=obj[p].a[4]\r\n obj[graph.n].a[5]=obj[p].a[5]\r\n obj[graph.n].a[6]=obj[p].a[6]\r\n obj[graph.n].a[7]=obj[p].a[7]\r\n obj[graph.n].a[8]=obj[p].a[8]\r\n obj[graph.n].a[9]=obj[p].a[9]\r\n obj[graph.n].b=obj[p].b\r\n print(obj[graph.n].b)\r\n obj[graph.n].parent = p'''\r\n check=0\r\n size=len(graph.lock)\r\n if(size!=0):\r\n for i in range(size):\r\n y=graph.lock[i]\r\n #y=y+1\r\n y=y-1\r\n if(y>0):\r\n if obj[graph.n].a[y]==0:\r\n check=1\r\n if obj[graph.n].a[3]!=0 and obj[graph.n].a[6]!=0 and obj[graph.n].a[9]!=0 and check==0:\r\n #obj[graph.n].b=obj[graph.n]-3\r\n #print(obj[graph.n].b)\r\n print(\"right\")\r\n temp=obj[graph.n].b\r\n temp=temp+1\r\n obj[graph.n].a[obj[graph.n].b]=obj[graph.n].a[temp]\r\n obj[graph.n].a[temp]=0\r\n obj[graph.n].b=temp\r\n print(obj[graph.n].a[1] , obj[graph.n].a[2],obj[graph.n].a[3],obj[graph.n].a[4],obj[graph.n].a[5],obj[graph.n].a[6] , obj[graph.n].a[7],obj[graph.n].a[8],obj[graph.n].a[9])\r\n '''test=1\r\n pp = obj[graph.n].node\r\n temp = []\r\n temp = [obj[graph.n].a[1] , obj[graph.n].a[2],obj[graph.n].a[3],obj[graph.n].a[4],obj[graph.n].a[5],obj[graph.n].a[6] , obj[graph.n].a[7],obj[graph.n].a[8],obj[graph.n].a[9]]\r\n print(temp)\r\n #print(obj[graph.n].b)\r\n check = 0\r\n for i in graph.visited:\r\n if graph.visited[i] == temp:\r\n check = 1\r\n if obj[graph.n].a[1]==1 and obj[graph.n].a[2]==3 and obj[graph.n].a[5]==2:\r\n #check =1\r\n print(\"done!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\")\r\n graph.target=graph.c\r\n graph.stop=1\r\n #print(obj[graph.n].a1)\r\n #print(obj[graph.n].b1)\r\n #print(obj[graph.n].a2)\r\n #print(obj[graph.n].b2)\r\n if check == 0 :\r\n #visited = {}\r\n print(\"updationnnnnn\")\r\n graph.c = graph.c+1\r\n graph.visited[graph.c] = []\r\n graph.visited[graph.c].append(obj[graph.n].a[1])\r\n graph.visited[graph.c].append(obj[graph.n].a[2])\r\n graph.visited[graph.c].append(obj[graph.n].a[3])\r\n graph.visited[graph.c].append(obj[graph.n].a[4])\r\n graph.visited[graph.c].append(obj[graph.n].a[5])\r\n graph.visited[graph.c].append(obj[graph.n].a[6])\r\n graph.visited[graph.c].append(obj[graph.n].a[7])\r\n graph.visited[graph.c].append(obj[graph.n].a[8])\r\n graph.visited[graph.c].append(obj[graph.n].a[9])\r\n #print(\"updated \")\r\n #print(graph.visited)\r\n #graph.visited[graph.c].append(obj[n].b)\r\n #print(\"test\")\r\n #twoMB(obj[graph.n],pp)\r\n if graph.stop==0:\r\n down(obj[pp],pp)\r\n if graph.stop==0:\r\n up(obj[pp],pp)\r\n if graph.stop==0:\r\n right(obj[pp],pp)\r\n if test==1:\r\n temp=obj[graph.n].b\r\n temp=temp-1\r\n obj[graph.n].a[obj[graph.n].b]=obj[graph.n].a[temp]\r\n obj[graph.n].a[temp]=0\r\n obj[graph.n].b=temp\r\n pp = obj[graph.n].node\r\n obj[graph.n].a[1]=obb.a[1]\r\n obj[graph.n].a[2]=obb.a[2]\r\n obj[graph.n].a[3]=obb.a[3]\r\n obj[graph.n].a[4]=obb.a[4]\r\n obj[graph.n].a[5]=obb.a[5]\r\n obj[graph.n].a[6]=obb.a[6]\r\n obj[graph.n].a[7]=obb.a[7]\r\n obj[graph.n].a[8]=obb.a[8]\r\n obj[graph.n].a[9]=obb.a[9]\r\n obj[graph.n].b=obb.b'''\r\n\r\n\r\ndef left(obb = graph(),p = int()) :\r\n #print(\"left\")\r\n '''test=0\r\n #graph.n = obb.node\r\n print(p)\r\n graph.n = graph.n+1\r\n print(graph.n)\r\n obj[graph.n] = graph()\r\n obj[graph.n].node = graph.n\r\n obj[graph.n].a[1]=obj[p].a[1]\r\n obj[graph.n].a[2]=obj[p].a[2]\r\n obj[graph.n].a[3]=obj[p].a[3]\r\n obj[graph.n].a[4]=obj[p].a[4]\r\n obj[graph.n].a[5]=obj[p].a[5]\r\n obj[graph.n].a[6]=obj[p].a[6]\r\n obj[graph.n].a[7]=obj[p].a[7]\r\n obj[graph.n].a[8]=obj[p].a[8]\r\n obj[graph.n].a[9]=obj[p].a[9]\r\n obj[graph.n].b=obj[p].b\r\n print(obj[graph.n].b)\r\n obj[graph.n].parent = p'''\r\n check=0\r\n size=len(graph.lock)\r\n if(size!=0):\r\n for i in range(size):\r\n y=graph.lock[i]\r\n #y=y+1\r\n y=y+1\r\n if(y>0):\r\n if obj[graph.n].a[y]==0:\r\n check=1\r\n if obj[graph.n].a[1]!=0 and obj[graph.n].a[4]!=0 and obj[graph.n].a[7]!=0 and check==0:\r\n #obj[graph.n].b=obj[graph.n]-3\r\n #print(obj[graph.n].b\r\n print(\"left\")\r\n temp=obj[graph.n].b\r\n temp=temp-1\r\n obj[graph.n].a[obj[graph.n].b]=obj[graph.n].a[temp]\r\n obj[graph.n].a[temp]=0\r\n obj[graph.n].b=temp\r\n print(obj[graph.n].a[1] , obj[graph.n].a[2],obj[graph.n].a[3],obj[graph.n].a[4],obj[graph.n].a[5],obj[graph.n].a[6] , obj[graph.n].a[7],obj[graph.n].a[8],obj[graph.n].a[9])\r\n '''test=1\r\n pp = obj[graph.n].node\r\n temp = []\r\n temp = [obj[graph.n].a[1] , obj[graph.n].a[2],obj[graph.n].a[3],obj[graph.n].a[4],obj[graph.n].a[5],obj[graph.n].a[6] , obj[graph.n].a[7],obj[graph.n].a[8],obj[graph.n].a[9]]\r\n print(temp)\r\n #print(obj[graph.n].b)\r\n check = 0\r\n for i in graph.visited:\r\n if graph.visited[i] == temp:\r\n check = 1\r\n if obj[graph.n].a[1]==1 and obj[graph.n].a[2]==3 and obj[graph.n].a[5]==2:\r\n #check =1\r\n print(\"done!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\")\r\n graph.target=graph.c\r\n graph.stop=1\r\n #print(obj[graph.n].a1)\r\n #print(obj[graph.n].b1)\r\n #print(obj[graph.n].a2)\r\n #print(obj[graph.n].b2)\r\n if check == 0 :\r\n #visited = {}\r\n graph.c = graph.c+1\r\n graph.visited[graph.c] = []\r\n graph.visited[graph.c].append(obj[graph.n].a[1])\r\n graph.visited[graph.c].append(obj[graph.n].a[2])\r\n graph.visited[graph.c].append(obj[graph.n].a[3])\r\n graph.visited[graph.c].append(obj[graph.n].a[4])\r\n graph.visited[graph.c].append(obj[graph.n].a[5])\r\n graph.visited[graph.c].append(obj[graph.n].a[6])\r\n graph.visited[graph.c].append(obj[graph.n].a[7])\r\n graph.visited[graph.c].append(obj[graph.n].a[8])\r\n graph.visited[graph.c].append(obj[graph.n].a[9])\r\n #print(\"updated \")\r\n #print(graph.visited)\r\n #graph.visited[graph.c].append(obj[n].b)\r\n #print(\"test\")\r\n #twoMB(obj[graph.n],pp)\r\n if graph.stop==0:\r\n up(obj[pp],pp)\r\n if graph.stop==0:\r\n down(obj[pp],pp)\r\n if graph.stop==0:\r\n left(obj[pp],pp)\r\n if test==1:\r\n temp=obj[graph.n].b\r\n temp=temp+1\r\n obj[graph.n].a[obj[graph.n].b]=obj[graph.n].a[temp]\r\n obj[graph.n].a[temp]=0\r\n obj[graph.n].b=temp\r\n obj[graph.n].a[1]=obb.a[1]\r\n obj[graph.n].a[2]=obb.a[2]\r\n obj[graph.n].a[3]=obb.a[3]\r\n obj[graph.n].a[4]=obb.a[4]\r\n obj[graph.n].a[5]=obb.a[5]\r\n obj[graph.n].a[6]=obb.a[6]\r\n obj[graph.n].a[7]=obb.a[7]\r\n obj[graph.n].a[8]=obb.a[8]\r\n obj[graph.n].a[9]=obb.a[9]\r\n obj[graph.n].b=obb.b'''\r\n\r\ndef lock(index = int()):\r\n graph.lock.append(index)\r\n\r\ndef unlock():\r\n graph.lock.pop()\r\n \r\nobj = {}\r\ngraph.n = graph.n+1\r\nobj[graph.n] = graph()\r\nobj[graph.n].node=graph.n\r\nobj[graph.n].parent=-1\r\nobj[graph.n].a[1]=5\r\nobj[graph.n].a[2]=8\r\nobj[graph.n].a[3]=3\r\nobj[graph.n].a[4]=4\r\nobj[graph.n].a[5]=6\r\nobj[graph.n].a[6]=7\r\nobj[graph.n].a[7]=1\r\nobj[graph.n].a[8]=2\r\nobj[graph.n].a[9]=0\r\nobj[graph.n].b=9\r\n\r\n#up(obj[graph.n],0)\r\n#down(obj[graph.n],0)\r\n#right(obj[graph.n],0)\r\n#left(obj[graph.n],0)\r\n#print(graph.visited)\r\n#print(graph.target)\r\n#graph.n=graph.target+1\r\n#print(obj[graph.n].a[1] , obj[graph.n].a[2],obj[graph.n].a[3],obj[graph.n].a[4],obj[graph.n].a[5],obj[graph.n].a[6] , obj[graph.n].a[7],obj[graph.n].a[8],obj[graph.n].a[9])\r\n#graph.n=graph.target\r\n#print(obj[graph.n].a[1] , obj[graph.n].a[2],obj[graph.n].a[3],obj[graph.n].a[4],obj[graph.n].a[5],obj[graph.n].a[6] , obj[graph.n].a[7],obj[graph.n].a[8],obj[graph.n].a[9])\r\n'''final =int()\r\nfor i in range(graph.c):\r\n if graph.visited[i]==goal:\r\n final = i\r\n break\r\ngraph.n=final\r\nprint(final)\r\n#graph.n=graph.target\r\nobj[graph.n].a[1]==1\r\n#print(obj[7].parent)\r\n#print(obj[7].a1,obj[7].b1,obj[7].a2,obj[7].b2)\r\nwhile obj[graph.n].parent != -1 :\r\n print(obj[graph.n].a[1] , obj[graph.n].a[2],obj[graph.n].a[3],obj[graph.n].a[4],obj[graph.n].a[5],obj[graph.n].a[6] , obj[graph.n].a[7],obj[graph.n].a[8],obj[graph.n].a[9])\r\n graph.n=obj[graph.n].parent\r\n print(graph.n)\r\nprint(obj[graph.n].a[1] , obj[graph.n].a[2],obj[graph.n].a[3],obj[graph.n].a[4],obj[graph.n].a[5],obj[graph.n].a[6] , obj[graph.n].a[7],obj[graph.n].a[8],obj[graph.n].a[9])'''\r\nup()\r\nup()\r\nleft()\r\nleft()\r\n#y=0\r\n#lock(1)\r\ntemp=int()\r\n\r\n#print(obj[graph.n].a[1])\r\ny=1\r\nfor i in range(9):\r\n if obj[graph.n].a[y]==1:\r\n temp=y\r\n y=y+1\r\nprint(graph.lock)\r\n#temp=6\r\n#print(\" \")\r\nprint(temp)\r\nprint(\"firsttttt\")\r\nif temp==1:\r\n print(\"\")\r\nif temp==2:\r\n right()\r\nif temp==3:\r\n right()\r\n right()\r\n down()\r\n left()\r\n left()\r\n up()\r\n right()\r\nif temp==4:\r\n down()\r\nif temp==5:\r\n down()\r\n right()\r\n up()\r\n left()\r\n down()\r\nif temp==6:\r\n down()\r\n right()\r\n right()\r\n up()\r\n left()\r\n left()\r\n down()\r\n right()\r\n up()\r\n left()\r\n down()\r\n\r\nif temp==7:\r\n down()\r\n down()\r\n right()\r\n up()\r\n up()\r\n left()\r\n down()\r\nif temp==8:\r\n down()\r\n right()\r\n down()\r\n left()\r\n up()\r\n right()\r\n up()\r\n left()\r\n down()\r\nif temp==9:\r\n down()\r\n right()\r\n right()\r\n down()\r\n left()\r\n up()\r\n right()\r\n down()\r\n left()\r\n left()\r\n up()\r\n right()\r\n up()\r\n left()\r\n down()\r\n \r\nlock(1)\r\nright()\r\nright()\r\nup()\r\nup()\r\nleft()\r\nleft()\r\ny=1\r\nfor i in range(9):\r\n if obj[graph.n].a[y]==3:\r\n temp=y\r\n y=y+1\r\nprint(obj[graph.n].a[1] , obj[graph.n].a[2],obj[graph.n].a[3],obj[graph.n].a[4],obj[graph.n].a[5],obj[graph.n].a[6] , obj[graph.n].a[7],obj[graph.n].a[8],obj[graph.n].a[9]) \r\nprint(\"yesyesyes\")\r\nprint(y)\r\n#temp=y\r\nprint(\"seconddddd\")\r\nif temp==3 :\r\n right()\r\nif temp==4:\r\n down()\r\n left()\r\n down()\r\n right()\r\n right()\r\n up()\r\n up()\r\n left()\r\n down()\r\nif temp==5:\r\n down()\r\nif temp==6:\r\n down()\r\n right()\r\n up()\r\n left()\r\n down()\r\nif temp==7:\r\n down()\r\n down()\r\n left()\r\n up()\r\n right()\r\n down()\r\n right()\r\n up()\r\n up()\r\n left()\r\n down()\r\nif temp==8:\r\n down()\r\n down()\r\n right()\r\n up()\r\n up()\r\n left()\r\n down()\r\nif temp==9:\r\n down()\r\n right()\r\n down()\r\n left()\r\n up()\r\n right()\r\n up()\r\n left()\r\n down()\r\n \r\n#lock(2)\r\nright()\r\nright()\r\nup()\r\nup()\r\n\r\ny=1\r\nfor i in range(9):\r\n if obj[graph.n].a[y]==2:\r\n temp=y\r\n y=y+1\r\nprint(temp)\r\nprint(\"thirdddddddd\")\r\nif temp==6:\r\n #unlock(2)\r\n left()\r\n down()\r\n down()\r\n right()\r\n up()\r\n left()\r\n up()\r\n right()\r\n down()\r\n down()\r\n left()\r\n up()\r\n right()\r\nif temp==4:\r\n down()\r\n left()\r\n left()\r\nif temp==5:\r\n print('')\r\nif temp==7:\r\n down()\r\n down()\r\n left()\r\n left()\r\n up()\r\n right()\r\n down()\r\nif temp==8:\r\n down()\r\n left()\r\n down()\r\nif temp==9:\r\n down()\r\n down()\r\n left()\r\n up()\r\n right()\r\nlock(2)\r\nlock(5)\r\ndown()\r\nright()\r\nright()\r\nup()\r\nup()\r\nunlock()\r\nunlock()\r\nleft()\r\ndown()\r\nlock(2)\r\nlock(3)\r\n\r\n\r\nleft()\r\nleft()\r\nup()\r\nup()\r\ny=1\r\nfor i in range(9):\r\n if obj[graph.n].a[y]==4:\r\n temp=y\r\n y=y+1\r\n\r\nprint(temp)\r\n#temp=y\r\nprint(\"fourthhhhhh\")\r\nif temp==5:\r\n right()\r\nif temp==6:\r\n right()\r\n right()\r\n down()\r\n left()\r\n left()\r\n up()\r\n right()\r\nif temp==7:\r\n down()\r\nif temp==8:\r\n right()\r\n down()\r\n left()\r\n up()\r\n right()\r\nif temp==9:\r\n right()\r\n right()\r\n down()\r\n left()\r\n up()\r\n right()\r\n down()\r\n left()\r\n left()\r\n up()\r\n right()\r\nlock(4)\r\ndown()\r\nleft()\r\nleft()\r\n\r\ny=1\r\nfor i in range(9):\r\n if obj[graph.n].a[y]==5:\r\n temp=y\r\n y=y+1\r\n#temp=y\r\nprint(temp)\r\nprint(\"fifthhhhhh\")\r\nif temp==5:\r\n print(\"\")\r\nif temp==6:\r\n right()\r\n up()\r\n right()\r\nif temp==8:\r\n unlock()\r\n up()\r\n right()\r\n down()\r\n right()\r\n up()\r\n left()\r\n left()\r\n down()\r\n right()\r\n up()\r\n right()\r\n lock(4)\r\nif temp==9:\r\n right()\r\n right()\r\n up()\r\n left()\r\n down()\r\n#lock(4)\r\nlock(5)\r\ndown()\r\nleft()\r\nleft()\r\nunlock()\r\nunlock()\r\nprint(graph.lock)\r\nup()\r\nright()\r\n\r\nwhile obj[graph.n].a[6]!=6:\r\n down()\r\n right()\r\n up()\r\n left()\r\nleft()\r\ndown()\r\nright()\r\nright()\r\n\r\nprint(obj[graph.n].a[1] , obj[graph.n].a[2],obj[graph.n].a[3],obj[graph.n].a[4],obj[graph.n].a[5],obj[graph.n].a[6] , obj[graph.n].a[7],obj[graph.n].a[8],obj[graph.n].a[9]) \r\n"} {"blob_id": "9d93d0a24c3c8072c13e033f9ad8a6e1a3858eed", "repo_name": "rbabaci1/CS-Module-Recursive_Sorting", "path": "/src/searching/searching.py", "length_bytes": 2178, "score": 4.28125, "int_score": 4, "content": "# TO-DO: Implement a recursive implementation of binary search\ndef binary_search(arr, target, start, end):\n midpoint = (start + end) // 2\n if start > end:\n return -1\n if arr[midpoint] == target:\n return midpoint\n\n if arr[midpoint] > target:\n return binary_search(arr, target, start, midpoint - 1)\n else:\n return binary_search(arr, target, midpoint + 1, end)\n\n\n# STRETCH: implement an order-agnostic binary search\n# This version of binary search should correctly find\n# the target regardless of whether the input array is\n# sorted in ascending order or in descending order\n# You can implement this function either recursively\n# or iteratively\n\n\ndef agnostic_binary_search(arr, target):\n isAsc, start, end = False, 0, len(arr) - 1\n if len(arr) >= 2:\n if arr[0] < arr[-1]:\n isAsc = True\n\n while start <= end:\n midpoint = (start + end) // 2\n if arr[midpoint] == target:\n return midpoint\n if isAsc:\n if arr[midpoint] > target:\n end = midpoint - 1\n else:\n start = midpoint + 1\n else:\n if arr[midpoint] > target:\n start = midpoint + 1\n else:\n end = midpoint - 1\n return -1\n\n\n# def isAscending(arr):\n# if len(arr) >= 2:\n# if arr[0] < arr[1]:\n# return True\n# return False\n\n# def agnostic_recursive_binary_search(arr, target, start=0, end=None):\n# isAsc = isAscending(arr)\n# if not end:\n# end = len(arr) - 1\n# midpoint = (start + end) // 2\n# # base cases\n# if start > end:\n# return -1\n# if arr[midpoint] == target:\n# return midpoint\n\n# if isAsc:\n# if arr[midpoint] > target:\n# return agnostic_binary_search(arr, target, start, midpoint - 1)\n# else:\n# return agnostic_binary_search(arr, target, midpoint + 1, end)\n# else:\n# if arr[midpoint] > target:\n# return agnostic_binary_search(arr, target, midpoint + 1, end)\n# else:\n# return agnostic_binary_search(arr, target, start, midpoint - 1)\n# return -1\n"} {"blob_id": "5b4d479ae57e50d856f851fe615dc71022f29222", "repo_name": "lxyshuai/Algorithm-primary-class-python", "path": "/5/find_one_less_value_index.py", "length_bytes": 1475, "score": 3.890625, "int_score": 4, "content": "# coding=utf-8\nfrom __future__ import division\n\n\"\"\"\n\u5728\u6570\u7ec4\u4e2d\u627e\u5230\u4e00\u4e2a\u5c40\u90e8\u6700\u5c0f\u7684\u4f4d\u7f6e\n\u3010\u9898\u76ee\u3011\n\u5b9a\u4e49\u5c40\u90e8\u6700\u5c0f\u7684\u6982\u5ff5\u3002arr\u957f\u5ea6\u4e3a1\u65f6\uff0carr[0]\u662f\u5c40\u90e8\u6700\u5c0f\u3002arr\u7684\u957f\u5ea6\u4e3a\nN(N>1)\u65f6\uff0c\u5982\u679carr[0] array[middle + 1]:\n left = middle + 1\n else:\n return middle\n return left\n\n\nif __name__ == '__main__':\n array = [6, 5, 3, 4, 6, 7, 8]\n print get_less_index(array)\n"} {"blob_id": "d4a72241a22d470eac635e374c8a1488a71b413c", "repo_name": "LassiAutio/scheduler", "path": "/roundrobin.py", "length_bytes": 4037, "score": 3.625, "int_score": 4, "content": "import string\nimport datetime\nimport math\nimport calendar\nfrom game import Game\n\n'''\nGenerates Round-robin schedule for given number of teams and round.\n'''\nclass RoundRobin(object):\n \n def __init__(self, teams_count, rounds_count=2, date_start = datetime.date(2015, 5, 12), date_end = datetime.date(2015, 8, 14)):\n assert(teams_count>=3)\n assert(rounds_count>=1)\n self.teams = generateTeams(teams_count)\n if len(self.teams)%2 != 0:\n self.teams.append(None)\n self.date_start = date_start\n self.date_end = date_end\n self.date_current = None\n self.rounds_count = rounds_count\n self.reverse_home_away = False\n self.schedule = []\n \n def getGamesCountOneRound(self):\n return getGamesCountOneRound(len(self.teams))\n \n def getGamesCount(self):\n return getGamesCount(len(self.teams), self.rounds_count)\n \n def getDaysInSeason(self):\n return (self.date_end - self.date_start).days + 1\n \n def getAvgDaysBetweenGames(self):\n return getAvgDaysBetweenGames(self.getGamesCount(), self.getDaysInSeason())\n \n def generateSchedule(self):\n self.schedule = []\n for i in range(self.rounds_count):\n self.schedule.extend( self.getNextRoundRobin() )\n \n def getSchedule(self):\n if self.schedule == []:\n self.generateSchedule()\n return self.schedule\n \n def printSchedule(self):\n self.generateSchedule()\n for game in self.schedule:\n print game.printGame()\n \n def getNextRoundRobin(self):\n half = len(self.teams) / 2\n schedule = []\n for turn in range(len(self.teams)-1):\n for i in range(half):\n home = self.teams[i]\n away = self.teams[len(self.teams)-i-1]\n if self.reverse_home_away == True:\n temp = home\n home = away\n away = temp\n if (home != None) and (away != None):\n game = Game(home, away, self.getNextDate() )\n schedule.append( game )\n last_team = self.teams.pop()\n self.teams.insert(1, last_team)\n self.reverse_home_away = not self.reverse_home_away\n return schedule\n \n def getNextDate(self):\n if self.date_current == None:\n self.date_current = self.date_start\n else:\n self.date_current += datetime.timedelta(days = self.getAvgDaysBetweenGames()+1 )\n #\n while calendar.IsSpecialDay(self.date_current):\n self.date_current += datetime.timedelta(days = 1)\n return self.date_current\n \ndef generateTeams(teams_count):\n assert(teams_count>=3)\n return list(string.ascii_uppercase)[:teams_count]\n\ndef getGamesCountOneRound(teams_count):\n assert(teams_count>=3)\n return int( (float(teams_count)/2) * (teams_count-1) )\n\ndef getGamesCount(teams_count, rounds_count):\n assert(rounds_count>=1)\n return getGamesCountOneRound(teams_count) * rounds_count\n\n# Returns how many days there would be between each games if they are separated evenly.\ndef getAvgDaysBetweenGames(games_count, days_count):\n x = days_count - games_count\n divider = games_count-1\n return math.floor( (float(x) / divider)+1 )\n\ndef getRoundRobin(teams, reverse_home_away=False):\n if len(teams)%2 != 0 :\n teams.append(None)\n half = len(teams) / 2\n schedule = []\n for turn in range(len(teams)-1):\n for i in range(half):\n home = teams[i]\n away = teams[len(teams)-i-1]\n if reverse_home_away == True:\n temp = home\n home = away\n away = temp\n if (home != None) and (away != None):\n game = Game(home, away)\n schedule.append( game )\n last_team = teams.pop()\n teams.insert(1, last_team)\n return schedule\n\nif __name__ == '__main__':\n robin = RoundRobin(5, 4)\n robin.printSchedule()"} {"blob_id": "01232d78e27044360a9bc8d0cb3c3a8f158266f6", "repo_name": "arthurDz/algorithm-studies", "path": "/linkedin/print_binary_tree.py", "length_bytes": 2633, "score": 4.28125, "int_score": 4, "content": "# Print a binary tree in an m*n 2D string array following these rules:\n\n# The row number m should be equal to the height of the given binary tree.\n# The column number n should always be an odd number.\n# The root node's value (in string format) should be put in the exactly middle of the first row it can be put. The column and the row where the root node belongs will separate the rest space into two parts (left-bottom part and right-bottom part). You should print the left subtree in the left-bottom part and print the right subtree in the right-bottom part. The left-bottom part and the right-bottom part should have the same size. Even if one subtree is none while the other is not, you don't need to print anything for the none subtree but still need to leave the space as large as that for the other subtree. However, if two subtrees are none, then you don't need to leave space for both of them.\n# Each unused space should contain an empty string \"\".\n# Print the subtrees following the same rules.\n# Example 1:\n# Input:\n# 1\n# /\n# 2\n# Output:\n# [[\"\", \"1\", \"\"],\n# [\"2\", \"\", \"\"]]\n# Example 2:\n# Input:\n# 1\n# / \\\n# 2 3\n# \\\n# 4\n# Output:\n# [[\"\", \"\", \"\", \"1\", \"\", \"\", \"\"],\n# [\"\", \"2\", \"\", \"\", \"\", \"3\", \"\"],\n# [\"\", \"\", \"4\", \"\", \"\", \"\", \"\"]]\n# Example 3:\n# Input:\n# 1\n# / \\\n# 2 5\n# / \n# 3 \n# / \n# 4 \n# Output:\n\n# [[\"\", \"\", \"\", \"\", \"\", \"\", \"\", \"1\", \"\", \"\", \"\", \"\", \"\", \"\", \"\"]\n# [\"\", \"\", \"\", \"2\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"5\", \"\", \"\", \"\"]\n# [\"\", \"3\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\"]\n# [\"4\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\"]]\n# Note: The height of binary tree is in the range of [1, 10].\n\ndef printTree(self, root: TreeNode) -> List[List[str]]:\n \n stack = [(root, 1, 1)]\n d = collections.defaultdict(dict)\n max_level = 1\n \n while stack:\n node, ind, level = stack.pop()\n max_level = max(level, max_level)\n d[level][ind] = node.val\n \n if node.left:\n stack.append((node.left, 2 * (ind - 1) + 1, level + 1))\n if node.right:\n stack.append((node.right, 2 * (ind - 1) + 2, level + 1))\n \n res = [[\"\"] * (2 ** (max_level) - 1) for _ in range(max_level)]\n \n def traverse(level, ind, i, j):\n if level not in d or ind not in d[level]: return\n res[level - 1][(i + j) // 2] = str(d[level][ind])\n traverse(level + 1, 2 * (ind - 1) + 1, i, (i + j) // 2 - 1)\n traverse(level + 1, 2 * (ind - 1) + 2, (i + j) // 2 + 1, j)\n \n traverse(1, 1, 0, len(res[0]) - 1)\n return res"} {"blob_id": "14281f6e51d73e402664c778b17e6955f6c16c8c", "repo_name": "keshavrkaranth/DSA", "path": "/recursion/recursive_digit_sum.py", "length_bytes": 367, "score": 3.609375, "int_score": 4, "content": "'''\n\n super_digit(9875)->9+8+7+5 = 29\n\tsuper_digit(29)->2 + 9 = 11\n\tsuper_digit(11)->1 + 1 = 2\n\tsuper_digit(2)-> 2\n'''\n\n\ndef superDigit(n, k):\n num = 0\n # find the sum of num\n for i in str(n):\n num += int(i)\n # multiply with occurence\n num *=k\n # recursive call\n return superDigit(num, 1) if num>9 else num\n\nprint(superDigit('420',1))\n\n"} {"blob_id": "c4c291736032f84236b72cf46d3d229c4325c50a", "repo_name": "maeda-kazuya/aoj", "path": "/10c.py", "length_bytes": 917, "score": 3.53125, "int_score": 4, "content": "n = int(input())\n\ndef solve(X, Y, Z):\n i = 0\n j = 0\n\n # if len(X) == 0 or len(Y) == 0:\n # return Z\n\n while True:\n print('\\n ----------------')\n print('# i: ' + str(i))\n print('# j: ' + str(j)) \n print('# X: ' + X)\n print('# Y: ' + Y)\n\n if i >= len(X) or j >= len(Y):\n break\n \n x = X[i]\n y = Y[j]\n\n if x == y:\n i += 1\n j += 1\n Z += x\n continue\n else:\n Z1 = solve(X[i+1:], Y, Z)\n Z2 = solve(X, Y[j+1:], Z)\n if (len(Z1) > len(Z2)):\n i += 1\n Z += Z1\n else:\n j += 1\n Z += Z2\n \n return Z\n \n# for i in range(n):\n# X = input()\n# Y = input()\n\n# Z = solve(X, Y, '')\n# print(Z)\n\nX = input()\nY = input()\nZ = solve(X, Y, '')\nprint(Z)\n\n"} {"blob_id": "3abb97dda3bf0f8dba87c5ebb82a79b2217e0e3a", "repo_name": "JohnEFerguson/ProjectEuler", "path": "/p24.py", "length_bytes": 508, "score": 3.734375, "int_score": 4, "content": "#!/usr/bin/env python\n\n#\n# Jack Ferguson 2018\n#\n# Problem 24\n#\n# q: \n# a: \n#\n\nfrom helpers.sorting import merge_sort\n\npermutations = []\n\ndef add_permutations(sofar, left):\n if len(sofar) == 10:\n permutations.append(sofar)\n else: \n if len(left) == 1: add_permutations(sofar + left, '')\n else:\n for i in range(0, len(left)):\n add_permutations(sofar + left[i], left[0:i] + left[i+1:])\n\nadd_permutations('', '0123456789')\n\nprint \"p24: \" + str(permutations[999999])\n\n"} {"blob_id": "17c2fa409980d9e2424a3b23a15447561fc344a3", "repo_name": "xuanyuwang/ctci", "path": "/ch4/node.py", "length_bytes": 8923, "score": 3.625, "int_score": 4, "content": "import unittest\nfrom collections import Counter\n\nclass Node():\n code = ''\n value = None\n weight = None\n leftChild = None\n rightChild = None\n parent = None\n depth = 0\n\n def __init__(self, value=None, freq=None,\n leftChild=None, rightChild=None, parent=None):\n self.value = value\n self.weight = freq\n self.leftChild = leftChild\n self.rightChild = rightChild\n self.parent = parent\n\n def isLeaf(self):\n return (not (self.leftChild or self.rightChild))\n\n def isRoot(self):\n return (not self.parent)\n\n def asLeftChildOf(self, parentNode):\n self.parent = parentNode\n self.depth = parentNode.depth + 1\n parentNode.leftChild = self\n\n def asRightChildOf(self, parentNode):\n self.parent = parentNode\n self.depth = parentNode.depth + 1\n parentNode.rightChild = self\n\n def bfs(self):\n totalNode = [self]\n nextLevel = [e for e in [self.leftChild, self.rightChild] if e]\n while len(nextLevel) > 0:\n currentlevel = nextLevel\n totalNode += nextLevel\n nextLevel = []\n for e in currentlevel:\n if e.leftChild:\n nextLevel.append(e.leftChild)\n if e.rightChild:\n nextLevel.append(e.rightChild)\n return totalNode\n\n def compareTree(self, anotherNode):\n nodeList = self.bfs()\n anotherNodeList = anotherNode.bfs()\n if len(nodeList) == len(anotherNodeList):\n if all([i.value == j.value for i, j in zip(nodeList, anotherNodeList)]):\n return True\n return False\n\n def compareNode(self, anotherNode):\n return anotherNode and self.value == anotherNode.value\n\n def isLeftChild(self):\n if (not self.parent):\n return False\n else:\n if self.compareNode(self.parent.leftChild):\n return True\n else:\n return False\n\n def isRightChild(self):\n if (not self.parent):\n return False\n else:\n if self.compareNode(self.parent.rightChild):\n return True\n else:\n return False\n\n def zig(self):\n root = self\n if root.isLeaf():\n return root\n else:\n tempRootParent = root.parent\n tempLrChild = root.leftChild.rightChild\n\n if root.isRoot():\n root.leftChild.parent = tempRootParent\n elif root.isLeftChild():\n root.leftChild.asLeftChildOf(tempRootParent)\n elif root.isRightChild():\n root.leftChild.asRightChildOf(tempRootParent)\n\n root.asRightChildOf(root.leftChild)\n if tempLrChild:\n tempLrChild.asLeftChildOf(root)\n else:\n root.leftChild = None\n\n\n newRoot = root.parent\n return newRoot\n\n def zag(self):\n root = self\n if root.isLeaf():\n return root\n else:\n tempRootParent = root.parent\n tempRlChild = root.rightChild.leftChild\n\n if root.isRoot():\n root.rightChild.parent = tempRootParent\n elif root.isLeftChild():\n root.rightChild.asLeftChildOf(tempRootParent)\n elif root.isRightChild():\n root.rightChild.asRightChildOf(tempRootParent)\n\n root.asLeftChildOf(root.rightChild)\n if tempRlChild:\n tempRlChild.asRightChildOf(root)\n else:\n root.rightChild = None\n\n\n newRoot = root.parent\n return newRoot\n\n def zigzig(self):\n root = self\n root = root.zig()\n root = root.zig()\n return root\n\n def zagzag(self):\n root = self\n root = root.zag()\n root = root.zag()\n return root\n\n def zigzag(self):\n root = self\n root.leftChild = root.leftChild.zag()\n newRoot = root.zig()\n return newRoot\n\n def zagzig(self):\n root = self\n root.rightChild = root.rightChild.zig()\n newRoot = root.zag()\n return newRoot\n\n def __repr__(self):\n return \"{} : {}, {}\\n\".format(self.value, self.code, self.weight)\n\n def __str__(self):\n return \"{} : {}, {}\\n\".format(self.value, self.code, self.weight)\n\n\nclass Test(unittest.TestCase):\n\n def testBsf(self):\n y = Node(value='y')\n x = Node(value='x')\n A = Node(value='A')\n B = Node(value='B')\n C = Node(value='C')\n A.asLeftChildOf(x)\n B.asRightChildOf(x)\n x.asLeftChildOf(y)\n C.asRightChildOf(y)\n\n answer = [y, x, C, A, B]\n\n self.assertEqual(y.bfs(), answer)\n\n def testCompare(self):\n y = Node(value='y')\n x = Node(value='x')\n A = Node(value='A')\n B = Node(value='B')\n C = Node(value='C')\n A.asLeftChildOf(x)\n B.asRightChildOf(x)\n x.asLeftChildOf(y)\n C.asRightChildOf(y)\n self.assertEqual(y.compareTree(y), True)\n\n def testZig(self):\n y = Node(value='y')\n x = Node(value='x')\n A = Node(value='A')\n B = Node(value='B')\n C = Node(value='C')\n A.asLeftChildOf(x)\n B.asRightChildOf(x)\n x.asLeftChildOf(y)\n C.asRightChildOf(y)\n\n y2 = Node(value='y')\n x2 = Node(value='x')\n C2 = Node(value='C')\n A2 = Node(value='A')\n B2 = Node(value='B')\n B2.asLeftChildOf(y2)\n C2.asRightChildOf(y2)\n y2.asRightChildOf(x2)\n A2.asLeftChildOf(x2)\n\n answer = y.zig()\n self.assertTrue(answer.compareTree(x2))\n\n def testZag(self):\n y = Node(value='y')\n x = Node(value='x')\n A = Node(value='A')\n B = Node(value='B')\n C = Node(value='C')\n A.asLeftChildOf(x)\n B.asRightChildOf(x)\n x.asLeftChildOf(y)\n C.asRightChildOf(y)\n\n y2 = Node(value='y')\n x2 = Node(value='x')\n C2 = Node(value='C')\n A2 = Node(value='A')\n B2 = Node(value='B')\n B2.asLeftChildOf(y2)\n C2.asRightChildOf(y2)\n y2.asRightChildOf(x2)\n A2.asLeftChildOf(x2)\n\n answer = x2.zag()\n self.assertTrue(answer.compareTree(y))\n\n def testZigZig(self):\n y = Node(value='y')\n x = Node(value='x')\n z = Node(value='z')\n C = Node(value='C')\n A = Node(value='A')\n B = Node(value='B')\n D = Node(value='D')\n\n y2 = Node(value='y')\n x2 = Node(value='x')\n z2 = Node(value='z')\n C2 = Node(value='C')\n A2 = Node(value='A')\n B2 = Node(value='B')\n D2 = Node(value='D')\n\n A.asLeftChildOf(x)\n B.asRightChildOf(x)\n x.asLeftChildOf(y)\n C.asRightChildOf(y)\n y.asLeftChildOf(z)\n D.asRightChildOf(z)\n\n C2.asLeftChildOf(z2)\n D2.asRightChildOf(z2)\n z2.asRightChildOf(y2)\n B2.asLeftChildOf(y2)\n A2.asLeftChildOf(x2)\n y2.asRightChildOf(x2)\n\n answer = z.zigzig()\n self.assertTrue(answer.compareTree(x2))\n\n def testZagZag(self):\n y = Node(value='y')\n x = Node(value='x')\n z = Node(value='z')\n C = Node(value='C')\n A = Node(value='A')\n B = Node(value='B')\n D = Node(value='D')\n\n y2 = Node(value='y')\n x2 = Node(value='x')\n z2 = Node(value='z')\n C2 = Node(value='C')\n A2 = Node(value='A')\n B2 = Node(value='B')\n D2 = Node(value='D')\n\n A.asLeftChildOf(x)\n B.asRightChildOf(x)\n x.asLeftChildOf(y)\n C.asRightChildOf(y)\n y.asLeftChildOf(z)\n D.asRightChildOf(z)\n\n C2.asLeftChildOf(z2)\n D2.asRightChildOf(z2)\n z2.asRightChildOf(y2)\n B2.asLeftChildOf(y2)\n A2.asLeftChildOf(x2)\n y2.asRightChildOf(x2)\n\n answer = x2.zagzag()\n self.assertTrue(answer.compareTree(z))\n\n def testZigzag(self):\n y = Node(value='y')\n x = Node(value='x')\n z = Node(value='z')\n C = Node(value='C')\n A = Node(value='A')\n B = Node(value='B')\n D = Node(value='D')\n\n y2 = Node(value='y')\n x2 = Node(value='x')\n z2 = Node(value='z')\n C2 = Node(value='C')\n A2 = Node(value='A')\n B2 = Node(value='B')\n D2 = Node(value='D')\n B.asLeftChildOf(x)\n C.asRightChildOf(x)\n A.asLeftChildOf(y)\n x.asRightChildOf(y)\n y.asLeftChildOf(z)\n D.asRightChildOf(z)\n\n A2.asLeftChildOf(y2)\n B2.asRightChildOf(y2)\n C2.asLeftChildOf(z2)\n D2.asRightChildOf(z2)\n y2.asLeftChildOf(x2)\n z2.asRightChildOf(x2)\n\n answer = z.zigzag()\n self.assertTrue(answer.compareTree(x2))\n\nif __name__ == '__main__':\n unittest.main()\n"} {"blob_id": "a64d765cea9b7477980a69fc91dacb0cd4c87196", "repo_name": "Shelnutt2/MAT4401", "path": "/Project2/ode.py", "length_bytes": 9352, "score": 3.59375, "int_score": 4, "content": "#!/bin/python\n#Seth Shelnutt\n#42941969\n#MAT4401\n\nimport argparse, math, sympy, time\nimport numpy as np\nfrom matplotlib import pyplot\n\ndef Euler(h,f,x1,x2,y1):\n y = sympy.Symbol('y') #Make y symbolic\n x = sympy.Symbol('x') #Make x symbolic\n func = f\n n = (int)((x2-x1)/h) #Number of steps\n xk = x1 #Set initial Values\n ya = y1 #Set initial Values\n xpoints = []\n ypoints = []\n xpoints.append(xk) #Add inital points to point list for graphing\n ypoints.append(ya) #Add inital points to point list for graphing\n\n start = time.time() \n for i in range(n):\n ya += h * f(xk, ya) #Euler Method\n xk += h #Move to next x values\n xpoints.append(xk) #Add x coordinate to x list for graph\n ypoints.append(ya) #Add y coordinate to y list for graph\n end = time.time()\n print(\"It took \" + str(end-start)+\" seconds to calculate\")\n return[xpoints,ypoints]\n\ndef midpoint(h,f,x1,x2,y1): #Define midpoint method\n y = sympy.Symbol('y') #Make y symbolic\n x = sympy.Symbol('x') #Make x symbolic\n n = (int)((x2-x1)/h)\n xk = x1 #Set initial Values\n ya = y1 #Set initial Values\n xpoints = []\n ypoints = []\n xpoints.append(xk) #Add inital points to point list for graphing\n ypoints.append(ya) #Add inital points to point list for graphing\n\n start = time.time()\n for i in range(n): #Iterate over the nubmer of steps\n ya += h*f(xk + 0.5*h, ya + 0.5*h*f(xk,ya)) #Midpoint method\n xk += h #Move to next x values\n xpoints.append(xk) #Add x coordinate to x list for graph\n ypoints.append(ya) #Add y coordinate to y list for graph\n end = time.time()\n print(\"It took \" + str(end-start)+\" seconds to calculate\")\n return[xpoints,ypoints]\n\ndef trapezoidODE(h,f,x1,x2,y1):\n y = sympy.Symbol('y') #Make y symbolic\n x = sympy.Symbol('x') #Make x symbolic\n n = (int)((x2-x1)/h)\n xk = x1 #Set initial Values\n ya = y1 #Set initial Values\n xpoints = []\n ypoints = []\n xpoints.append(xk) #Add inital points to point list for graphing\n ypoints.append(ya) #Add inital points to point list for graphing\n start = time.time()\n for i in range(n):\n ya += .5*h*f(xk , ya) + .5*h*f(xk+h,ya+h*f(xk,ya)) #Trapezoid iterative method\n xk += h #Move to next x values\n xpoints.append(xk) #Add x coordinate to x list for graph\n ypoints.append(ya) #Add y coordinate to y list for graph\n end = time.time()\n print(\"It took \" + str(end-start)+\" seconds to calculate\")\n return[xpoints,ypoints]\n\n\nxlot = np.linspace(0,3,1000)\n\ny = sympy.Symbol('y') #Make y symbolic\nx = sympy.Symbol('x') #Make x symbolic\ny1 = 3*y \ny2 = 1/(1+x**2)-2*y**2\nf = sympy.lambdify((x, y), y1, 'numpy') #Make it a function\nyone = Euler(.1,f,0,3,1)\nyfive = Euler(.05,f,0,3,1)\nyoone = Euler(.01,f,0,3,1)\nyofive = Euler(.005,f,0,3,1)\nz = np.exp(3*xlot)\n\npyplot.plot(yone[0],yone[1],label=\"Step .1\")\npyplot.plot(yfive[0],yfive[1],label=\"Step .05\")\npyplot.plot(yoone[0],yoone[1],label=\"Step .01\")\npyplot.plot(yofive[0],yofive[1],label=\"Step .005\")\npyplot.plot(xlot,z,label=\"e^3x\")\npyplot.legend(loc=2)\npyplot.ylim(0,5000)\npyplot.title(\"Euler method\")\npyplot.show()\n\nf = sympy.lambdify((x, y), y2, 'numpy') #Make it a function\nyone = Euler(.1,f,0,10,0)\nyfive = Euler(.05,f,0,10,0)\nyoone = Euler(.01,f,0,10,0)\nyofive = Euler(.005,f,0,10,0)\nz = xlot/(1+xlot**2)\n\npyplot.plot(yone[0],yone[1],label=\"Step .1\")\npyplot.plot(yfive[0],yfive[1],label=\"Step .05\")\npyplot.plot(yoone[0],yoone[1],label=\"Step .01\")\npyplot.plot(yofive[0],yofive[1],label=\"Step .005\")\npyplot.plot(xlot,z,label=\"1/(1+x^2)\")\npyplot.legend()\npyplot.ylim(0,0.8)\npyplot.title(\"Euler method\")\npyplot.show()\n\nf = sympy.lambdify((x, y), y1, 'numpy') #Make it a function\nyone = midpoint(.1,f,0,3,1)\nyfive = midpoint(.05,f,0,3,1)\nyoone = midpoint(.01,f,0,3,1)\nyofive = midpoint(.005,f,0,3,1)\nz = np.exp(3*xlot)\n\npyplot.plot(yone[0],yone[1],label=\"Step .1\")\npyplot.plot(yfive[0],yfive[1],label=\"Step .05\")\npyplot.plot(yoone[0],yoone[1],label=\"Step .01\")\npyplot.plot(yofive[0],yofive[1],label=\"Step .005\")\npyplot.plot(xlot,z,label=\"e^3x\")\npyplot.legend(loc=2)\npyplot.ylim(0,5000)\npyplot.title(\"Midpoint method\")\npyplot.show()\n\nf = sympy.lambdify((x, y), y2, 'numpy') #Make it a function\nyone = midpoint(.1,f,0,10,0)\nyfive = midpoint(.05,f,0,10,0)\nyoone = midpoint(.01,f,0,10,0)\nyofive = midpoint(.005,f,0,10,0)\nz = xlot/(1+xlot**2)\n\npyplot.plot(yone[0],yone[1],label=\"Step .1\")\npyplot.plot(yfive[0],yfive[1],label=\"Step .05\")\npyplot.plot(yoone[0],yoone[1],label=\"Step .01\")\npyplot.plot(yofive[0],yofive[1],label=\"Step .005\")\npyplot.plot(xlot,z,label=\"1/(1+x^2)\")\npyplot.legend()\npyplot.ylim(0,0.8)\npyplot.title(\"Midpoint method\")\npyplot.show()\n\nf = sympy.lambdify((x, y), y1, 'numpy') #Make it a function\nyone = trapezoidODE(.1,f,0,3,1)\nyfive = trapezoidODE(.05,f,0,3,1)\nyoone = trapezoidODE(.01,f,0,3,1)\nyofive = trapezoidODE(.005,f,0,3,1)\nz = np.exp(3*xlot)\n\npyplot.plot(yone[0],yone[1],label=\"Step .1\")\npyplot.plot(yfive[0],yfive[1],label=\"Step .05\")\npyplot.plot(yoone[0],yoone[1],label=\"Step .01\")\npyplot.plot(yofive[0],yofive[1],label=\"Step .005\")\npyplot.plot(xlot,z,label=\"e^3x\")\npyplot.legend(loc=2)\npyplot.ylim(0,5000)\npyplot.title(\"Trapezoid method\")\npyplot.show()\n\nf = sympy.lambdify((x, y), y2, 'numpy') #Make it a function\nyone = trapezoidODE(.1,f,0,10,0)\nyfive = trapezoidODE(.05,f,0,10,0)\nyoone = trapezoidODE(.01,f,0,10,0)\nyofive = trapezoidODE(.005,f,0,10,0)\nz = xlot/(1+xlot**2)\n\npyplot.plot(yone[0],yone[1],label=\"Step .1\")\npyplot.plot(yfive[0],yfive[1],label=\"Step .05\")\npyplot.plot(yoone[0],yoone[1],label=\"Step .01\")\npyplot.plot(yofive[0],yofive[1],label=\"Step .005\")\npyplot.plot(xlot,z,label=\"1/(1+x^2)\")\npyplot.legend()\npyplot.ylim(0,0.8)\npyplot.title(\"Trapezoid method\")\npyplot.show()\n\nf = sympy.lambdify((x, y), y1, 'numpy') #Make it a function\nyoneE = Euler(.1,f,0,3,1)\nyonem = midpoint(.1,f,0,3,1)\nyonet = trapezoidODE(.1,f,0,3,1)\nz = np.exp(3*xlot)\n\npyplot.plot(yoneE[0],yoneE[1],label=\"Euler\")\npyplot.plot(yonem[0],yonem[1],label=\"Midpoint\")\npyplot.plot(yonet[0],yonet[1],label=\"Trapezoid\")\npyplot.plot(xlot,z,label=\"e^3x\")\npyplot.legend(loc=2)\npyplot.ylim(0,5000)\npyplot.title(\"Step size .1\")\npyplot.show()\n\nf = sympy.lambdify((x, y), y1, 'numpy') #Make it a function\nyoneE = Euler(.05,f,0,3,1)\nyonem = midpoint(.05,f,0,3,1)\nyonet = trapezoidODE(.05,f,0,3,1)\nz = np.exp(3*xlot)\n\npyplot.plot(yoneE[0],yoneE[1],label=\"Euler\")\npyplot.plot(yonem[0],yonem[1],label=\"Midpoint\")\npyplot.plot(yonet[0],yonet[1],label=\"Trapezoid\")\npyplot.plot(xlot,z,label=\"e^3x\")\npyplot.legend(loc=2)\npyplot.ylim(0,5000)\npyplot.title(\"Step size .05\")\npyplot.show()\n\nf = sympy.lambdify((x, y), y1, 'numpy') #Make it a function\nyoneE = Euler(.01,f,0,3,1)\nyonem = midpoint(.01,f,0,3,1)\nyonet = trapezoidODE(.01,f,0,3,1)\nz = np.exp(3*xlot)\n\npyplot.plot(yoneE[0],yoneE[1],label=\"Euler\")\npyplot.plot(yonem[0],yonem[1],label=\"Midpoint\")\npyplot.plot(yonet[0],yonet[1],label=\"Trapezoid\")\npyplot.plot(xlot,z,label=\"e^3x\")\npyplot.legend(loc=2)\npyplot.ylim(0,5000)\npyplot.title(\"Step size .01\")\npyplot.show()\n\nf = sympy.lambdify((x, y), y1, 'numpy') #Make it a function\nyoneE = Euler(.005,f,0,3,1)\nyonem = midpoint(.005,f,0,3,1)\nyonet = trapezoidODE(.005,f,0,3,1)\nz = np.exp(3*xlot)\n\npyplot.plot(yoneE[0],yoneE[1],label=\"Euler\")\npyplot.plot(yonem[0],yonem[1],label=\"Midpoint\")\npyplot.plot(yonet[0],yonet[1],label=\"Trapezoid\")\npyplot.plot(xlot,z,label=\"e^3x\")\npyplot.legend(loc=2)\npyplot.ylim(0,5000)\npyplot.title(\"Step size .005\")\npyplot.show()\n\nf = sympy.lambdify((x, y), y2, 'numpy') #Make it a function\nyoneE = Euler(.1,f,0,10,0)\nyonem = midpoint(.1,f,0,10,0)\nyonet = trapezoidODE(.1,f,0,10,0)\nz = xlot/(1+xlot**2)\n\npyplot.plot(yoneE[0],yoneE[1],label=\"Euler\")\npyplot.plot(yonem[0],yonem[1],label=\"Midpoint\")\npyplot.plot(yonet[0],yonet[1],label=\"Trapezoid\")\npyplot.plot(xlot,z,label=\"1/(1+x^2)\")\npyplot.legend()\npyplot.ylim(0,0.8)\npyplot.title(\"Step size .1\")\npyplot.show()\n\nf = sympy.lambdify((x, y), y2, 'numpy') #Make it a function\nyoneE = Euler(.05,f,0,10,0)\nyonem = midpoint(.05,f,0,10,0)\nyonet = trapezoidODE(.05,f,0,10,0)\nz = xlot/(1+xlot**2)\n\npyplot.plot(yoneE[0],yoneE[1],label=\"Euler\")\npyplot.plot(yonem[0],yonem[1],label=\"Midpoint\")\npyplot.plot(yonet[0],yonet[1],label=\"Trapezoid\")\npyplot.plot(xlot,z,label=\"1/(1+x^2)\")\npyplot.legend()\npyplot.ylim(0,0.8)\npyplot.title(\"Step size .05\")\npyplot.show()\n\nf = sympy.lambdify((x, y), y2, 'numpy') #Make it a function\nyoneE = Euler(.01,f,0,10,0)\nyonem = midpoint(.01,f,0,10,0)\nyonet = trapezoidODE(.01,f,0,10,0)\nz = xlot/(1+xlot**2)\n\npyplot.plot(yoneE[0],yoneE[1],label=\"Euler\")\npyplot.plot(yonem[0],yonem[1],label=\"Midpoint\")\npyplot.plot(yonet[0],yonet[1],label=\"Trapezoid\")\npyplot.plot(xlot,z,label=\"1/(1+x^2)\")\npyplot.legend()\npyplot.ylim(0,0.8)\npyplot.title(\"Step size .01\")\npyplot.show()\n\nf = sympy.lambdify((x, y), y2, 'numpy') #Make it a function\nyoneE = Euler(.005,f,0,10,0)\nyonem = midpoint(.005,f,0,10,0)\nyonet = trapezoidODE(.005,f,0,10,0)\nz = xlot/(1+xlot**2)\n\npyplot.plot(yoneE[0],yoneE[1],label=\"Euler\")\npyplot.plot(yonem[0],yonem[1],label=\"Midpoint\")\npyplot.plot(yonet[0],yonet[1],label=\"Trapezoid\")\npyplot.plot(xlot,z,label=\"1/(1+x^2)\")\npyplot.legend()\npyplot.ylim(0,0.8)\npyplot.title(\"Step size .005\")\npyplot.show()\n"} {"blob_id": "f48042c33d1c01d6724b3ffe373181050094bf83", "repo_name": "Sebastiandt41/Compu-metodos", "path": "/Semana_4/Ode.py", "length_bytes": 1243, "score": 3.5, "int_score": 4, "content": "import numpy as np \nimport matplotlib.pyplot as plt \n\n#ODE's \n\n#Euler method \nb = 1\na = 0\nh = 0.1\nn = int(((b-a)/h)+1.0)\npuntos = np.linspace(a,b,n)\n#h = float((b-a)/(n-1.0))\t\n\nx = np.zeros(n)\ny = np.zeros(n)\n\nx[0] = a\ny[0] = 0\n\ndef funcion_p(x,y):\n\t\n\treturn 1+y*y\n\ndef euler():\n\tfor i in range(0,n-1):\n\t\tx[i+1] = x[i] + h \n\t\ty[i+1] = y[i] + h*funcion_p(x[i],y[i])\n\treturn x,y\n\n#Leap-frog - center difference\ndef leap():\n\tx[1] = a+h\n\ty[1] = y[0] + h*funcion_p(x[0],y[0])\n\tfor i in range(1,n-1):\n\t\tx[i+1] = x[i] + h \n\t\ty[i+1] = y[i-1] + 2*h*funcion_p(x[i],y[i])\n\t\n\treturn x,y\n\n#Runge-kutta 4 order \ndef runge():\n\tfor i in range(0,n-1):\n\t\n\t\tk1 = k1 = h*funcion_p(x[i],y[i])\n\t\tk2 = h*funcion_p(x[i]+(0.5*h),y[i]+(0.5*k1))\n\t\tk3 = h*funcion_p(x[i]+(0.5*h),y[i]+(0.5*k2))\n\t\tk4 = h*funcion_p(x[i]+h,y[i]+k3)\n\n\t\tprom = ((k1+(2.0*k2)+(2.0*k3)+k4))*(0.166666666)\n\n\t\tx[i+1] = x[i] + h\n\t\ty[i+1] = y[i] + prom\n\treturn x,y\n\t\n\nplt.plot(euler()[0],euler()[1],color='g',label ='Euler m.')\nplt.plot(leap()[0],leap()[1],color='b',label='Leap-frog m.')\nplt.plot(runge()[0],runge()[1],color='r',label='Runge-Kutta.')\nplt.title(\"Ordinary differencial equations methods\")\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\nplt.legend(loc =0)\nplt.show()\nplt.close()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"} {"blob_id": "c6782052ce678efadc40562cff5211c6ec5f1364", "repo_name": "kanhaichun/ICS4U", "path": "/Ivy232/Lily/A12Feb15.py", "length_bytes": 5674, "score": 4.3125, "int_score": 4, "content": "'''\r\nAssignment 12 - Recursive Algorithms - Towers of Hanoi\r\n\r\n\r\nCoding convention: \r\n(a) lower case file name\r\n(b) Lily, 25 Feb.2018, Recursive Algorithms\r\n(c) mixedCase variable names\r\nPurpose:\r\n(1) Create a class with functions for three recursive algorithms. \r\n(2)Include factorials, the Towers of Hanoi and any other recursive function. \r\n(3)Allow the user to choose any of the three functions and then interact with the function. \r\n(4)The program should provide adequate instructions and output to be useful.\r\n'''\r\n\r\n\r\nfrom turtle import *\r\n\r\nclass Recur:\r\n def func1(self,x): #This is for the game about factorial\r\n if x == 1: #define a number when x = 1, allowing the function to recur.\r\n return 1 #THis is to provide the key unknown variable in the end.\r\n else:\r\n return x * self.func1(x-1) #This is to calculate the factorial.\r\n \r\n def tower(self, N, Beg, Aux, End): #This is for the game about Towers of Hanoi.\r\n if N == 1: #This is to move the botton tower to the \"pole of End\" after moving the other to the \"pole of Auxiliary\".\r\n print(Beg + \" \u2013> \" + End) #This is to print out the step taken.\r\n else:\r\n self.tower(N-1,Beg, End, Aux) #This is to print all the steps taken before there is only one botton tower left in the \"pole of Beginning\".\r\n self.tower(1,Beg, Aux, End) #This is to move the botton tower to the \"pole of End\" after moving the other to the \"pole of Auxiliary\".\r\n self.tower(N-1, Aux, Beg, End) #This is to move all of the towers except for the botton one to the \"pole of End\".\r\n\r\n def func3(self,length, depth): #This is the function of drawing a snowflake.\r\n if depth == 0:\r\n forward(length) #This is to go forward for 1 unit\r\n else:\r\n self.func3(length/3, depth-1) #This is the start of the loop.\r\n right(60) #This step is to make a turn and also connect the end of every loop.\r\n self.func3(length/3, depth-1) #second loop\r\n left(120) #This step is to make a turn and also connect the end of every loop.\r\n self.func3(length/3, depth-1) #third loop\r\n right(60) #This step is to make a turn and also connect the end of every loop.\r\n self.func3(length/3, depth-1) #forth loop\r\n\r\n \r\n \r\n def func3_(self,length,repeat,spe):\r\n speed(spe) #This is to define a speed for Turtle.\r\n for i in range(3): #There are mainly three parts in a flake\r\n self.func3(length,repeat) #This is to call the function \"func3\" to draw the three sides of a complete snowflake. (We know the prototype of a snowflake is a triangle with three sides.)\r\n left(120) #This is to make a turn when a loop of function \"func3\" is finished.\r\n #if input(\"Do you want to quit the snowflake?\") == \"yes\":\r\n bye() #This is to quit this snowflake-drawing-game.\r\n \r\n def control(self): #Create a function for the initiation of the whole game.\r\n self.playGame = True # This is to create a condition for the initiation of the game.\r\n while (self.playGame == True): #This is to make orders when the prerequisite is met.\r\n print(\"There are three games available: for Factorials; for Towers of Hanoi; for Drawing a snowflake \")\r\n print(\"\")\r\n print(\"You can also type in to quit the games.\")\r\n print(\"\")\r\n choi=input(\"Please type in the one you would like to play:\") #This is to require the player to make a choice.\r\n if choi == \"A\": #This is to direct the player to certain type of game.\r\n number = int(input(\"For what number do you want to figure out the factorial?\"))\r\n print(\"The factorial of \" + str(number) + \" is \" + str(self.func1(number)))\r\n if choi == \"B\": #This is to direct the player to certain type of game.\r\n number = int(input(\"How many towers do you want for the Towers of Hanoi?\"))\r\n print(\"\")\r\n print(\"The towers should be moved like below:\")\r\n print(\"\")\r\n print(\"(attention: A, B and C below represent pole of beginning, pole of auxiliary and pole of end respectively.)\")\r\n self.tower(number, \"A\", \"B\", \"C\") #This is to print out the way the towers are moved.\r\n if choi == \"C\": #This is to direct the player to certain type of game.\r\n length = int(input(\"What length of the six sides do you want for the snowflake?(Please enter a number big enough)\"))\r\n repeat= int(input(\"How many times of divergence do you want for the snowflake?(Please do not enter a number more than 5)\"))\r\n spe = int(input(\"What drawing speed do you want for the snowflake?\"))\r\n self.func3_(length, repeat, spe)\r\n if choi == \"E\": #This is to provide the player a choice to quit the whole game when they want to.\r\n self.playGame = False #This is to cancel the base of the whole game when the player chooses to quit.\r\n else: \r\n continue #This is to keep the game working when the player wants to continue\r\n \r\nprint(\"Welcome to the Game Centre! Hope you have fun and enjoy yourself here!\") \r\nstart = Recur() #This is to create a instance for the class.\r\nstart.control() #This is to call the function in the class with the instance.\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n'''\r\n=======\r\n>>>>>>> 81e8aa76a02d1c71b464c2e0e4b35300b428e514\r\n'''\r\n"} {"blob_id": "74b5f808031fdc7356a2d8ea4c60ea50787f288f", "repo_name": "amallya88/py-functions", "path": "/rice_python_courses/intro_scripting_specialization/sieve_of_eratosthenes.py", "length_bytes": 1418, "score": 4.03125, "int_score": 4, "content": "\"\"\"\nImplement the Sieve of Eratosthenes\nhttps://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\n\"\"\"\nimport textwrap\nimport timeit\n\nwrapper = textwrap.TextWrapper(width=80)\n\n\ndef compute_primes(bound):\n \"\"\"\n Return a list of the prime numbers in range[2, bound]\n \"\"\"\n lst_numbers = list(range(2, bound + 1))\n prime_status = [True] * (bound + 1)\n # checking for primality a different problem than generating list of primes\n # so assume all numbers in list are primes, until proven False\n # prime_status[index] stores the primality of lst_numbers[index]\n lst_primes = [] # returned list of prime numbers\n for divisor in lst_numbers:\n if prime_status[divisor]:\n lst_primes.append(divisor)\n for factor in range(divisor ** 2, bound + 1, divisor):\n # during each iteration of outer loop all factors of divisor will be marked as not prime (False)\n prime_status[factor] = False\n return lst_primes\n\n\ndef get_primes_lst(bound):\n lst_primes = compute_primes(bound)\n return lst_primes\n\n\nnum_of_primes = 10000000\nstart_time = timeit.default_timer()\nlst_primes = get_primes_lst(num_of_primes)\nprint(\"time to generate\", num_of_primes, \"prime numbers\", timeit.default_timer() - start_time)\nprint(\"there are \", len(lst_primes), \"primes in the first \", num_of_primes, \"numbers\")\n\n# for elm in wrapper.wrap(str(lst_primes)):\n# print(elm)\n"} {"blob_id": "28c471b6e7601b8e1b5b65384770da5802a8eb41", "repo_name": "AlessSilva/IA-2019.2---Problemas-de-Busca", "path": "/Trabalho1_IA_/C\u00f3digoPy/Trabalho_IA_.py", "length_bytes": 14702, "score": 4.0, "int_score": 4, "content": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\n#Sobre a modelagem do problema das 'N Rainhas':\n#\n# Estados de Busca: \n# * Um estado \u00e9 representado por uma lista 'tabuleiro' de inteiros de tamanho at\u00e9 n\n# * Os valores de 'tabuleiro' est\u00e3o entre [-1,n-1], sem repeti\u00e7\u00e3o\n# * tabuleiro[i] = j, significa que na linha i e coluna j existe uma rainha (exce\u00e7\u00e3o j=-1)\n# * tabuleiro[i] = -1, significa que na linha i n\u00e3o cont\u00e9m nenhuma rainha\n# Opera\u00e7\u00f5es:\n# * Adicionar uma rainha na primeira linha que n\u00e3o cont\u00e9m uma rainha, sem que ocorra ataques\n# Estado Objetivo:\n# * tabuleiro[i] diferente de '-1' para todo i em [0,n-1]\n\n\n# In[2]:\n\n\n#Implementa\u00e7\u00e3o da FILA\n\nclass Fila(object):\n #Construtor\n def __init__(self):\n self.dados = []\n \n #Inserir : insere elemento na Fila\n def insere(self, elemento):\n self.dados.append(elemento)\n \n #Retirar : retira e retorna o primeiro elemento da Fila\n def retira(self):\n return self.dados.pop(0)\n \n def primeiro(self):\n return self.dados[0]\n\n #Vazia : verifica se a Fila est\u00e1 vazia\n def vazia(self):\n return len(self.dados) == 0\n\n\n# In[3]:\n\n\n#Implementa\u00e7\u00e3o da Pilha\n\nclass Pilha(object):\n #Construtor\n def __init__(self):\n self.dados = []\n \n #Empilhar : insere elemento na Pilha\n def empilha(self, elemento):\n self.dados.append(elemento)\n \n def top(self):\n if not self.vazia():\n return self.dados[-1]\n\n #Desempilhar : retira e retorna o \u00faltimo elemento da Pilha\n def desempilha(self):\n if not self.vazia():\n return self.dados.pop(-1)\n \n #Vazia : verifica se a Pilha est\u00e1 vazia\n def vazia(self):\n return len(self.dados) == 0\n\n\n# In[4]:\n\n\n# Classe Estado : representa um estado poss\u00edvel do problema das 'N Rainha'\n# *Atributos: \n# 'n' - N\u00famero de rainhas\n# 'tabuleiro' - Lista que representa a configura\u00e7\u00e3o do tabuleiro\n#\n# *M\u00e9todos:\n# 'validaOperacao(i,j)' - Retorna 'True', caso inserir uma rainha na linha i\n# e coluna j n\u00e3o coloca outra rainha em risco.\n# Retorna 'False', caso contr\u00e1rio\n# 'isObjetivo()' - Retorna 'True', caso o estado seja um estado objetivo.\n# Retorna 'False', caso contr\u00e1rio\n# 'gerarVizinhos(i)' - Retorna a lista de vizinhos do estado inserindo uma rainha\n# na linha i\n\nclass Estado(object):\n \n #Construtor\n def __init__(self, n):\n self.n = n\n self.tabuleiro = []\n \n def validaOperacao(self,i,j):\n #Para verificar se existe uma rainha \u00e9 atacada pelas diagonais \u00e9 verificado se existe uma soma i+j \n #ou uma subtra\u00e7\u00e3o i-j\n soma = []\n sub = []\n for i0 in range(self.n):\n if self.tabuleiro[i0] != -1:\n soma.append(i0+self.tabuleiro[i0])\n sub.append(i0-self.tabuleiro[i0])\n #Verificando se:\n # -J\u00e1 existe uma rainha na coluna j\n # -J\u00e1 existe uma rainha na diagonal principal\n # -J\u00e1 existe uma rainha na diagonal secund\u00e1ria\n if self.tabuleiro.count(j) > 0 or soma.count(i+j) > 0 or sub.count(i-j) > 0:\n return False\n return True\n \n def isObjetivo(self):\n #Pela modo como a programa\u00e7\u00e3o do problema foi construida, um estado objetivo \u00e9 aquele\n #em que todas as linhas possuem uma rainha (A aus\u00eancia de uma rainha \u00e9 representado pelo valor '-1')\n for i in range(self.n):\n if self.tabuleiro[i] == -1: #Se pelo menos uma linha cont\u00e9m '-1', o estado n\u00e3o \u00e9 objetivo\n return False\n return True\n \n def gerarVizinhos(self, i):\n #Como dito anteriormente, essa fun\u00e7\u00e3o retorna todos os vizinhos v\u00e1lidos do estado, inserindo\n #uma rainha na linha i\n vizinhos = []\n for j in range(self.n): #Ser\u00e1 testado todas as possibilidades de j (coluna)\n if self.validaOperacao(i,j): #Caso inserir na linha i o valor j seja v\u00e1lido:\n aux = list.copy(self.tabuleiro) #1-Fazer uma c\u00f3pia do tabuleiro do estado\n aux[i] = j #2-Na c\u00f3pia, inserir na linha i o valor j\n vizinhos.append(aux) #3-Adicionar a c\u00f3pia na lista de vizinhos v\u00e1lidos\n return vizinhos #Retorna a lista de vizinhos\n\n\n# In[5]:\n\n\n#Implementa\u00e7\u00e3o da Busca em Profundidade(DFS) para o problema das 'N Rainhas'\n\ndef BFS( inicial ):\n\n n = inicial.n\n \n filaEstados = Fila() #Fila respons\u00e1vel por guardar informa\u00e7\u00e3o sobre um caminho(lista de estados)\n filaIndices = Fila() #Fila respons\u00e1vel por guardar informa\u00e7\u00e3o da pr\u00f3xima linha a ser preenchida\n #A ideia \u00e9 que as filas tenham sempre o mesmo tamanho.\n \n filaEstados.insere( [inicial] ) #O caminho inicial \u00e9 formado apenas pelo estado inicial\n filaIndices.insere( 0 ) #No caminho inicial, o \u00faltimo estado (o estado inicial) ter\u00e1 que \n #inserir um elemento na linha 0 \n\n ordemGerados = [ [inicial] ] #Lista para guardar a ordem em que os caminhos s\u00e3o gerados.\n #Inicialmente recebe o caminho inicial\n \n solucao = False #Vari\u00e1vel para identificar se existe solu\u00e7\u00e3o\n sair = False #Vari\u00e1vel para identificar se precisa mostrar passo a passo\n \n while (not filaEstados.vazia()) :\n \n #--------------------- Apenas Intera\u00e7\u00e3o ---------------------\n if not sair:\n print('\\n\\t'+'\\033[31m'+'Estado da Fila'+'\\033[0;0m')\n print('\\033[32m'+'N\u00famero de elementos:'+'\\033[0;0m'+str(len(filaEstados.dados)))\n print('\\033[32m'+'Elemento do topo:'+'\\033[0;0m')\n for x in filaEstados.primeiro():\n print('\\033[46m'+str(x.tabuleiro)+'\\033[0;0m')\n if str(input('Aperte ENTER para continuar ou digite E para sair')) == 'E':\n sair = True\n #---------------------------------------------------------------\n \n #Sobre as duas primeiras vari\u00e1veis auxiliares:\n # aux1 cont\u00e9m um caminho\n # aux1[-1] \u00e9 o \u00faltimo estado( \u00faltima configura\u00e7\u00e3o do tabuleiro ) do caminho aux1\n # aux2 cont\u00e9m a linha onde deve ser inserido uma rainha em aux[-1]\n \n aux1 = filaEstados.retira()\n aux2 = filaIndices.retira()\n \n if( aux1[-1].isObjetivo() ): #Verificar se aux1[-1] \u00e9 um objetivo\n solucao = True\n \n #--------------------- Apenas Intera\u00e7\u00e3o ---------------------\n if not sair:\n print(\"\\nElemento do topo \u00e9 um objetivo !\")\n if str(input('Aperte ENTER para continuar ou digite E para sair')) == 'E':\n sair = True\n break\n #------------------------------------------\n \n else:\n \n #--------------------- Apenas Intera\u00e7\u00e3o ---------------------\n if not sair:\n print(\"\\nElemento do topo n\u00e3o \u00e9 um objetivo. Hora de gerar seus vizinhos\")\n if str(input('Aperte ENTER para continuar ou digite E para sair')) == 'E':\n sair = True\n #------------------------------------------\n \n vizinhos = aux1[-1].gerarVizinhos(aux2) #Gerar os vizinhos de aux1[-1] que inserem\n #uma rainha na linha aux2\n \n #--------------------- Apenas Intera\u00e7\u00e3o ---------------------\n if not sair:\n print('\\033[32m'+'\\nVizinhos: '+'\\033[0;0m',vizinhos)\n print(\"Vamos adicion\u00e1-los na fila !\")\n if str(input('Aperte ENTER para continuar ou digite E para sair')) == 'E':\n sair = True\n #------------------------------------------\n \n for v in vizinhos: #Para cada vizinho:\n aux3 = Estado(n) #1-Criar um novo estado aux3\n aux3.tabuleiro = v #2-Definir o vizinho v como tabuleiro de aux3\n aux4 = (list.copy(aux1)) #3-Criar uma c\u00f3pia aux4 de aux1 (c\u00f3pia do caminho)\n aux4.append(aux3) #4-Adicionar ao caminho aux4 o estado aux3\n ordemGerados.append(aux4) #5-Registrar o momento em que foi gerado o novo caminho\n filaEstados.insere(aux4) #6-Inserir o novo caminho na fila\n filaIndices.insere(aux2+1)#7-Inserir a informa\u00e7\u00e3o da pr\u00f3xima linha que deve ser preenchida\n \n if not solucao:\n print(\"\\nPoxa n\u00e3o tem solu\u00e7\u00e3o\")\n ordemGerados.append([inicial]) #Se n\u00e3o existe solu\u00e7\u00e3o, coloca o estado inicial no final do gerados \n #(\u00c9 apenas um simbolismo que eu adotei)\n \n return ordemGerados #Retornar todos os caminhos. A solu\u00e7\u00e3o ser\u00e1 o \u00faltimo caminho\n\n\n# In[6]:\n\n\n#Implementa\u00e7\u00e3o da Busca em Profundidade(DFS) para o problema das 'N Rainhas'\n\ndef DFS( inicial ):\n\n n = inicial.n\n \n pilhaEstados = Pilha() #Pilha respons\u00e1vel por guardar informa\u00e7\u00e3o sobre um caminho(lista de estados)\n pilhaIndices = Pilha() #Pilha respons\u00e1vel por guardar informa\u00e7\u00e3o da pr\u00f3xima linha a ser preenchida\n #A ideia \u00e9 que as pilhas tenham sempre o mesmo tamanho.\n \n pilhaEstados.empilha( [inicial] ) #O caminho inicial \u00e9 formado apenas pelo estado inicial\n pilhaIndices.empilha( 0 ) #No caminho inicial, o \u00faltimo estado (o estado inicial) ter\u00e1 que \n #inserir um elemento na linha 0 \n\n ordemGerados = [ [inicial] ] #Lista para guardar a ordem em que os caminhos s\u00e3o gerados.\n #Inicialmente recebe o caminho inicial\n \n solucao = False #Vari\u00e1vel para identificar se existe solu\u00e7\u00e3o\n sair = False #Vari\u00e1vel para identificar se precisa mostrar passo a passo\n \n while (not pilhaEstados.vazia()) :\n \n #--------------------- Apenas Intera\u00e7\u00e3o ---------------------\n if not sair:\n print('\\n\\t'+'\\033[31m'+'Estado da Pilha'+'\\033[0;0m')\n print('\\033[32m'+'N\u00famero de elementos:'+'\\033[0;0m'+str(len(pilhaEstados.dados)))\n print('\\033[32m'+'Elemento do topo:'+'\\033[0;0m')\n for x in pilhaEstados.top():\n print('\\033[46m'+str(x.tabuleiro)+'\\033[0;0m')\n if str(input('Aperte ENTER para continuar ou digite E para sair')) == 'E':\n sair = True\n #---------------------------------------------------------------\n \n #Sobre as duas primeiras vari\u00e1veis auxiliares:\n # aux1 cont\u00e9m um caminho\n # aux1[-1] \u00e9 o \u00faltimo estado( \u00faltima configura\u00e7\u00e3o do tabuleiro ) do caminho aux1\n # aux2 cont\u00e9m a linha onde deve ser inserido uma rainha em aux[-1]\n \n aux1 = pilhaEstados.desempilha()\n aux2 = pilhaIndices.desempilha()\n \n if( aux1[-1].isObjetivo() ): #Verificar se aux1[-1] \u00e9 um objetivo\n solucao = True\n \n #--------------------- Apenas Intera\u00e7\u00e3o ---------------------\n if not sair:\n print(\"\\nElemento do topo \u00e9 um objetivo !\")\n if str(input('Aperte ENTER para continuar ou digite E para sair')) == 'E':\n sair = True\n break\n #------------------------------------------\n \n else:\n \n #--------------------- Apenas Intera\u00e7\u00e3o ---------------------\n if not sair:\n print(\"\\nElemento do topo n\u00e3o \u00e9 um objetivo. Hora de gerar seus vizinhos\")\n if str(input('Aperte ENTER para continuar ou digite E para sair')) == 'E':\n sair = True\n #------------------------------------------\n \n vizinhos = aux1[-1].gerarVizinhos(aux2) #Gerar os vizinhos de aux1[-1] que inserem\n #uma rainha na linha aux2\n \n #--------------------- Apenas Intera\u00e7\u00e3o ---------------------\n if not sair:\n print('\\033[32m'+'\\nVizinhos: '+'\\033[0;0m',vizinhos)\n print(\"Vamos adicion\u00e1-los na pilha !\")\n if str(input('Aperte ENTER para continuar ou digite E para sair')) == 'E':\n sair = True\n #------------------------------------------\n \n for v in vizinhos: #Para cada vizinho:\n aux3 = Estado(n) #1-Criar um novo estado aux3\n aux3.tabuleiro = v #2-Definir o vizinho v como tabuleiro de aux3\n aux4 = (list.copy(aux1)) #3-Criar uma c\u00f3pia aux4 de aux1 (c\u00f3pia do caminho)\n aux4.append(aux3) #4-Adicionar ao caminho aux4 o estado aux3\n ordemGerados.append(aux4) #5-Registrar o momento em que foi gerado o novo caminho\n pilhaEstados.empilha(aux4) #6-Empilhar o novo caminho na pilha\n pilhaIndices.empilha(aux2+1)#7-Empilhar a informa\u00e7\u00e3o da pr\u00f3xima linha que deve ser preenchida\n \n if not solucao:\n print(\"\\nPoxa n\u00e3o tem solu\u00e7\u00e3o\")\n ordemGerados.append([inicial]) #Se n\u00e3o existe solu\u00e7\u00e3o, coloca o estado inicial no final do gerados \n #(\u00c9 apenas um simbolismo que eu adotei)\n \n return ordemGerados #Retornar todos os caminhos. A solu\u00e7\u00e3o ser\u00e1 o \u00faltimo caminho\n\n\n# In[ ]:\n\n\nn = int(input(\"Informe o n\u00famero de rainhas/dimens\u00e3o do tabuleiro: \"))\n\ninicial = Estado(n)\n\nwhile True:\n \n inicial.n = n\n for _ in range(n):\n inicial.tabuleiro.append(-1)\n \n print(\" Digite 1 para executar a BFS\")\n print(\" Digite 2 para executar a DFS\")\n print(\" Digite 3 para alterar o n\u00famero de rainhas\")\n print(\" Dizite 4 para sair\")\n \n op = str(input(\"Escolha uma opc\u00e3o: \"))\n \n print(\"\\n\")\n \n if op == '1':\n solucao = BFS(inicial)\n print(\"\\n\")\n print(\"Solu\u00e7\u00e3o Encontrada: \")\n for e in solucao[-1]:\n print('\\033[32m',e.tabuleiro,'\\033[0;0m')\n print(\"\\n\")\n \n if op == '2':\n solucao = DFS(inicial)\n print(\"\\n\")\n print(\"Solu\u00e7\u00e3o Encontrada: \")\n for e in solucao[-1]:\n print('\\033[32m',e.tabuleiro,'\\033[0;0m')\n print(\"\\n\")\n \n if op == '3':\n n = int(input(\"Informe o n\u00famero de rainhas/dimens\u00e3o do tabuleiro: \"))\n \n if op == '4':\n break\n \n del inicial.tabuleiro[:]\n \n\n"} {"blob_id": "3dc3daf7b285144691f03a5e94d8c4614e6ec98d", "repo_name": "FlowerMath/ivi", "path": "/bin_search.py", "length_bytes": 891, "score": 3.703125, "int_score": 4, "content": "def max_index(a: list, index: int) -> int:\n elem = a[index]\n while index < len(a) - 1 and elem == a[index + 1]:\n index = index + 1\n return index + 1\n\n\ndef min_index(a: list, index: int) -> int:\n elem = a[index]\n while index > 0 and elem == a[index - 1]:\n index = index - 1\n return index\n\n\ndef bin_search(a: list, elem: int) -> range:\n if len(a) == 0:\n return range(-1, -1)\n last = len(a)\n first = 0\n if elem == a[0]:\n return range(min_index(a, 0), max_index(a, 0))\n while last - first > 1:\n half = first + (last - first) // 2\n if a[half] > elem:\n last = half\n elif a[half] < elem:\n first = half\n else:\n return range(min_index(a, half), max_index(a, half))\n\n\nl = [1, 1, 1, 1, 3, 7, 10, 10, 10, 10, 10, 10]\nprint(bin_search(l, 10)) # 5-10\nprint(bin_search(l, 3)) # 0-3\n"} {"blob_id": "f9b0a4d85a0ee82d34a5d7377a43bb1916316d3e", "repo_name": "Ayush6459/Btech_project", "path": "/BtechProject/knapsack01Problem/knapsack01DP.py", "length_bytes": 1222, "score": 3.8125, "int_score": 4, "content": "import random\nimport numpy as np\n# number of items == number of values==n\n# kanapsack capacity == W\n# maximum range of values = v\n# maximum range of wieghts = w \n# randomly generated itmes array and values array\n# return the max weight that can fit in the knapsack\n\n\nn = int(input('enter the no. of itmes you have : \\n'))\nW = int(input('enter the maximum capacity of knapsack : \\n'))\nv = int(input('enter the maximum range of value to store : \\n'))\nw = int(input('enter the maximum range of the weight to store : \\n'))\n\n'''values=[random.randint(0,v) for i in range(0,n)]\nwieghts=[random.randint(0,w) for i in range(0,n)]'''\nvalues=np.random.randint(1,v,size=n)\nwieghts=np.random.randint(1,w,size=n)\n\n# initialize the memoize matrix \nt = [[-1 for i in range(W+1)] for j in range(n+1)]\n\ndef knapsack(wieghts,values,W,n):\n if n==0 or W==0:\n return 0\n if t[n][W] !=-1:\n return t[n][W]\n if wieghts[n-1]<=W:\n t[n][W]=max(values[n-1]+knapsack(wieghts,values,W-wieghts[n-1],n-1),knapsack(wieghts,values,W,n-1))\n return t[n][W]\n elif wieghts[n-1]>W:\n t[n][W]=knapsack(wieghts,values,W,n-1)\n return t[n][W]\n\n\nprint(values)\nprint(wieghts)\nprint(knapsack(wieghts,values,W,n))\n\n\n\n"} {"blob_id": "8ba356b650ec3ac42eccfba902c023e2cbdc87b5", "repo_name": "arthurDz/algorithm-studies", "path": "/microsoft/24_game.py", "length_bytes": 1679, "score": 3.65625, "int_score": 4, "content": "# You have 4 cards each containing a number from 1 to 9. You need to judge whether they could operated through *, /, +, -, (, ) to get the value of 24.\n\n# Example 1:\n# Input: [4, 1, 8, 7]\n# Output: True\n# Explanation: (8-4) * (7-1) = 24\n# Example 2:\n# Input: [1, 2, 1, 2]\n# Output: False\n# Note:\n# The division operator / represents real division, not integer division. For example, 4 / (1 - 2/3) = 12.\n# Every operation done is between two numbers. In particular, we cannot use - as a unary operator. For example, with [1, 1, 1, 1] as input, the expression -1 - 1 - 1 - 1 is not allowed.\n# You cannot concatenate numbers together. For example, if the input is [1, 2, 1, 2], we cannot write this as 12 + 12.\n\ndef judgePoint24(self, nums: List[int]) -> bool:\n def dfs(arr):\n if len(arr) == 1:\n return math.isclose(arr[0], 24.0)\n \n nex = [(i, t) for i in range(len(arr) - 1) for t in range(i + 1, len(arr))]\n for x, y in nex:\n rest = [i for i in range(len(arr)) if i != x and i != y]\n for operator in [\"*\", \"/\", \"+\", \"-\"]:\n if operator != '/' or arr[y] != 0:\n new_arr = [eval(\"%s%sfloat(%s)\" % (arr[x], operator, float(arr[y])))] + [arr[t] for t in rest] \n if dfs(new_arr): return True\n \n if operator in [\"/\", \"-\"]:\n if operator != '/' or arr[x] != 0:\n new_arr = [eval(\"%s%sfloat(%s)\" % (arr[y], operator, arr[x]))] + [arr[t] for t in rest] \n if dfs(new_arr): return True\n \n return False\n \n return dfs(nums)"} {"blob_id": "701720373cdc3322495ef5172dbf254d784b9bc2", "repo_name": "0as1s/leetcode", "path": "/856_score_of_partentheses.py", "length_bytes": 1211, "score": 3.515625, "int_score": 4, "content": "class Solution(object):\n def scoreOfParentheses(self, S):\n \"\"\"\n :type S: str\n :rtype: int\n \"\"\"\n stack = []\n for i in S:\n # print(stack)\n if i == \"(\":\n stack.append(\"(\")\n if i == \")\":\n if type(stack[-1]) == int: # (n <- ')'\n top = 2*stack.pop() # 2n\n if not stack:\n stack.append(top)\n continue\n\n if type(stack[-1]) == int: # m2n\n stack.append(top + stack.pop())\n else: # (2n\n stack.pop()\n stack.append(top)\n else: # (\n stack.pop()\n if not stack:\n stack.append(1)\n continue\n if type(stack[-1]) == int: # n( <- ')'\n stack.append(1 + stack.pop())\n else:\n stack.pop() # (( <- ')'\n stack.append(1)\n # print(stack)\n return stack[-1]\n\n\ns = Solution()\nprint(s.scoreOfParentheses(\"()((()))\"))"} {"blob_id": "4d9bf0d86187a2522c76be74fc376cfd482077d0", "repo_name": "yiclwh/MJ_2018", "path": "/844. Backspace String Compare.py", "length_bytes": 1450, "score": 4.09375, "int_score": 4, "content": "# Given two strings S and T, return if they are equal when both \\\n# are typed into empty text editors. # means a backspace character.\n\n\u5982\u679c\u4e0d\u80fd\u7528stack\u7684\u8bdd O(1) space\n\u5173\u952e\u662f\u5bf9string\u7684\u9884\u5904\u7406 \u4ece\u540e\u5f80\u524d str[index] == '#' or count > 0 \u7684\u65f6\u5019\u8981\u5f80\u524d\n\ndef backspaceCompare(self, S, T):\n \"\"\"\n :type S: str\n :type T: str\n :rtype: bool\n \"\"\"\n def processString(str, index):\n if index < 0 or str[index] != '#':\n return index\n count = 0\n while index >= 0 and (str[index] == '#' or count > 0):\n if str[index] == '#':\n count += 1\n else:\n count -= 1\n index -= 1\n return index\n \n e1 = len(S) - 1\n e2 = len(T) - 1\n while True:\n e1 = processString(S, e1)\n e2 = processString(T, e2)\n if e1 < 0 or e2 < 0 or S[e1] != T[e2]:\n return e1 == -1 and e2 == -1\n e1-=1\n e2-=1\n\nprint(backspaceCompare('ab##', 'c#d#')) #'bxj##tw', 'bxo#j##tw'))\n\ndef backspaceCompare(self, S, T):\n \"\"\"\n :type S: str\n :type T: str\n :rtype: bool\n \"\"\"\n def helper(s):\n stack= []\n for c in s:\n if c == '#':\n if stack:\n stack.pop()\n else:\n stack.append(c)\n return stack\n s1 = []\n s2 = []\n s1 = helper(S)\n s2 = helper(T)\n return s1 == s2\n #return ''.join(s1) == ''.join(s2)"} {"blob_id": "eeba0570bd1e42f134ea2829458fbb8d5dc22647", "repo_name": "oneshan/Leetcode", "path": "/accepted/011.container-with-most-water.py", "length_bytes": 1192, "score": 3.859375, "int_score": 4, "content": "#\r\n# [11] Container With Most Water\r\n#\r\n# https://leetcode.com/problems/container-with-most-water\r\n#\r\n# Medium (36.39%)\r\n# Total Accepted: \r\n# Total Submissions: \r\n# Testcase Example: '[1,1]'\r\n#\r\n# Given n non-negative integers a1, a2, ..., an, where each represents a point\r\n# at coordinate (i, ai). n vertical lines are drawn such that the two endpoints\r\n# of line i is at (i, ai) and (i, 0). Find two lines, which together with\r\n# x-axis forms a container, such that the container contains the most water.\r\n#\r\n# Note: You may not slant the container and n is at least 2.\r\n\r\n\r\nclass Solution(object):\r\n def maxArea(self, height):\r\n \"\"\"\r\n :type height: List[int]\r\n :rtype: int\r\n \"\"\"\r\n i, j = 0, len(height) - 1\r\n ans = 0\r\n while i < j:\r\n ans = max(ans, min(height[i], height[j]) * (j - i))\r\n if height[i] > height[j]:\r\n j -= 1\r\n else:\r\n i += 1\r\n return ans\r\n\r\nif __name__ == \"__main__\":\r\n sol = Solution()\r\n print(sol.maxArea([1, 1]))\r\n print(sol.maxArea([1, 2, 3, 4, 5]))\r\n print(sol.maxArea([5, 4, 3, 2, 1]))\r\n print(sol.maxArea([1, 5, 3, 2, 4]))\r\n"} {"blob_id": "7f970e94589e8e09df70fc1afa49a2c8bb666eb0", "repo_name": "transientlunatic/pylightcurve", "path": "/pylightcurve/filters.py", "length_bytes": 5575, "score": 3.59375, "int_score": 4, "content": "import numpy as np\nfrom math import factorial\nimport scipy.signal as signal\n\ndef savitzky_golay(y, window_size, order, deriv=0, rate=1):\n \"\"\"\n Smooth (and optionally differentiate) data with a Savitzky-Golay filter.\n The Savitzky-Golay filter removes high frequency noise from data.\n It has the advantage of preserving the original shape and\n features of the signal better than other types of filtering\n approaches, such as moving averages techniques. This implementation is\n taken from [3]_.\n\n Parameters\n ----------\n y : array_like, shape (N,)\n The values of the time history of the signal.\n window_size : int\n The length of the window. Must be an odd integer number.\n order : int\n The order of the polynomial used in the filtering.\n Must be less then `window_size` - 1.\n deriv: int, default: 0\n the order of the derivative to compute (default = 0 means only smoothing)\n\n Returns\n -------\n ys : :class:`numpy.ndarray`, shape (N)\n the smoothed signal (or it's n-th derivative).\n\n Notes\n -----\n The Savitzky-Golay is a type of low-pass filter, particularly\n suited for smoothing noisy data. The main idea behind this\n approach is to make for each point a least-square fit with a\n polynomial of high order over a odd-sized window centered at\n the point.\n\n Examples\n --------\n >>> t = np.linspace(-4, 4, 500)\n >>> y = np.exp( -t**2 ) + np.random.normal(0, 0.05, t.shape)\n >>> ysg = savitzky_golay(y, window_size=31, order=4)\n >>> import matplotlib.pyplot as plt\n >>> plt.plot(t, y, label='Noisy signal')\n >>> plt.plot(t, np.exp(-t**2), 'k', lw=1.5, label='Original signal')\n >>> plt.plot(t, ysg, 'r', label='Filtered signal')\n >>> plt.legend()\n >>> plt.show()\n\n References\n ----------\n .. [1] A. Savitzky, M. J. E. Golay, Smoothing and Differentiation of\n Data by Simplified Least Squares Procedures. Analytical\n Chemistry, 1964, 36 (8), pp 1627-1639.\n .. [2] Numerical Recipes 3rd Edition: The Art of Scientific Computing\n W.H. Press, S.A. Teukolsky, W.T. Vetterling, B.P. Flannery\n Cambridge University Press ISBN-13: 9780521880688\n .. [3] http://wiki.scipy.org/Cookbook/SavitzkyGolay\n \"\"\"\n\n try:\n window_size = np.abs(np.int(window_size))\n order = np.abs(np.int(order))\n except ValueError, msg:\n raise ValueError(\"window_size and order have to be of type int\")\n if window_size % 2 != 1 or window_size < 1:\n raise TypeError(\"window_size size must be a positive odd number\")\n if window_size < order + 2:\n raise TypeError(\"window_size is too small for the polynomials order\")\n order_range = range(order+1)\n half_window = (window_size -1) // 2\n # precompute coefficients\n b = np.mat([[k**i for i in order_range] for k in range(-half_window, half_window+1)])\n m = np.linalg.pinv(b).A[deriv] * rate**deriv * factorial(deriv)\n # pad the signal at the extremes with\n # values taken from the signal itself\n firstvals = y[0] - np.abs( y[1:half_window+1][::-1] - y[0] )\n lastvals = y[-1] + np.abs(y[-half_window-1:-1][::-1] - y[-1])\n y = np.concatenate((firstvals, y, lastvals))\n return np.convolve( m[::-1], y, mode='valid')\n\ndef running_median(y, window):\n \"\"\"\n A method to subtract a running median for smoothing data.\n\n Parameters\n ----------\n y : :class:`numpy.ndarray`\n A 1D array containing the data time series.\n window : int\n The number of time bins to use for the running median. At edges\n the window will be shorter.\n \n Returns\n -------\n ffit : :class:`numpy.ndarray`\n A 1D array containing the running median of the data time series.\n \"\"\"\n \n ffit = np.array([])\n idxs = range(len(y))\n halfwin = int(window/2)\n \n for i in range(len(y)):\n v = (idxs < (idxs[i]+halfwin)) & (idxs > (idxs[i]-halfwin))\n ffit = np.append(ffit, np.median(y[v]))\n\n return ffit\n\ndef highpass_filter_lightcurve(lightcurve, knee=(1./(0.3*86400.)), **kwargs):\n \"\"\"\n Detrends a light curve by high-pass filtering it using a third order Butterworth\n filter (:func:`scipy.signal.butter`).\n\n Parameters\n -----------\n x : :class:`numpy.ndarray`\n An array of time stamps\n z : :class:`numpy.ndarray`\n An array containing the time series data\n knee : float, optional, default: 3.858e-05\n The high-pass filter knee frequency in Hz (default is 3.858e-05 Hz or (1/0.3)/day).\n column : str, optional\n The column of data which the filter should be run over.\n Defaults to the default column if not set.\n\n Returns\n -------\n z : :class:`numpy.ndarray`\n An array which contains a time series which has been smoothed.\n\n \"\"\"\n\n data = lightcurve.data\n if \"column\" in kwargs:\n column = kwargs[\"column\"]\n z = np.array(data[column])\n else:\n z = lightcurve.clc\n \n x = lightcurve.cts\n #z = lightcurve.clc\n nans, stuff = lightcurve._nan_helper(z)\n z = lightcurve.nan_interp(z)\n dt = lightcurve.dt()\n if dt <= 0:\n raise(NameError(\"[ERROR] Sample time of 0 detected. Halting.\"))\n fs = lightcurve.fs()\n highcut = knee/(1./(2.*dt))\n zr = z[::-1] # Reverse the timeseries to remove phase offset\n zd = np.concatenate((zr, z))\n b, a = signal.butter(3, highcut, btype='highpass')\n y = signal.lfilter(b, a, zd)\n z = y[np.floor(len(y)/2):]\n return z"} {"blob_id": "842d41ea3fb6d9a869bf302beec638178a3312e8", "repo_name": "vxiaohan/LeetCodeProblems", "path": "/486_PredictTheWinner/486_PredictTheWinner.py", "length_bytes": 981, "score": 3.59375, "int_score": 4, "content": "import unittest\n\n\nclass Solution:\n def PredictTheWinner(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n if len(nums) == 0:\n return True\n if len(nums) == 1:\n return True if nums[0] >= 0 else False\n if len(nums) == 2:\n return True\n dp = [[0 for i in range(len(nums))] for j in range(len(nums))]\n for i in range(len(nums)):\n dp[i][i] = nums[i]\n for i in range(len(nums) - 1, -1, -1):\n for j in range(i + 1, len(nums)):\n dp[i][j] = max(nums[j] - dp[i][j - 1], nums[i] - dp[i + 1][j])\n return True if dp[0][-1] >= 0 else False\n\n\nclass TestPredictTheWinner(unittest.TestCase):\n def testPredictTheWinner(self):\n test = Solution()\n self.assertEqual(test.PredictTheWinner([1, 5, 2]), False)\n self.assertEqual(test.PredictTheWinner([1, 5, 233, 7]), True)\n\n\nif __name__ == '__main__':\n unittest.main()\n"} {"blob_id": "f9c9067076ac9f56926dd925bd5938dcdd11b687", "repo_name": "benjimr/Barcode-Reader", "path": "/barcode_reader.py", "length_bytes": 10967, "score": 3.578125, "int_score": 4, "content": "# The following submission is a\n# barcode and QR code detection \n# script that can also parse\n# some barcode data. The script\n# was researched and developed by:\n#\n# \tRobert Vaughan - C15341261\n# \t\tResearched detection\n# \tBen Ryan - C15507277\n# \t\tResearched reading the data\n# \tMohamad Zabad - C15745405\n# \t\tResearched image transformation\n#\n# All research and explanations of how each person came to their \n# solution over the number of weeks can be found within the project\n# blogs for as stated in class, no explanation within the code is required.\n\nimport numpy as np\nimport cv2\nimport math\nimport easygui\n \ndef intCheck(string):\n try: \n int(string)\n return True\n except ValueError:\n return False\n\t\t\n# Takes a an image and \n# finds the std and ceils it\n# to the nearest odd number\ndef nearestOddInteger(val):\n\treturn int(np.ceil(np.std(val)) // 2 * 2 + 1)\n\n# Checks to see if an image is\n# a barcode or not\ndef barcodeCheck(img):\n\theight, width, _ = np.shape(img)\n\n\tif width > (height + 5) or width < (height - 5):\n\t\tprint(\"Barcode: \" + str(width) + \" \" + str(height))\n\t\treturn True\n\telse:\n\t\tprint(\"QR: \" + str(width) + \" \" + str(height))\n\t\treturn False\n\n# Code to detect if a barcode\ndef codeDetection(img): \n\timage_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\theight, width, _ = np.shape(img)\n\t#print(np.shape(img))\n\t\n\t# Creating a blur kernal\n\tblur_k = (5,5)\n\n\timage_gray = cv2.GaussianBlur(image_gray, blur_k, 0)\n\n\t# Canny's the image with a dynamic threshold value\n\tcanny = cv2.Canny(image_gray, threshold1=255-nearestOddInteger(image_gray), threshold2=255)\n\t\n\t# Using a percentage of the square area to draw our kernal\n\tarea = int((math.sqrt(width * height)) * .02)\n\tstructEl = cv2.getStructuringElement(cv2.MORPH_RECT, (area,area))\n\n\t# Dilate the image to bind together areas with heavy\n\t# positive pixels\n\tdilation = cv2.dilate(canny, structEl, iterations = 2)\n\n\t# Takes the boundary from the contoured areas\n\t# To ensure that solid structures are present\n\tstructK = (4,4)\n\tstructEl = cv2.getStructuringElement(cv2.MORPH_RECT, structK)\n\tboundary = cv2.morphologyEx(dilation,cv2.MORPH_GRADIENT,structEl)\n\n\t# Getting the contours of the dilated image\n\tcontours, _ = cv2.findContours(boundary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)\n\tcv2.drawContours(image_gray, contours, -1, 255, 3)\n\n\t# Finding the biggest contour, which \n\t# should be our code\n\tc = max(contours, key = cv2.contourArea)\n\n\t# Gets the bounding co-ordinates of the\n\t# biggest contour to get the image\n\tx, y, width, height = cv2.boundingRect(c)\n\n\t# Get the rotated rect.\n\t# This is for later use\n\t# for the rotation stages of the image\n\trotRect = cv2.minAreaRect(c)\n\n\t# Creates a copy of an image\n\t# and draws an outline of the detected area from\n\t# our contouring\n\timg_copy = img.copy()\n\tcv2.rectangle(img_copy,(x, y),(x + width, y + height), (0,255,0), 2)\n\t\n\tcrop_img = img[y:y + height, x:x + width]\n \n\treturn crop_img, rotRect, img_copy\n\t\t\n#handles decoding barcodes\ndef decodeBarcode(img):\t\n\t#get dimensions\n\th, w, c = np.shape(img)\n\t\n\t#convert to grey and threshold it\n\timg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\t_, img = cv2.threshold(img, 128, 255, cv2.THRESH_BINARY)\n\t\n\t#closing image to clean up the barcode, remove numbers so they don't interfere with decoding\n\tstructEl = cv2.getStructuringElement(cv2.MORPH_RECT, (1, int(h/4)))\n\tmorphed = cv2.morphologyEx(img, cv2.MORPH_CLOSE, structEl)\n\t\n\t#if previous morph left mostly white, barcode is probably rotated 90 degrees\n\t#if this is the case morph using different shape structuring element\n\tif np.mean(morphed) > 240:\n\t\tstructEl = cv2.getStructuringElement(cv2.MORPH_RECT, (int(w/4), 1))\n\t\tmorphed = cv2.morphologyEx(img, cv2.MORPH_CLOSE, structEl)\n\t\t\n\t#get the binary code for each section of the barcode\n\t#black bar 1 white bar 0\n\tbinaryCode, finalImg = getBinary(morphed, h, w)\n\t\n\t#convert the binary code found in to the acutal barcode numbers\n\tfinalCode = convertBinary(binaryCode)\n\n\tif finalCode is None:\t\t\n\t\tfinalCode = \"Could not read correctly\"\n\t\n\tprint(\"CODE: \" + finalCode)\t\n\treturn finalCode\n\t\n#gets a binary string from the image\ndef getBinary(img, h, w):\n\t#calculate the exact boundaries/characteristics of the barcode for decoding\t\t\n\tstartX, endX, startY, endY, barWidth, img = findBounds(img, h, w)\n\n\tbinaryCode = ''\n\t\n\t#iterate over the barcode using above variables\n\tfor column in range(startX, endX, barWidth):\n\t\t#select bar\n\t\tline = img[startY: endY, column:column+barWidth]\n\t\t\n\t\t#find the avg value for the pixels in the selected bar\n\t\t\n\t\tavg = np.mean(line)\n\n\t\t#if in the upper half of values binary 0, else binary 1\n\t\tif avg > int((255/2)):\n\t\t\tbinaryCode += '0'\n\t\telse:\n\t\t\tbinaryCode += '1'\n\t\t\t\n\treturn binaryCode, img\n\n\ndef rotated(img_in):\n\n\t# copy of the image used for the rotation in the end\n\timg_copy = img_in.copy()\n\n\t# Grayscale converting\n\timage_gray = cv2.cvtColor(img_in, cv2.COLOR_BGR2GRAY)\n\tblur_k = (5,5)\n\t#Applying a GaussianBlur\n\timage_gray = cv2.GaussianBlur(image_gray, blur_k, 0)\n\t#Reversing the colours\n\tgray = cv2.bitwise_not(image_gray)\n\t# threshold the image\n\tthresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]\n\n\t# Storing the positive pixel locations ( 0 is off and 1 is on )\n\tcoords = np.column_stack(np.where(thresh > 0))\n\t# minAreaRect will determine the angle needed to align everything\n\tangle = cv2.minAreaRect(coords)[-1]\n\n\n\t# the `cv2.minAreaRect` function returns values in the\n\t# range [-90, 0); as the rectangle rotates clockwise the\n\t# returned angle trends to 0 -- in this special case we\n\t# need to add 90 degrees to the angle\n\tif angle < -45:\n\t\tangle = -(90 + angle)\n\n\t# otherwise, just take the inverse of the angle to make\n\t# it positive\n\telse:\n\t\tangle = -angle\n\n\t# rotating the image\n\t(h, w) = thresh.shape[:2]\n\tcenter = (w // 2, h // 2)\n\tM = cv2.getRotationMatrix2D(center, angle, 1.0)\n\trotated = cv2.warpAffine(img_copy, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)\n\n\treturn rotated\n\n\n#finding exact boundaries to be read\ndef findBounds(img, h , w):\n\tstartX = 0 \n\tendX = 0\n\tstartY = 0 \n\tendY = 0\n\tbarWidth = 1\n\t\n\t#calculate startx and barWidth\n\t#iterating over columns finding mean values until it finds one that is on avg black\n\tfor x in range(0,w):\n\t\t#cut the image in single pixel wide, full height bars, across the image\n\t\tcolumn = img[0:h,x:x+1]\n\t\t\t\n\t\t#if the mean is below 128 assume black, mark as start, and start recording the width of bars\n\t\tif np.mean(column) < 230:\n\t\t\tstartX = x\n\t\t\t\n\t\t\t#keep iterating from the start counting how wide the bar is\n\t\t\tfor x2 in range(x,w):\n\t\t\t\tcolumn2 = img[0:h,x2+1]\n\n\t\t\t\t#once it goes back to white on avg break, stop counting bar width\n\t\t\t\tif np.mean(column2) > 230:\n\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tbarWidth +=1\n\t\t\tbreak\n\t\t\n\t#calc endX, working backwwards from width to 0 finding where the end of the barcode is\n\tfor x in range(w-1, 0, -1):\n\t\tcolumn = img[0:h, x:x+1]\n\t\t\n\t\t#when found save it and break\n\t\tif np.mean(column) < 230:\n\t\t\tendX = x\n\t\t\tbreak\n\t\t\t\n\t#calc start y as above\n\tfor y in range(0, h):\n\t\trow = img[y:y+1, startX:endX]\n\t\t\n\t\tif np.mean(row) < 175:\n\t\t\tstartY = y\n\t\t\tbreak;\n\t\t\t\n\t#calc end y as above\n\tfor y in range(h-1, 0, -1):\n\t\trow = img[y:y+1,startX:endX]\n\t\n\t\tif np.mean(row) < 175:\n\t\t\tendY = y\n\t\t\tbreak;\n\n\t#if not oriented correctly rotate 90 degress\n\tif endX - startX < endY - startY:\n\t\t#crop the found area\n\t\tcrop_img = img[startY:endY, startX:endX]\n\t\th, w = np.shape(crop_img)\n\t\t\n\t\t#create new white image to fit the cropped image so rotating doesn't lose any code\n\t\twh = int(math.hypot(w, -h))\n\t\tnewImg = np.zeros((wh,wh), np.uint8)\n\t\tnewImg.fill(255)\n\t\t\n\t\tx1 = int((wh-w)/2)\n\t\ty1 = int((wh-h)/2)\n\t\t\n\t\tnewImg[y1:y1+h, x1:x1+w] = crop_img\n\t\t\n\t\tc = (wh/2,wh/2)\n\t\t\n\t\t#rotate 90\n\t\trotMx = cv2.getRotationMatrix2D(c, 90, 1)\n\t\trotImg = cv2.warpAffine(newImg, rotMx, (wh,wh), borderValue = (255,255,255))\n\n\t\t#find bounds in new image and overwrite previous bounds\n\t\th,w = np.shape(rotImg)\n\t\tstartX, endX, startY, endY, barWidth, img = findBounds(rotImg, h , w)\n\t\t\t\n\tshowImage(\"Rot\", img)\n\treturn startX, endX, startY, endY, barWidth, img\n\t\n#converts from binary to decimal\ndef convertBinary(binaryCode):\n\t#UPC-A codes\n\tleft = ['0001101', '0011001', '0010011', '0111101', '0100011', '0110001', '0101111', '0111011', '0110111', '0001011']\n\tright = ['1110010', '1100110', '1101100', '1000010', '1011100', '1001110', '1010000', '1000100', '1001000', '1110100']\n\n\t#if error found\n\tif errorCheck(binaryCode) is not True:\n\t\treturn\n\t\t\n\t#if the guard bars are in the correct location then the following should split the left and right side \n\t#exactly for decodoing\n\tleftSide = binaryCode[3:45]\n\trightSide = binaryCode[50:92]\n\t\n\tfinalLeft = convertSide(leftSide, left)\n\tfinalRight = convertSide(rightSide, right)\n\t\n\t#if converted sides are empty, code is probably upside down, so flip it\n\tif finalLeft == '' or finalRight == '':\n\t\trightSide, leftSide = leftSide[::-1], rightSide[::-1]\n\t\t\n\t\tfinalLeft = convertSide(leftSide, left)\n\t\tfinalRight = convertSide(rightSide, right)\n\t\t\n\tfinalCode = finalLeft + finalRight\n\treturn finalCode\n\t\n#checks guard bars are in the correct place and code is correct length\ndef errorCheck(binaryCode):\n\tsideGuard = '101'\n\tmidGuard = '01010'\n\n\tprint(len(binaryCode), binaryCode)\n\tif len(binaryCode) != 95:\n\t\t\tprint(\"incorrect length found\")\n\t\t\treturn False\n\t\t\t\n\t#checking if guard bars are in the correct place, otherwise don't bother checking the rest\n\t#only works for perfectly aligned and read.\n\tif binaryCode[0:3] == sideGuard and binaryCode[45:50] == midGuard and binaryCode[92:95] == sideGuard:\n\t\treturn True\n\t\n\treturn False\n\t\n#converts a side of the barcode from binary to decimal using provided list\ndef convertSide(side, bin):\n\tfinal = ''\n\t\n\tfor section in range(0,len(side)+1, 7):\n\t\tfor code in bin:\n\t\t\tif side[section:section+7] == code:\n\t\t\t\tfinal += str(bin.index(code))\n\t\t\t\tbreak\n\n\treturn final\n \n#shows image and hold window open\ndef showImage(title, image):\n\ts = np.shape(image)\n\n\tif s[0] > 1000 or s[1] > 1000:\n\t\timage = cv2.resize(image, (int(s[1]*.5), int(s[0]*.5)))\n\t\n\tcv2.imshow(title, image)\n\tcv2.waitKey(0)\n\t\n#aligns the image based on the rotation in the provided rotated rectangle\ndef align(crop_img, rotRect):\n\th, w, c = np.shape(crop_img)\n\n\t#create new white image for aligning\n\twh = int(math.hypot(w, - h))\n\tnewImg = np.zeros((wh, wh, c), np.uint8)\n\tnewImg.fill(255)\n\n\tx1 = int((wh-w)/2)\n\ty1 = int((wh-h)/2)\n\n\t# put orig inside new img\n\tnewImg[y1:y1+h, x1:x1+w] = crop_img\n\n\t# get centre\n\tc = (wh/2,wh/2)\n\n\t#rotate\n\trotMx = cv2.getRotationMatrix2D(c, rotRect[2], 1)\n\trotImg = cv2.warpAffine(newImg, rotMx, (wh,wh), borderValue = (255,255,255))\n\n\treturn rotImg\n\ndef main():\n\tfilename = easygui.fileopenbox()\n\timg = cv2.imread(filename)\n\n\tcopy = img.copy()\n\timg = rotated(img)\n\timg, rotRect, drawn = codeDetection(img)\n\n\tfinalCode = 'QR Code'\n\tif barcodeCheck(img):\n\t\taligned = align(img, rotRect)\n\t\tfinalCode = decodeBarcode(aligned)\n\t\t\n\tshowImage(finalCode, drawn)\n\nif __name__ == \"__main__\":\n main()"} {"blob_id": "b7f26c83f36b945b24b791c08fad8ae13972c5be", "repo_name": "SuperMartinYang/learning_algorithm", "path": "/leetcode/medium/add_two_numbers.py", "length_bytes": 1498, "score": 3.890625, "int_score": 4, "content": "# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def addTwoNumbers(self, l1, l2):\n \"\"\"\n reverse list\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n l1 = self.reverse_list(l1)\n l2 = self.reverse_list(l2)\n carry = 0\n cur_1 = l1\n cur_2 = l2\n res = ListNode(0)\n cur = res\n while cur_1 or cur_2:\n if cur_1 and cur_2:\n cur.next = ListNode((cur_1.val + cur_2.val + carry) % 10)\n carry = (cur_1.val + cur_2.val + carry) // 10\n cur_1 = cur_1.next\n cur_2 = cur_2.next\n else:\n tmp = cur_1 or cur_2\n cur.next = ListNode((tmp.val + carry) % 10)\n carry = (tmp.val + carry) // 10\n cur_1 = cur_1.next if cur_1 else None\n cur_2 = cur_2.next if cur_2 else None\n cur = cur.next\n if carry:\n cur.next = ListNode(carry)\n return self.reverse_list(res.next)\n\n def reverse_list(self, head):\n pre = None\n while head:\n _next = head.next\n head.next = pre\n pre = head\n head = _next\n return pre\n\n def addTwoNumbers2(self, l1, l2):\n \"\"\"\n use stack\n :param l1:\n :param l2:\n :return:\n \"\"\""} {"blob_id": "de92282c342b1b750c981f122da05bf193d8fa2f", "repo_name": "jasonkimprojects/rosalind-challenge", "path": "/CORR.py", "length_bytes": 3157, "score": 3.609375, "int_score": 4, "content": "# Copyright 2019 Jason Kim. All rights reserved.\n# CORR.py\n# My solution to CORR of the Rosalind Project.\n# Jason Kim\n# 7/30/2019\n\n\n# Returns the reverse complement of a DNA sequence.\ndef rev_complement(sequence):\n complement_of = {\n 'A': 'T',\n 'T': 'A',\n 'G': 'C',\n 'C': 'G'\n }\n seq_reverse = sequence[::-1]\n revc = ''\n for char in seq_reverse:\n revc += complement_of[char]\n return revc\n\n\n# Returns the Hamming distance between two DNA sequences.\ndef hamming_dist(first, second):\n assert len(first) == len(second)\n count = 0\n for i in range(len(first)):\n if first[i] != second[i]:\n count += 1\n return count\n\n\ndef main():\n file = open(\"rosalind_corr.txt\", \"r\")\n buffer = ''\n # Hash table to store sequences as keys and number of\n # occurrences as values. Does NOT include reverse complements.\n occurrences = {}\n for line in file:\n if line[0] == '>':\n if buffer:\n # Check the sequence and its reverse complement.\n # If either exists, increase value of key in hash table.\n if buffer in occurrences:\n occurrences[buffer] += 1\n elif rev_complement(buffer) in occurrences:\n occurrences[rev_complement(buffer)] += 1\n # Else, create a new key-value pair.\n else:\n occurrences[buffer] = 1\n # Reset buffer after addition.\n buffer = ''\n else:\n buffer += line.replace('\\n', '')\n # Must process the last buffer manually.\n file.close()\n if buffer in occurrences:\n occurrences[buffer] += 1\n elif rev_complement(buffer) in occurrences:\n occurrences[rev_complement(buffer)] += 1\n else:\n occurrences[buffer] = 1\n # Separate the CORRECT keys in the dictionary that\n # have a value (# of occurrences) of at least 2\n # into a list of correct sequences.\n correct_seqs = []\n for key in occurrences:\n if occurrences[key] >= 2:\n # Can't pop key yet because it breaks the iterator\n correct_seqs.append(key)\n # Now pop the keys that were copied into occurrences\n for duplicate_key in correct_seqs:\n occurrences.pop(duplicate_key)\n # Save length before adding reverse complements\n old_length = len(correct_seqs)\n # For all the correct sequences, append their reverse\n # complements to correct_seqs\n for i in range(old_length):\n # Because we're appending to the end, the items at\n # earlier indices are preserved.\n correct_seqs.append(rev_complement(correct_seqs[i]))\n # Now traverse over the incorrect sequences in the dictionary.\n for key in occurrences:\n # Compare the Hamming distance of this key with that of\n # all the correct sequences.\n for seq in correct_seqs:\n # Hamming distance is 1 with respect to exactly one\n # correct read, per the specifications.\n if hamming_dist(key, seq) == 1:\n print(key + \"->\" + seq)\n return\n\n\nif __name__ == \"__main__\":\n main()\n\n"} {"blob_id": "a2680a252bcea4a0956abecdb0d9dc579b6827d3", "repo_name": "wyaadarsh/LeetCode-Solutions", "path": "/Python3/0366-Find-Leaves-of-Binary-Tree/soln-1.py", "length_bytes": 693, "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\nclass Solution(object):\n def findLeaves(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[List[int]]\n \"\"\"\n dic = collections.defaultdict(list)\n def traverse(node):\n if not node:\n return 0\n left = traverse(node.left)\n right = traverse(node.right)\n lev = max(left, right) + 1\n dic[lev] += [node.val]\n return lev\n traverse(root)\n return [dic[lev] for lev in range(1, len(dic) + 1)]"} {"blob_id": "17776fa19edb5ccb29bc92350de69a3c5b42dd1c", "repo_name": "SR-Sunny-Raj/Hacktoberfest2021-DSA", "path": "/27. LeetCode Problems/56. Merge Intervals.py", "length_bytes": 1152, "score": 3.9375, "int_score": 4, "content": "\"\"\"\n56. Merge Intervals\nLink:- https://leetcode.com/problems/merge-intervals/\n\nGiven an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.\n\n \nExample 1:\n\nInput: intervals = [[1,3],[2,6],[8,10],[15,18]]\nOutput: [[1,6],[8,10],[15,18]]\nExplanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].\nExample 2:\n\nInput: intervals = [[1,4],[4,5]]\nOutput: [[1,5]]\nExplanation: Intervals [1,4] and [4,5] are considered overlapping.\n \n\nConstraints:\n\n1 <= intervals.length <= 104\nintervals[i].length == 2\n0 <= starti <= endi <= 104\n\n\"\"\"\n\nclass Solution:\n def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n intervals=sorted(intervals)\n mi=intervals[0][0]\n ma=intervals[0][1]\n ans=[]\n for i in intervals:\n if mi<=i[0]<=ma or mi<=i[1]<=ma:\n mi=min(mi,i[0])\n ma=max(ma,i[1])\n else:\n ans.append([mi,ma])\n mi=i[0]\n ma=i[1]\n ans.append([mi,ma])\n return ans\n"} {"blob_id": "046d3558bc3491f890ccae2943c72cee7a819729", "repo_name": "renacin/GradientDescent_From_Scratch", "path": "/Practice/GD_Basics.py", "length_bytes": 6638, "score": 4.15625, "int_score": 4, "content": "# Name: Renacin Matadeen\n# Student Number: N/A\n# Date: 09/21/2018\n# Course: N/A\n# Title Understanding Gradient Descent\n#\n#\n#\n#\n#\n# ----------------------------------------------------------------------------------------------------------------------\n\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# ----------------------------------------------------------------------------------------------------------------------\n\"\"\"\n\nIn order to understand machine learning, its inner workings, and how it can be used an individual must first understand \nthe basics of the field. One of the most important concepts in machine learning is the ability to learn from data, and \nmake actions based on them. In its simplest form gradient descent provides computers with the ability to iteratively\nfind the lowest cost for a specific function. This is important as machines need a method of determining which answer is\nthe most appropriate given a task. \n\nAs a note:\n Gradient Descent Implements:\n + Calculus\n - Derivatives\n - Partial Derivatives\n \n + Programmatic Math\n - Effectively Implementing Equations\n \nThings To Remember:\n Mean Squared Error\n + Gradient descent looks to minimize error, or cost of the overall prediction to ensure optimal accuracy. \n The distance between a sample point and the line of best fit is considered the error, note that the error is \n squared to account for negative values as well as return a observation of magnitude. \n \n The Formula For MSE Is:\n\n 1/N * \u03a3(y_i - y_predicted)^2\n \n Where:\n y_predicted = (mx_i + b)\n \n When you're trying to minimize cost, your answer depends on two other variables (m, and b)\n The theoretical space becomes 3-Dimensional. \n \n Always look for the global minimum, never the local minimum!\n \n As you get closer to the minimum, make smaller steps. This is important as you don't want to overshoot your\n descent! Find the slope to find the direction, and as the slope decreases make smaller movements. To do this you\n must find partial derivatives!\n \n Slope Iteration:\n b2 = b1 - Learning Rate * Partial Derivative (Slope)\n \n In this case find the partial derivatives of MSE!\n \nTaking A Step Back\n This method of gradient descent is quite accurate. However it uses all data points to calculate the line of best\n fit. In the case of 10 or so data points this isn't bad. But when scaled up to 1'000'000 if not billions of points\n this can take some time to complete. Additionally learning rates, as well as iterations also add another level of \n time complexity. \n \n Looking to solve this issue you can use Stochastic Gradient Descent (SGD), if not Mini-Batch SGD to solve such an\n issue. \n \nNext Steps, Look Towards implementations In TensorFlow, or other ML frameworks!\n\n\"\"\"\n\n# ----------------------------------------------------------------------------------------------------------------------\n\n\ndef gradient_descent(x, y):\n # Time Functions\n start_time = time.time()\n\n # Start With Some Value For m & b\n m_curr = 0\n b_curr = 0\n\n # Number Of Iterations\n iterations = 1000\n\n # Length Of Data Points\n n = len(x)\n\n # Define Learning Rate\n learning_rate = 0.05\n\n # Print Heading\n print(\"{:-^55}\".format(\"Gradient Descent\"))\n\n # Gather Data\n cost_values = []\n m_values = []\n b_values = []\n\n # Iteration\n for i in range(iterations):\n\n # Find The Y Predicted Given The m & b\n y_predicted = m_curr * x + b_curr\n\n # Find The Cost Of The Current Model, Using List Comprehension, Works Because Of Np.Array, Not Python List\n # Y & Y_Predicted Are Lists, Np.Array Allows For Matrix Subtraction\n cost = (1/n) * sum([val**2 for val in (y - y_predicted)])\n\n # Find The m & b derivative\n md = -(2/n) * sum(x * (y - y_predicted))\n bd = -(2/n) * sum(y - y_predicted)\n\n # Adjust m & b values. Learning Rate Is Subtracted Because Descent In Gradient Descent\n m_curr = m_curr - learning_rate * md\n b_curr = b_curr - learning_rate * bd\n\n # Print Values\n print(\"Iteration {0} | Cost: {1:.5f} | M: {2:.5f} | B: {3:.5f}\".format(i + 1, cost, m_curr, b_curr))\n\n cost_values.append(cost)\n m_values.append(m_curr)\n b_values.append(b_curr)\n\n # End Timer\n total_time = time.time() - start_time\n print(\"\\n{:-^55}\".format(\"Estimated Time\"))\n print(\"Seconds: {0:.2f}\".format(total_time))\n return m_curr, b_curr, cost_values, m_values, b_values\n\n# ----------------------------------------------------------------------------------------------------------------------\n\n\n# Populate X, Y with numbers generated with a set function, however gaussian noise has been added\n\n# Instantiate Number Of Points, M, and B\npoints = 1000\nm_actual = 2\nb_actual = 5\n\nx = 2 * (np.random.rand(1, points))\ny = (b_actual + (m_actual * x)) + (np.random.rand(1, points))\n\n# Turn To Simple Lists\nx_basic = [num for num in x[0]]\ny_basic = [num for num in y[0]]\n\nx = np.array(x_basic)\ny = np.array(y_basic)\n\n# Instantiate, And Collect Data\nm, b, cost_values, m_values, b_values = gradient_descent(x, y)\n\n# # Prediction: X Values To Map\n# x1 = 1\n# x2 = 5\n# x3 = 200\n#\n# # Find Values\n# y1 = (m * x1) + b\n# y2 = (m * x2) + b\n# y3 = (m * x3) + b\n#\n# # Print Additional Info For Understanding\n# print(\"\\n{:-^55}\".format(\"Predictions\"))\n# print(\"If: {0} = {1:.2f} | {2} = {3:.2f} | {4} = {5:.2f}\".format(x1, y1, x2, y2, x3, y3))\n#\n# print(\"\\n{:-^55}\".format(\"Plots\"))\n# print(\"\\n{:^55}\".format(\"*See Plots*\"))\n#\n#\n# # Plot Of Data\n# plt.xlabel('X Values')\n# plt.ylabel('Y Values')\n# plt.title('Plot Of Data')\n# plt.grid(True)\n# plt.scatter(x_basic, y_basic, marker=\"o\", s=1)\n# plt.show()\n\n# Plot Of Cost Values, As A Line\nplt.xlabel('Iteration')\nplt.ylabel('Iteration Cost')\nplt.title('Cost Values Over Iterations')\nplt.grid(True)\niteration = [x for x in range(len(cost_values))]\nplt.plot(iteration, cost_values)\nplt.show()\n#\n# # Plot Of M By B Values, As A Line\n# plt.xlabel('B Values')\n# plt.ylabel('M Values')\n# plt.title('Gradient Descent')\n# plt.grid(True)\n# plt.plot(b_values, m_values)\n# plt.show()\n#\n# # Misc\n# print(\"\\n{:-^50}\".format(\"\ud83d\udd25\ud83d\udd25\ud83d\udd25\ud83d\udd25\ud83d\udd25\"))\n"} {"blob_id": "e96e58cf709b6506013a45c21102878269b80787", "repo_name": "riscalab/wlcsim", "path": "/wlcsim/bd/init_beads.py", "length_bytes": 5913, "score": 3.671875, "int_score": 4, "content": "\"\"\"\nRoutines for setting the initial locations of the beads for BD.\n\nFunctions here are largely used in order to make sure that the initial\nconfiguration that is used to perform BD is valid.\n\n.. note::\n\n Writing a correct ``init_*`` function can be arbitrarily difficult due to\n compounding factors such as confinement, bead connectivity, inter-polymer\n interactions, and so forth. If your system is complicated enough, consider\n using an existing function here and simply adding your energies to the\n Monte-Carlo code in order to generate approximately equilibrium initial\n configurations using MC.\n\nThis file also contains routines to directly initialize some simple types of\nchains extremely near (or at) equilibrium to reduce the number of\ninitialization BD or MC steps required to equilibrate the polymer.\nAlternatively, some of these chains are as far as possible from equilibrium\n(such as `init_straight_x`) in order to ensure that e.g. the end-to-end\ndistance reaching its equilibrium distribution is representative of the time it\ntakes for the chain itself to reach equilibrium.\n\n\n.. note::\n\n If you know the analog of the \"Rouse\" time for your system (i.e. the\n time-scale of the largest mode), this is typically an easier and more\n principled way to determine how long to run initialization BD than doing a\n huge number of simulations and trying to measure how long it takes for\n something like the end-to-end distribution to equilibrate.\n\"\"\"\nimport numpy as np\nfrom numba import jit\n\n\ndef init_straight_x(N, L):\n \"\"\"Return straight line from 0 along positive x-axis.\"\"\"\n x0 = np.zeros((N, 3))\n x0[:, 0] = np.linspace(0, L, N)\n return x0\n\n\ndef init_circle(N, L):\n \"\"\"Return a circle with circumference L in the x-y plane.\"\"\"\n # want circumference L\n R = L/(2*np.pi)\n r = np.zeros((N, 3))\n r[:, 0] = R*np.cos(np.linspace(0, 2*np.pi, N))\n r[:, 1] = R*np.sin(np.linspace(0, 2*np.pi, N))\n u = np.zeros((N, 3))\n u[:, 0] = -np.sin(np.linspace(0, 2*np.pi, N))\n u[:, 1] = np.cos(np.linspace(0, 2*np.pi, N))\n return r, u\n\n\n@jit(nopython=True)\ndef init_linear_rouse_conf(N, bhat, rx, ry, rz):\n \"\"\"Ad-hoc method for Rouse polymers in elliptical confinement.\n\n Will not necessarily be exactly at equilibrium, but pretty close.\n\n Parameters\n ----------\n bhat : float\n b*np.sqrt(Lb), the std dev of the distance between beads\n rx, ry, rz : float\n Principle axes of confinement ellipse\n\n Returns\n -------\n (N, 3) array of float\n The initial locations of the beads.\n \"\"\"\n x0 = np.zeros((N, 3))\n # x0 = np.cumsum(x0, axis=0)\n for i in range(1, N):\n # 1/sqrt(3) since generating per-coordinate\n x0[i] = x0[i-1] + bhat/np.sqrt(3)*np.random.randn(3)\n while x0[i, 0]**2/rx**2 + x0[i, 1]**2/ry**2 + x0[i, 2]**2/rz**2 > 1:\n x0[i] = x0[i-1] + bhat/np.sqrt(3)*np.random.randn(3)\n return x0\n\n\n@jit(nopython=True)\ndef init_homolog_rouse_conf(N, N_tot, loop_list, bhat, rx, ry, rz):\n \"\"\"VERY ad-hoc, probably not near equilibrium, or even in confinement.\"\"\"\n # first initialize the first chain\n x0 = np.zeros((N_tot, 3))\n x0[:N, :] = init_linear_rouse_conf(N, bhat, rx, ry, rz)\n # now initialize the loops\n num_loops, _ = loop_list.shape\n for j in range(1, num_loops-1):\n k1l, k1r, k2l, k2r = loop_list[j]\n # need to initialize beads [k2l,..,k2r] so that they form a Brownian\n # bridge between the (already determined) positions of k1l and k1r\n # first, build a regular brownian walk starting at k1l\n num_beads = k1r - k1l - 1\n for i in range(num_beads):\n i1 = k2l + i - 1 if i > 0 else k1l\n i2 = k2l + i\n x0[i2] = x0[i1] + bhat/np.sqrt(3)*np.random.randn(3)\n while 1 < x0[i2, 0]**2/rx**2 + x0[i2, 1]**2/ry**2 \\\n + x0[i2, 2]**2/rz**2:\n x0[i2] = x0[i1] + bhat/np.sqrt(3)*np.random.randn(3)\n # then subtract off the correct amount from each step to make the\n # brownian bridge. This guy is no longer guaranteed to be in the\n # confinement....but will typically not be catastrophically far outside\n bridge = x0[k1r] - x0[k1l] # target end-to-end vector\n # center bridge temporarily about zero\n for jj in range(k2l, k2r+1):\n x0[jj] -= x0[k1l]\n # jit >:( x0[k2l:k2r+1] = x0[k2l:k2r+1] - x0[k1l][None,:]\n # now fix end-to-end vector\n for i in range(num_beads):\n # fraction of the way along the bridge\n f = (i + 1)/(num_beads + 1)\n x0[k2l+i] = x0[k2l+i]*(1 - f) + f*bridge\n # re-center bridge around x0[k1l]\n for jj in range(k2l, k2r+1):\n x0[jj] += x0[k1l]\n # x0[k2l:k2r+1] = x0[k2l:k2r+1] + x0[k1l][None,:]\n # finally, initialize the free ends\n if num_loops == 1:\n x0[N:, :] = init_linear_rouse_conf(N, bhat, rx, ry, rz)\n return x0\n # \"left\" free end must be built backwards from first connection point\n k1l, k1r, k2l, k2r = loop_list[0]\n num_beads = k1r - k1l - 1 # or k2r - k2l + 1\n for i in range(num_beads):\n i1 = k2r - i + 1 if i > 0 else k1r\n i2 = k2r - i\n x0[i2] = x0[i1] + bhat/np.sqrt(3)*np.random.randn(3)\n while x0[i2, 0]**2/rx**2 + x0[i2, 1]**2/ry**2 + x0[i2, 2]**2/rz**2 > 1:\n x0[i2] = x0[i1] + bhat/np.sqrt(3)*np.random.randn(3)\n # right free end can be built as normal with no bridge stuff\n k1l, k1r, k2l, k2r = loop_list[-1]\n num_beads = k1r - k1l - 1 # or k2r - k2l + 1\n for i in range(num_beads):\n i1 = k2l + i - 1 if i > 0 else k1l\n i2 = k2l + i\n x0[i2] = x0[i1] + bhat/np.sqrt(3)*np.random.randn(3)\n while x0[i2, 0]**2/rx**2 + x0[i2, 1]**2/ry**2 + x0[i2, 2]**2/rz**2 > 1:\n x0[i2] = x0[i1] + bhat/np.sqrt(3)*np.random.randn(3)\n return x0\n"} {"blob_id": "152f29a70dc8eacc17182b420ecdbf6733d8c02a", "repo_name": "djshuster/banzhaf-info-calculator", "path": "/banzhaf_info.py", "length_bytes": 3023, "score": 4.09375, "int_score": 4, "content": "# Created by David Shuster\n# Last updated 14 Dec., 2020\n\n# This program takes in data from electionData.csv\n# and outputs the \"Ratio of Banzhaf Index to Fraction of Vote\" for each party in results.csv.\n# The default quota is 61. To use a different quota,\n# enter the new quota as a whole number in the command line when running the program.\n# For example \"py banzhaf_info.py 90\" will set the quota to 90.\n# For more detailed information, check out README.txt.\n\nimport coalitions\nimport csv\nimport sys\n\ndef main():\n parties={}\n if (len(sys.argv)==2):\n quota = int(sys.argv[1])\n else:\n quota = 61\n\n # 1 argument: returns True if the seat count for the list of party-lists sums up to or past the quota.\n # 3 arguments: If removing=True and removed has a value, then removed holds the name of the removed party;\n # then return false if and only if the party-lists' seats cannot sum to 61 without the removed party.\n # In other words, if this latter use scenario returns false, then the removed party is a critical voter.\n def majority(name_list, removing=False, removed=\"\"):\n sum = 0\n for name in name_list:\n sum += int(parties[name][\"seats\"])\n if(removing and removed!=\"\"):\n sum-= int(parties[removed][\"seats\"])\n return (sum>=quota)\n\n # import information from electionData.csv\n with open('electionData.csv') as myFile:\n data = csv.reader(myFile, delimiter=',')\n for row in data:\n if (row[0]==\"\"):\n break\n if (row[0]==\"Name of list\"):\n continue\n party_info={}\n party_info[\"fraction_of_vote\"] = float(row[2])/100\n party_info[\"seats\"] = row[3]\n party_info[\"Bpower\"] = 0\n party_info[\"Bindex\"] = 0\n parties[row[0]] = party_info\n names = parties.keys()\n coalition_list = coalitions.list_of_lists(list(names))\n\n # establish the Banzhaf power of each coalition\n for coalition in coalition_list:\n if majority(coalition):\n for party in coalition:\n if(not majority(coalition, removing=True, removed=party)):\n parties[party][\"Bpower\"] +=1\n\n # find the total Banzhaf power\n total_Bpower = 0\n for name in names:\n total_Bpower+=parties[name][\"Bpower\"]\n\n # write the results into results.csv\n with open('results.csv', 'w', newline='') as csvfile:\n field1 = 'Knesset Elected List Names'\n field2 = 'Ratio of Banzhaf Index to Fraction of Vote'\n writer = csv.DictWriter(csvfile, fieldnames=[field1, field2])\n writer.writeheader()\n for name in names:\n parties[name][\"Bindex\"] = parties[name][\"Bpower\"] / total_Bpower\n ratio = round(parties[name][\"Bindex\"] / parties[name][\"fraction_of_vote\"], 2)\n writer.writerow({field1: name, field2: ratio})\n print(name, \"has a Banzhaf index/(fraction of vote) ratio of \", ratio)\n\nif __name__ == '__main__':\n main()"} {"blob_id": "a5647d6d04690adebac3f65032c47db1d205be34", "repo_name": "Crisescode/leetcode", "path": "/Python/Tree/222. counts_complete_tree_nodes.py", "length_bytes": 2583, "score": 4.0625, "int_score": 4, "content": "#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# https://leetcode-cn.com/problems/count-complete-tree-nodes/\n# Given the root of a complete binary tree, return the number of the nodes in the tree.\n#\n# According to Wikipedia, every level, except possibly the last, is completely filled in a complete\n# binary tree, and all nodes in the last level are as far left as possible. It can have between 1\n# and 2h nodes inclusive at the last level h.\n#\n# \u6765\u6e90\uff1a\u529b\u6263\uff08LeetCode\uff09\n# \u94fe\u63a5\uff1ahttps://leetcode-cn.com/problems/count-complete-tree-nodes\n# \u8457\u4f5c\u6743\u5f52\u9886\u6263\u7f51\u7edc\u6240\u6709\u3002\u5546\u4e1a\u8f6c\u8f7d\u8bf7\u8054\u7cfb\u5b98\u65b9\u6388\u6743\uff0c\u975e\u5546\u4e1a\u8f6c\u8f7d\u8bf7\u6ce8\u660e\u51fa\u5904\u3002\n\n\"\"\"\nExample:\n Input:\n 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7\n Input: root = [1, 2, 3, 4, 5, 6, 7]\n Output: 7\n\"\"\"\n\nfrom typing import List\n\n\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 countNodes(self, root: TreeNode) -> (int, List):\n result = 0\n # l_results = []\n\n if not root:\n return result\n\n from collections import deque\n queue = deque([root])\n while queue:\n # l_result = []\n length = len(queue)\n for _ in range(length):\n cur = queue.popleft()\n # l_result.append(cur.val)\n result += 1\n\n if cur.left:\n queue.append(cur.left)\n\n if cur.right:\n queue.append(cur.right)\n\n # l_results.append(l_result)\n\n return result\n\n\nclass Solution2:\n def countNodes(self, root: TreeNode) -> int:\n if not root:\n return 0\n\n left = root.left\n right = root.right\n\n left_height, right_height = 0, 0\n while left:\n left = left.left\n left_height += 1\n\n while right:\n right = right.right\n right_height += 1\n\n if left_height == right_height:\n return (2 << left_height) - 1\n\n left_h = self.countNodes(root.left)\n right_h = self.countNodes(root.right)\n return left_h + right_h + 1\n\n\nif __name__ == \"__main__\":\n root = TreeNode(1)\n root.left = TreeNode(2)\n root.right = TreeNode(3)\n root.left.left = TreeNode(4)\n root.left.right = TreeNode(5)\n root.right.left = TreeNode(6)\n # root.right.right = TreeNode(7)\n\n # print(Solution().countNodes(root))\n print(Solution2().countNodes(root))\n"} {"blob_id": "c7244352dc66be7208b802295fb0370ca5c420eb", "repo_name": "asherLZR/algorithms", "path": "/sorting/heap_sort.py", "length_bytes": 2030, "score": 3.8125, "int_score": 4, "content": "from abstract_data_types.referential_array import build_array\n\n\nclass Heap:\n\n def __init__(self):\n self.array = build_array(100)\n self.count = 0\n\n def __len__(self):\n return self.count\n\n def swap(self, i, j):\n self.array[i], self.array[j] = self.array[j], self.array[i]\n\n def largest_child(self, k):\n # if the last element in the heap is the left child, then there is no right\n # or if the the left child is greater than the right, return index for left\n if 2 * k == self.count or self.array[2*k][0] > self.array[2*k+1][0]:\n return 2*k\n else:\n return 2*k+1\n\n def rise(self, k):\n while k > 1 and self.array[k//2][0] < self.array[k][0]:\n self.swap(k, k//2)\n k //= 2\n\n def sink(self, k):\n # 2k and 2k+1\n while 2 * k <= self.count:\n child = self.largest_child(k)\n if self.array[k][0] >= self.array[child][0]:\n break\n self.swap(child, k)\n k = child\n\n def get_max(self):\n if len(self) == 0:\n raise ValueError(\"There is no max in an empty heap!\")\n item = self.array[1]\n self.swap(1, self.count)\n self.count -= 1\n self.sink(1)\n return item[1]\n\n def add(self, key, value):\n item = (key, value)\n if self.count + 1 < len(self.array):\n self.array[self.count+1] = item\n else:\n self._resize()\n self.array[self.count+1] = item\n self.count += 1\n self.rise(self.count)\n\n def _resize(self):\n new_array = build_array(2*len(self.array))\n for i in range(len(self.array)):\n new_array[i] = self.array[i]\n self.array = new_array\n\n\ndef heap_sort(a_list):\n my_heap = Heap()\n for elem in a_list:\n my_heap.add(elem, elem)\n for i in range(len(my_heap)-1, -1, -1):\n a_list[i] = my_heap.get_max()\n return a_list\n\n\ndef main():\n pass\n\n\nif __name__ == '__main__':\n main()\n"} {"blob_id": "0d7f0d2d3681b3934bfc9bb21b6173e5773d0c4f", "repo_name": "lkaihua/clay", "path": "/N-queen.py", "length_bytes": 1061, "score": 3.765625, "int_score": 4, "content": "'''\n# Read input from stdin and provide input before running code\n\nname = raw_input()\nprint 'Hi, %s.' % name\n'''\n\nN = 3\n\n# board = [ [0]*N ]*N\nboard = [ [0 for x in range(0, N)] for y in range(0, N)]\n\n\ndef solution(n):\n # all queens placed\n if n == 0:\n # print board\n return True\n for i in xrange(0, N):\n for j in xrange(0, N):\n # if it's not okay to put queen in current block\n if is_attacked(i, j, board):\n continue \n board[i][j] = 1\n # find any first solution\n if solution(n-1):\n return True\n\n # or find all solutions\n # solution(n-1) \n board[i][j] = 0\n return False\n \n\ndef is_attacked(r, c, board):\n # check row\n for i in xrange(0, N):\n for j in xrange(0, N):\n if i == r or j == c or j-i == c-r or j+i == c+r :\n if board[i][j] == 1:\n # print 'attacked', r,c \n return True\n return False\n \nprint solution(N)\nprint board"} {"blob_id": "b774c8ded079fe43192fae1a057c45c17f3eef35", "repo_name": "jabberwocky0139/recursion-drill", "path": "/rec06.py", "length_bytes": 1037, "score": 3.875, "int_score": 4, "content": "# -*- coding: utf-8 -*-\nfrom functools import reduce\n\n# (0, 0)\u304b\u3089(x, y)\u307e\u3067\u306e\u7d4c\u8def\u306e\u7dcf\u6570\u3092\u51fa\u529b\u3059\u308b\ndef maze(x, y):\n if x == 0 and y == 0:\n return 1\n elif x > 0 and y > 0:\n return maze(x-1, y) + maze(x, y-1)\n elif x > 0 and y == 0:\n return maze(x-1, y)\n elif y > 0 and x == 0:\n return maze(x, y-1)\n\ndef half_maze(x, y):\n if x == 0 and y == 0:\n return 1\n elif x == y:\n return maze(x, y-1)\n elif x > 0 and y > 0:\n return maze(x-1, y) + maze(x, y-1)\n elif x > 0 and y == 0:\n return maze(x-1, y)\n\n## print(half_maze(13, 13))\n\n# n\u500b\u306e\u30ce\u30fc\u30c9\u3092\u6301\u3064\u4e8c\u5206\u6728\u306e\u7dcf\u6570\ndef node(n):\n if n == 0:\n return 1\n else:\n return sum([node(i) * node(n-i-1) for i in range(0, n)])\n\n## print(node(13))\n\ndef coin(n, arr):\n if n == 0:\n return 1\n elif len(arr) == 0:\n return 0\n elif n < 0:\n return 0\n else:\n return coin(n - arr[0], arr) + coin(n, arr[1:])\n\nprint(coin(100, [1, 5, 10, 50, 100, 500]))\n"} {"blob_id": "74a0c3b73e56fc15e959f12080542dfef7c8df73", "repo_name": "alexwume/CV", "path": "/CV_hw0/hw0/code/alignChannels.py", "length_bytes": 2687, "score": 3.5625, "int_score": 4, "content": "import numpy as np\nfrom PIL import Image\ndef alignChannels(red, green, blue):\n \"\"\"Given 3 images corresponding to different channels of a color image,\n compute the best aligned result with minimum abberations\n\n Args:\n red, green, blue - each is a HxW matrix corresponding to an HxW image\n\n Returns:\n rgb_output - HxWx3 color image output, aligned as desired\"\"\"\n h=red.shape[0]\n w=red.shape[1]\n tmp=100000000000\n map_RG={}\n map_RB={}\n map_GB={}\n offset_max=30\n\n for i in range(-2*offset_max,2*offset_max+1): #for row\n for j in range(-2*offset_max,2*offset_max+1): #for column\n #Calculate SSD at each i,j\n if -offset_max<= i <=offset_max and -offset_max<=j<=offset_max:\n SSD_RG=ssd(red[max(i,0):min(h,h+i),max(j,0):min(w,w+j)],green[max(-i,0):min(h,h-i),max(-j,0):min(w,w-j)]) #red-green\n SSD_RB=ssd(red[max(i,0):min(h,h+i),max(j,0):min(w,w+j)],blue[max(-i,0):min(h,h-i),max(-j,0):min(w,w-j)]) #red-blue\n #store values\n map_RB[i,j] = SSD_RB\n map_RG[i,j] = SSD_RG\n SSD_GB = ssd(green[max(i,0):min(h,h+i), max(j, 0):min(w, w + j)], blue[max(-i, 0):min(h, h - i), max(-j, 0):min(w, w - j)]) # blue-green\n #store value and i,j in map\n map_GB[(i,j)]=SSD_GB\n #print(map_RG)\n for key1 in map_RG.keys():\n for key2 in map_RB.keys():\n #print(map_GB[-key1[0]+key2[0],-key1[1]+key2[1]])\n key3=(-key1[0]+key2[0],-key1[1]+key2[1])\n if map_RG[key1]+map_RB[key2]+map_GB[key3] str:\n \n def checker(paragraph,banned):\n for i in paragraph:\n if i not in banned:\n if i in dictionary:\n dictionary[i] += 1\n else:\n dictionary[i] = 1\n for i in (\"!?',;.\"):\n paragraph = paragraph.split(i)\n paragraph = \" \".join(paragraph)\n\n dictionary = {}\n \n paragraph = paragraph.split()\n \n\n for i in range(len(paragraph)):\n if paragraph[i].isalpha():\n paragraph[i] = paragraph[i].lower()\n else:\n paragraph[i] = paragraph[i][:-1].lower()\n\n banned = set(banned)\n\n checker(paragraph,banned)\n\n freq = sorted((value, key) for (key,value) in dictionary.items())\n\n return freq[-1][1]\n"} {"blob_id": "1271af5bfbd7b2f17f9f56ad65aac472d675f2a0", "repo_name": "lhf860/leetcode_python", "path": "/dynamic_programming_03/\u6590\u6ce2\u90a3\u5951\u6570\u5217.py", "length_bytes": 629, "score": 3.96875, "int_score": 4, "content": "# coding:utf-8\n\n\"\"\"\n\u6590\u6ce2\u90a3\u5951\u6570\u5217\u7684\u5b9e\u73b0\n\nfib(i)={1, i< 3; fib(i-1) + fib(i-2) i>=3;\n\n\u5b9e\u73b0\u65b9\u5f0f\u4e24\u79cd\uff1a\n1\uff09 \u9012\u5f52\u7b97\u6cd5\uff0c\u6309\u7167\u4e0a\u8ff0\u65b9\u5f0f\u5b9a\u4e49\u7684\u516c\u5f0f\u8fdb\u884c\u5b9e\u73b0\uff0c \u4f1a\u6709\u91cd\u53e0\u5b50\u95ee\u9898\uff0c\u91cd\u590d\u8ba1\u7b97\uff1b\u9012\u5f52\u95ee\u9898\uff1a\u81ea\u9876\u5411\u4e0b\n2\uff09 \u52a8\u6001\u89c4\u5212\uff0c\u81ea\u5e95\u5411\u4e0a\uff0c\u907f\u514d\u91cd\u590d\u8ba1\u7b97\uff0c\u9700\u8981\u989d\u5916\u7684\u7a7a\u95f4\u6765\u4fdd\u5b58\u4e2d\u95f4\u7ed3\u679c\n\n\n\n\"\"\"\n\n# \u9012\u5f52\u7b97\u6cd5\u6c42\u89e3\n\ndef fib(n):\n if n < 1:\n return 0\n\n if n < 3:\n return 1\n return fib(n-2) + fib(n-1)\n\n\n# \u52a8\u6001\u89c4\u5212\u6c42\u89e3\n\ndef fib(n):\n l= [0, 1, 1]\n for i in range(3, n+1):\n l.append(l[i-1] + l[i-2])\n return l[n]\n\n\n\n\n\n\n\n\n\n\n\n\n"} {"blob_id": "c46c142b043cbe458580236cd45f767a84513bc4", "repo_name": "zelunwu/ocean_analysis", "path": "/build/lib/oda/geos.py", "length_bytes": 2520, "score": 3.59375, "int_score": 4, "content": "#!/usr/bin/env python\n\nimport numpy as np\n\ndef earth_dist_2p(lat, lon, unit='m', r=6373.0):\n '''\n Calculate distance between two points.\n\n dist = earth_dist2p(lon, lat, unit='km', r = 6373.0)\n :param lon: array, longitude, shoule be [lon1,lon2]\n :param lat: array, latitude, shoule be [lat1,lat2]\n :param unit: str, units, default is 'km', can be 'km', 'm', or 'mile'\n :param r: earth radius, defalt is 6373km.\n :return: dist, distance, default unit is 'km'\n '''\n\n if len(lon) != len(lat):\n raise TypeError(\"Length of input variable 'lon' and 'lat' should be the same.\")\n\n lon = np.deg2rad(lon)\n lat = np.deg2rad(lat)\n\n lon1 = lon[0]\n lon2 = lon[1]\n lat1 = lat[0]\n lat2 = lat[1]\n dlon = lon2 - lon1\n dlat = lat2 - lat1\n\n a = np.sin(dlat / 2) ** 2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon / 2) ** 2\n # new rad before two points\n c = 2 * np.arctan2(np.sqrt(a), np.sqrt(1 - a))\n dist = r * np.abs(c)\n # Units\n if unit == 'm' or unit == 'meter':\n dist = dist * 1.0e3\n elif unit == 'mi' or unit == 'miles' or unit == 'mile':\n dist = dist / 0.621371\n\n return dist\n\n\ndef earth_dist_2d(lat=np.arange(-89.5, 90), lon=np.arange(0.5, 360), unit='m', r=6373.0, lon_0=None, lat_0=None):\n '''\n Calculate 2 dimensional distance x and y of longitude lon and latitude lat\n :param lon: array, default is np.arange(0.5,360). Can be meshgrid array.\n :param lat: array, default is np.arange(-89.5,90). Can be meshgrid array.\n :param unit: str, units, default is 'km', can be 'km', 'm', or 'mile'\n :param r: float, earth radius in kilometers.\n :param lon_0: float, oringinal longitude\n :param lat_0: float, oringinal latitude\n :return: x, y\n '''\n if np.ndim(lon) != np.ndim(lat):\n raise TypeError(\"Dimensions of input variable 'lon' and 'lat' should be the same.\")\n\n if lat_0 == None:\n lat_0 = lat[0]\n if lon_0 == None:\n lon_0 = lon[0]\n\n x = np.reshape(np.array([(lon_p-lon_0)/360.0*2*np.pi*r for lon_p in lon]),(1,len(lon)))\n weight = np.abs(np.reshape(np.cos(np.deg2rad(lat)),(len(lat),1)))\n x = np.dot(weight,x)\n if unit == 'm':\n x = x*10.0e3\n y = np.repeat(np.reshape(np.array([earth_dist_2p([lat_0,lat_p],[0,0],unit=unit,r=r) for lat_p in lat]),(len(lat),1)),len(lon),axis=1)\n return y, x\n\n\n\ndef area(lat,lon,unit='m'):\n\n y,x = earth_dist_2d(lat,lon,unit=unit)\n _, dx = np.gradient(x)\n dy,_ = np.gradient(y)\n dA = dx*dy\n return dA\n\n\n\n"} {"blob_id": "b1354406425e1fdb7550e63fdf3e3b2e82ca4e10", "repo_name": "kironezhengyu/leetcode", "path": "/linkedList/partitionLLAroundX.py", "length_bytes": 1038, "score": 3.6875, "int_score": 4, "content": "'''\npartition a LL around x that all nodes \ngreater than x after smaller than x\n'''\n\nclass ListNode():\n val = 0\n next = None\n def __init__(self,x=0):\n self.val = x\n self.next = None\n def __repr__(self):\n if self.next:\n return '%d--->%s' % (self.val, str(self.next))\n else:\n return '%d' % (self.val)\n \n\n\ndef addAll(head,arr):\n refrenceHead = head\n for value in arr:\n temp = ListNode(value)\n head.next = temp\n head = temp\n return refrenceHead\n\nhead = ListNode(1)\naddAll(head,[2,1,3,4,1])\n\ndef partition(head,x):\n pivot = ListNode(x)\n root = ListNode(-1)\n r_l =root\n p_l = pivot\n\n current = head\n while current :\n next = current.next\n if current.val < x:\n r_l.next = current\n r_l = current\n else:\n p_l.next = current\n p_l = current\n p_l.next = None\n current = next\n r_l.next = pivot.next\n\n return root.next\nprint partition(head,3)\n\n\n"} {"blob_id": "f0ef4cb34b1fcf8b01f7bc816348bd8f4f9201ab", "repo_name": "sungguenja/studying", "path": "/sort/redix_sort.py", "length_bytes": 916, "score": 3.625, "int_score": 4, "content": "def countingsort(arr,digit):\n n = len(arr)\n\n # \ubc30\uc5f4\uc758 \ud06c\uae30\uc5d0 \ub9de\uac8c result \uc0dd\uc131 \uc790\ub9bf\uc218\uc5d0 \uc774\uc6a9\ud558\ub294 10\uae38\uc774\uc9dc\ub9ac \ubc30\uc5f4\n result = [0]*n\n count = [0]*10\n\n for i in range(n):\n count[(int(arr[i]/digit))%10] += 1\n \n # count \ubc30\uc5f4\uc744 \uc218\uc815\ud574 digit\uc73c\ub85c \uc7a1\uc740 \ud3ec\uc9c0\uc158\uc744 \uc124\uc815\n for i in range(1,10):\n count[i] += count[i-1]\n print(i,count[i])\n \n i = n-1\n print(count)\n print(result)\n while i>=0:\n index = int(arr[i]/digit)\n result[count[index%10]-1] = arr[i]\n count[index%10] -= 1\n i -= 1\n print(count)\n print(result)\n \n for i in range(n):\n arr[i] = result[i]\n print(arr)\n\ndef radixsort(arr):\n maximum = max(arr)\n digit = 1\n while int(maximum/digit) > 0:\n countingsort(arr,digit)\n digit *= 10\n\narr = [180,7513,54,1,9754,123,446,10]\nradixsort(arr)\nprint(arr)"} {"blob_id": "0e753674a2c8efd00bcbebe532a280364f14aaed", "repo_name": "Web-Dev-Collaborative/Lambda-Final-Backup", "path": "/2-resources/_Past-Projects/Whiteboard-Pairing-master/BSTFromArray/model_solution.py", "length_bytes": 2020, "score": 3.875, "int_score": 4, "content": "import math\n\ndef create_minimal_BST(sorted_array):\n return create_minimal_BST_helper(sorted_array, 0, len(sorted_array) - 1)\n\ndef create_minimal_BST_helper(sorted_array, left, right):\n if right < left:\n return None\n\n mid = math.floor((left + right) / 2)\n node = BinaryTreeNode(sorted_array[mid])\n\n node.left = create_minimal_BST_helper(sorted_array, left, mid - 1)\n node.right = create_minimal_BST_helper(sorted_array, mid + 1, right)\n\n return node\n\nclass BinaryTreeNode:\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\n# Helper function to validate that the created tree is a valid BST\ndef is_BST(root):\n node_and_bounds_stack = []\n node_and_bounds_stack.append({\"node\": root, \"lower_bound\": -math.inf, \"upper_bound\": math.inf})\n\n while node_and_bounds_stack != []:\n node_and_bounds = node_and_bounds_stack.pop()\n node = node_and_bounds[\"node\"]\n\n lower_bound = node_and_bounds[\"lower_bound\"]\n upper_bound = node_and_bounds[\"upper_bound\"]\n\n if node.value <= lower_bound or node.value >= upper_bound:\n return False\n\n if node.left != None:\n node_and_bounds_stack.append({\"node\": node.left, \"lower_bound\": lower_bound, \"upper_bound\": node.value})\n\n if node.right != None:\n node_and_bounds_stack.append({\"node\": node.right, \"lower_bound\": node.value, \"upper_bound\": upper_bound})\n\n return True\n\n# Helper function to check the max height of a BST\ndef max_depth(node):\n if node == None: return 0\n\n return 1 + max(max_depth(node.left), max_depth(node.right))\n\n# Some tests\nsorted_array = [1, 2, 3, 4, 5, 6, 7]\nbst = create_minimal_BST(sorted_array)\n\nprint(is_BST(bst)) # should print true\nprint(max_depth(bst)) # should print 3\n\nsorted_array = [4, 10, 11, 18, 42, 43, 47, 49, 55, 67, 79, 89, 90, 95, 98, 100]\nbst = create_minimal_BST(sorted_array)\n\nprint(is_BST(bst)) # should print true\nprint(max_depth(bst)) # should print 5\n"} {"blob_id": "37277014eec9d486fadf58e9c5dc4864cba31ae7", "repo_name": "rloredo/projectEulerPy2.7", "path": "/problem9.py", "length_bytes": 895, "score": 4.0625, "int_score": 4, "content": "\n#A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,\n# a2 + b2 = c2\n# For example, 32 + 42 = 9 + 16 = 25 = 52.\n# There exists exactly one Pythagorean triplet for which a + b + c = 1000.\n# Find the product abc.\n\ndef isPythTripl(a,b,c):\n return a**2 + b**2 == c**2 and (a < b and b < c)\n\n#Encontrar triplete que sume n\ndef findPyth(n):\n a = 1\n b = 1\n # Iterar a y b\n while a < n:\n while b < n - a:\n # Encontrar c como la resta\n c = n - a - b\n # Si c es < b no cumple condicion y no vale la pena chequear\n if c < b:\n break\n #Chequear si es triplete\n if isPythTripl(a, b, c):\n return str(a) + ' + ' + str(b) + ' + ' + str(c) + ' = ' + str(a+b+c) + ' producto: ' + str(a*b*c)\n b = b + 1\n a = a + 1\n b = a\n\n\nprint findPyth(1000)\n"} {"blob_id": "55df39183ab76df931b17a96f3f9325252c5b677", "repo_name": "AkhileshChaikam/LeetCode", "path": "/WordBreak2.py", "length_bytes": 1317, "score": 3.625, "int_score": 4, "content": "#Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.\n\n#Return all such possible sentences.\n\n#For example, given\n#s = \"catsanddog\",\n#dict = [\"cat\", \"cats\", \"and\", \"sand\", \"dog\"].\n\n#A solution is [\"cats and dog\", \"cat sand dog\"].\n\nclass Solution:\n # @param s, a string\n # @param dict, a set of string\n # @return a boolean\n def wordBreak(self, s, dict):\n mysol = []\n list1 = []\n dict1 = {}\n for i in range(0,len(s),1):\n list2 = [False]*len(s)\n list1.append(list2)\n self.myFun(s,dict,len(s),list1,dict1)\n self.dfs(list1,dict,s,mysol,0,\"\")\n print mysol\n\n def myFun(self, s, dict,n,list1,dict1):\n for i in range(0,n+1,1):\n for j in range(i+1,n+1,1):\n if(s[i:j] in dict):\n list1[i][j-1]=True\n\n def dfs(self,list1,dict,s,mysol,index,appendString):\n if(index == len(s)):\n mysol.append(appendString.strip())\n return\n for i in range(index,len(list1[0]),1):\n if(list1[index][i] is True):\n self.dfs(list1,dict,s,mysol,i+1,appendString+ \" \"+s[index:i+1])\n\n\n\nstring = \"leetcode\"\ndict = {\"leet\",\"code\"}\nSoln = Solution()\nSoln.wordBreak(string,dict)"} {"blob_id": "b3f57f9701bf5aa0678649d789c940a23846a089", "repo_name": "Eroica-cpp/LeetCode", "path": "/006-ZigZag-Conversion/solution01.py", "length_bytes": 1370, "score": 4.1875, "int_score": 4, "content": "#!/usr/bin/python\n# ==============================================================================\n# Author: Tao Li (taoli@ucsd.edu)\n# Date: May 1, 2015\n# Question: 006-ZigZag-Conversion\n# Link: https://leetcode.com/problems/zigzag-conversion/\n# ==============================================================================\n# The string \"PAYPALISHIRING\" is written in a zigzag pattern on a given number \n# of rows like this: (you may want to display this pattern in a fixed font for\n# better legibility)\n# \n# P A H N\n# A P L S I I G\n# Y I R\n# \n# And then read line by line: \"PAHNAPLSIIGYIR\"\n# \n# Write the code that will take a string and make this conversion given a number of rows:\n# \n# string convert(string text, int nRows);\n# \n# convert(\"PAYPALISHIRING\", 3) should return \"PAHNAPLSIIGYIR\".\n# ==============================================================================\n\nclass Solution:\n # @param {string} s\n # @param {integer} numRows\n # @return {string}\n def convert(self, s, numRows):\n\t\tif numRows == 1 or len(s) <= numRows: \n\t\t\treturn s\n\t\tdiv = 2 * numRows - 2\n\t\tdic = {}\n\t\tfor i in range(numRows):\n\t\t\tdic[i] = \"\"\n\t\tfor j in range(len(s)):\n\t\t\tmod = j % div\n\t\t\tif mod <= (numRows-1):\n\t\t\t\tdic[mod] += s[j]\n\t\t\telse:\n\t\t\t\tdic[numRows-1-(mod-(numRows-1))] += s[j]\n\t\tnewStr = \"\"\n\t\tfor k in range(numRows):\n\t\t\tnewStr += dic[k]\n\t\treturn newStr"} {"blob_id": "18848ddd80eaa6ba4c0822579c256969a447da91", "repo_name": "clhchtcjj/Algorithm", "path": "/backtrack/leetcode 93 Restore IP Addresses.py", "length_bytes": 1203, "score": 3.546875, "int_score": 4, "content": "__author__ = 'CLH'\n\n'''\n Given a string containing only digits, restore it by returning all possible valid IP address combinations.\n'''\n\n\nclass Solution:\n def __init__(self):\n self.total_ans = []\n self.ans = []\n\n def is_legal(self, s):\n # when length bigger than 1, can not begin with 0\n if (len(s)>1 and s[0]=='0'):\n return False\n # must in [0-255]\n elif -1 < int(s) < 256:\n return True\n return False\n\n def backtrack(self,s,k):\n if s == \"\" and k == 5:\n self.total_ans.append('.'.join(self.ans))\n # pruning\n elif k == 5 or len(s) < (5-k) or len(s)/3 > (5-k):\n return\n else:\n # enumeration\n for i in range(1,min(4,len(s)+1)):\n if self.is_legal(s[0:i]):\n self.ans.append(s[0:i])\n self.backtrack(s[i:], k+1)\n self.ans.pop()\n\n def restoreIpAddresses(self, s):\n \"\"\"\n :type s: str\n :rtype: List[str]\n \"\"\"\n self.backtrack(s,1)\n return self.total_ans\n\nif __name__ == \"__main__\":\n S = Solution()\n print(S.restoreIpAddresses(\"010010\"))"} {"blob_id": "ea31e1d141a2b2550d38993abadfdffe23bce41e", "repo_name": "kyeokabe/coding", "path": "/matrixmul.py", "length_bytes": 818, "score": 3.765625, "int_score": 4, "content": "#A: mxn (2x4) note:m=len(A), n=len(A[0])\n#B: nxp (4x3) note:p=len(B[0])\n#C: mxp (2x3)\n\n###Answer Function###\ndef matmul(A,B):\n C=[]\n D=[]\n for m in range(0,len(A)):\n for p in range(0,len(B[0])):\n #defined index here because using C[m][p] doesn't work like numpy\n #(cannot write into individual indices correctly this way)\n index=0\n for n in range(0,len(A[0])):\n index+=A[m][n]*B[n][p]\n C.append(index)\n #reshape \"C\" into 2D matrix \"D\"\n for x in range(0,len(A)):\n D.append(C[x*len(B[0]):(x+1)*len(B[0])])\n return D\n\n\"\"\"\n###test section###\nA=[[4, 2, 1,6],[6, 8, 3,0]]\nB=[[3 ,2, 5],[0,1, 2],[2,2, 1],[0,1,3]]\n\nprint matmul(A,B)\n\n#test with numpy\nimport numpy as np\nQ=np.array([[4, 2, 1,6],[6, 8, 3,0]])\nR=np.array([[3 ,2, 5],[0,1, 2],[2,2, 1],[0,1,3]])\n\nprint np.dot(Q,R)\n\n\"\"\"\n"} {"blob_id": "f6c19d0d9881e607b01e9814ab9e4d419e96ac4a", "repo_name": "Zhenye-Na/leetcode", "path": "/python/277.find-the-celebrity.py", "length_bytes": 2101, "score": 4.1875, "int_score": 4, "content": "# 227. Find the Celebrity\n#\n# Description\n#\n# Suppose you are at a party with `n` people (labeled from `0` to `n - 1`) and among them,\n# there may exist one celebrity. The definition of a celebrity is that all the other\n# `n - 1` people know him/her but he/she does not know any of them.\n#\n# Now you want to find out who the celebrity is or verify that there is not one.\n# The only thing you are allowed to do is to ask questions like: \"Hi, A. Do you know B?\"\n# to get information of whether A knows B. You need to find out the celebrity\n# (or verify there is not one) by asking as few questions as possible (in the asymptotic sense).\n#\n# You are given a helper function `bool knows(a, b)` which tells you whether `A knows B`.\n#\n# Implement a function `int findCelebrity(n)`, your function should minimize the number of calls to knows.\n#\n# Example\n#\n# Example1\n#\n# Input:\n# 2 // next n * (n - 1) lines \n# 0 knows 1\n# 1 does not know 0\n# Output: 1\n# Explanation:\n# Everyone knows 1,and 1 knows no one.\n#\n# Example2\n#\n# Input:\n# 3 // next n * (n - 1) lines \n# 0 does not know 1\n# 0 does not know 2\n# 1 knows 0\n# 1 does not know 2\n# 2 knows 0\n# 2 knows 1\n# Output: 0\n# Explanation:\n# Everyone knows 0,and 0 knows no one.\n# 0 does not know 1,and 1 knows 0.\n# 2 knows everyone,but 1 does not know 2.\n\n\n\"\"\"\nThe knows API is already defined for you.\n@param a, person a\n@param b, person b\n@return a boolean, whether a knows b\nyou can call Celebrity.knows(a, b)\n\"\"\"\n\n\nclass Solution:\n # @param {int} n a party with n people\n # @return {int} the celebrity's label or -1\n def findCelebrity(self, n):\n # Write your code here\n candidate = 0\n for i in range(1, n):\n if Celebrity.knows(candidate, i):\n # celebrity should not know anyone\n candidate = i\n\n for i in range(n):\n if i != candidate and (Celebrity.knows(candidate, i) or not Celebrity.knows(i, candidate)):\n # not self, candidate knows somebody or someone does not know the candidate\n return -1\n\n return candidate\n\n# @lc code=end\n\n"} {"blob_id": "51472d82e2326dd7bf0f4c691fae6cd29c9ee0d9", "repo_name": "worldwidekatie/Sprint-Challenge--Algorithms", "path": "/recursive_count_th/count_th.py", "length_bytes": 1467, "score": 4.25, "int_score": 4, "content": "'''\nYour function should take in a single parameter (a string `word`)\nYour function should return a count of how many occurences of ***\"th\"*** occur within `word`. Case matters.\nYour function must utilize recursion. It cannot contain any loops.\n'''\n\n# * Your function should take in a signle parameter \n# (a string `word`)\n# * Your function should return a count of \n# how many occurences of ***\"th\"*** occur within `word`. \n# Case matters.\n# * Your function must utilize recursion. \n# * It cannot contain any loops.\n\n# Run `python test_count_th.py` to run the tests for your `count_th()` function to ensure that your implementation is correct.\n\n# Understand - \n# It takes a string, which is indexed like a list\n# It looks for occurances of 'th' case sensitive\n# It returns an integer of the number of occurances.\n# It has to use recursion, not loops\n\n# Plan -\n# Base case - return zero if there are no occurances\n# Make a variable to return whose default is zero\n# Can't use loops but can index into the string and use\n# an if statement to add to the variable and add to\n# the numbers used to index. this is what I can recurse. \n\n\ndef count_th(word, sm=0, lg=2, total=0):\n\n if len(word) == 0:\n return total\n\n elif lg > len(word):\n return total\n \n else:\n if word[sm:lg] == 'th':\n total += 1\n sm += 1\n lg += 1\n return count_th(word, sm, lg, total)\n\n\nprint(len(\"abcthxyz\"))\nprint(count_th(\"abcthxyz\"))"} {"blob_id": "5e7423d2a7f34b336dcc22a3a116cd35c77995a0", "repo_name": "nathanielastudillo/ANOVA", "path": "/ANOVA.py", "length_bytes": 1032, "score": 3.90625, "int_score": 4, "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 11 13:50:03 2019\n\n@author: nathanielastudillo\n\"\"\"\n\n'''\nAn ANOVA script for calculating the F value of a few samples of size n\n'''\nimport numpy as np\n\ndef ANOVA(groups): #pass in a list of lists where each sublist is a group\n #data for groups\n groups = groups\n groupMeans = []\n n = len(groups[0])\n N = 0\n SSB = 0 #sum of squares between\n SSE = 0 #sum of squares error\n k=len(groups)\n #calculate N\n for group in groups:\n N += len(group)\n #compute group means\n for group in groups:\n groupMeans.append(np.mean(group))\n #compute total mean\n totalMean = np.mean(groupMeans)\n # calculate SSB\n for mean in groupMeans:\n SSB += n*((mean - totalMean)**2)\n #calculate SSE\n for group in groups:\n mean = np.mean(group)\n for item in group:\n SSE += (item - mean)**2\n #Calculate F Value \n df1 = k-1\n df2 = N-k\n F = (SSB/df1)/(SSE/df2)\n return(F)\n\n\n \n "} {"blob_id": "dae07d97f8d009aeed44530c4587441e1f304ce8", "repo_name": "kovalevcon/practice-code", "path": "/Between Two Sets/between-two-sets.py", "length_bytes": 591, "score": 3.703125, "int_score": 4, "content": "\n\ndef getTotalX(a, b):\n lcm = calc_for_array(a, 'lcm')\n gcd = calc_for_array(b, 'gcd')\n\n count = 0\n multiple_lcm = lcm\n while multiple_lcm <= gcd:\n if gcd % multiple_lcm == 0:\n count += 1\n multiple_lcm += lcm\n\n return count\n\n\ndef gcd(a, b):\n if b == 0:\n return a\n return int(gcd(b, a % b))\n\n\ndef lcm(a, b):\n return int(a * (b / gcd(a, b)))\n\n\ndef calc_for_array(arr, name):\n result = arr[0]\n for i in range(len(arr)):\n result = globals()[name](result, arr[i])\n\n return result\n\n\nprint(getTotalX([2, 4], [16, 32, 96]))\n"} {"blob_id": "61068b7807ab10ed3bf07b28b32ed112a9ff7223", "repo_name": "Brunokrk/ANN", "path": "/simpson.py", "length_bytes": 813, "score": 3.5, "int_score": 4, "content": "import math\n\n\ndef simps(f, a, b, n):\n if( n % 2) != 0 or n < 1:\n raise ValueError(\"n deve ser par e maior que 1\")\n h = (b-a) / n\n soma_odd, soma_even = 0, 0\n for k in range(1, n, 2):\n soma_odd += f(a+k *h)\n for k in range(2, n, 2):\n soma_even +=f(a+k*h)\n return (h / 3) * (f(a) + 4 * soma_odd + 2 *soma_even +f(b))\n\n\na, b = 0,1\nn = 8\nh = (b-a)/n\nparticao = [a + k * h for k in range (n+1)]\nparticao_odd = [a + k * h for k in range (1, n, 2)]\nparticao_even = [a + k * h for k in range (2, n, 2)]\n\nprint(particao)\nprint(particao_odd)\nprint(particao_even)\n\ndef f(x):\n return math.exp(-x**2)\n\na,b = -0.522, 1.121\nn=1_096# n \u00e9 o n\u00famero de subintervalos\ni1 = simps(f, a, b, n)\nprint(i1)\n\n\ndef g(x):\n return math.cos(x**2)\n\na,b = -0.522, 1.121\nn = 8\n#i2 = simps(g, a, b, n)"} {"blob_id": "d1f0b7087421015c3a13d88a341375994385612e", "repo_name": "Kallehz/Python", "path": "/Pr\u00f3f1/NumbersGame.py", "length_bytes": 2926, "score": 3.859375, "int_score": 4, "content": "# Hawk and his little brother, Stone, are playing a little game with\n# the following rules. Initially 8 random integers, from 1 to 100\n# (inclusive), are laid on the table for both players to see. The\n# players then have 2 minutes to construct a sequence of numbers, from\n# the given 8 numbers, with the following conditions. To the right\n# of each even number must be either be an odd number, or the same even\n# number. To the right of each odd number must be either a larger even\n# number or a strictly smaller odd number. The player who constructs the\n# longer sequence wins. Just before the two minutes are up, Stone\n# notices that he can construct a legal sequence using all 8 numbers.\n# However, in all the excitement, he knocks all the numbers off the\n# table, and cannot remember how to construct the sequence. Hawk is very\n# sceptical of his brother, so he asks you to write a program that\n# determines whether his brother is telling the truth or not.\n# Write a function numbers_game that takes a list of 8 integers (in the range\n# from 1 to 100) as input. The function returns True if it is possible\n# to construct a legal sequence from the 8 integers; False otherwise.\n\n\nfrom itertools import permutations\ndef numbers_game(lis):\n for perm in permutations(lis):\n valid = True\n for i in range(0, len(lis)-1):\n #To the right of each even number must be either be an odd number, or the same evennumber.\n if perm[i] % 2 == 0:\n if not(perm[i+1] % 2 != 0 or perm[i] == perm[i+1]):\n valid = False\n break\n #To the right of each odd number must be either a larger even number or a strictly smaller odd number.\n if perm[i] % 2 != 0:\n if not((perm[i+1] > perm[i] and perm[i+1] % 2 == 0) or (perm[i+1] < perm[i] and perm[i+1] % 2 != 0)):\n valid = False\n break\n\n if valid:\n return True\n return valid\n\n\n##def numbers_game(lis):\n## for perm in permutations(lis):\n## if isValid(perm):\n## return True\n## return False\n##\n##def isValid(perm):\n## for i in range(0, len(perm)-1):\n## # To the right of each even number must be either be an odd number, or the same even number.\n## if perm[i] % 2 == 0:\n## if (perm[i+1] % 2 != 0 or perm[i] == perm[i+1]):\n## continue\n## else: \n## return False\n## # To the right of each odd number must be either a larger even number or a strictly smaller odd number.\n## if perm[i] % 2 != 0:\n## if (perm[i+1] > perm[i] and perm[i+1] % 2 == 0) or (perm[i+1] < perm[i] and perm[i+1] % 2 != 0):\n## continue\n## else:\n## return False\n## \n## return True\n \nprint(numbers_game([8,3,29,12,7,1,20,39]))\n#True\nprint(numbers_game([3,2,4,6,3,3,15,3]))\n#False\n"} {"blob_id": "81cac5f414082f29c4af2510f06ffab5e3994abb", "repo_name": "wxyBUPT/leetCode.py", "path": "/norecursion/Solution_173.py", "length_bytes": 1665, "score": 4.09375, "int_score": 4, "content": "#coding=utf-8\n__author__ = 'xiyuanbupt'\n# e-mail : xywbupt@gmail.com\n\n'''\n173. Binary Search Tree Iterator Add to List QuestionEditorial Solution My Submissions\nTotal Accepted: 72214\nTotal Submissions: 186544\nDifficulty: Medium\nContributors: Admin\nImplement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.\n\nCalling next() will return the next smallest number in the BST.\n\nNote: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.\n\n'''\n\n# 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\n\n# 77.41%\nclass BSTIterator(object):\n\n def __init__(self, root):\n \"\"\"\n :type root: TreeNode\n \"\"\"\n self.node = root\n self.stack = []\n\n def hasNext(self):\n \"\"\"\n :rtype: bool\n \"\"\"\n return self.node or self.stack\n\n def next(self):\n \"\"\"\n :rtype: int\n \"\"\"\n node = self.node\n stack = self.stack\n\n while node:\n stack.append(node)\n node = node.left\n node = stack.pop()\n val = node.val\n self.node = node.right\n return val\n\ndef inorder(root):\n stack = []\n node = root\n res = []\n while node or stack:\n while node:\n stack.append(node)\n node = node.left\n node = stack.pop()\n res.append(node.val)\n node = node.right\n\n\n\n\n\n# Your BSTIterator will be called like this:\n# i, v = BSTIterator(root), []\n# while i.hasNext(): v.append(i.next())"} {"blob_id": "b14f56d290b900e27d1871bc959ee8a2f27d5c0f", "repo_name": "JIANGWQ2017/DataStructure", "path": "/graph.py", "length_bytes": 3544, "score": 3.703125, "int_score": 4, "content": "import sys\n\nclass graph:\n\tdef __init__(self,nodeNum,adjacentMatrix):\n\t\tself.nodeNum = nodeNum\n\t\tself.adjacentMatrix = adjacentMatrix\n\t\t\n\n\tdef traverse(self,algorithm):\n\t\t# \u7531\u4e8e\u6709\u4e9b\u70b9\u662f\u5b64\u7acb\u70b9\uff0c \u6240\u4ee5\u9700\u8981\u5bf9\u6bcf\u4e2a\u8282\u70b9\u8fdb\u884c_dfs\uff0c \u7528visited \u6765\u907f\u514d\u91cd\u590d\u8bbf\u95ee\n\t\tvisited = [0 for i in range(self.nodeNum)]\n\t\t\n\t\tif algorithm.lower() == 'bfs':\n\t\t\torder = []\n\t\t\tfor i in range(self.nodeNum):\n\t\t\t\tif visited[i] == 0:\n\t\t\t\t\t\n\t\t\t\t\to = self._bfs(i,visited)\n\t\t\t\t\tif o:\n\t\t\t\t\t\torder.extend(o)\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn \n\t\t\tprint(order)\n\t\t\t\n\t\tif algorithm.lower() == 'dfs':\n\t\t\torder = []\n\t\t\tfor i in range(self.nodeNum):\n\t\t\t\tif visited[i] == 0:\n\t\t\t\t\torder.extend(self._dfs(i,visited))\n\t\t\t\n\t\t\tprint(order)\n\t\n\tdef checkLoop(self,algorithm):\n\t\tif algorithm.lower() == 'kahn':\n\t\t\tnodes = [1 for i in range(self.nodeNum)]\n\t\t\tgreeds = [sum(self.adjacentMatrix[i]) for i in range(self.nodeNum)]\n\t\t\tprint(self._kahn_uDAG(nodes,greeds))\n\t\t\t\n\t\t\t\n\t\tif algorithm.lower() == 'bfs':\n\t\t\tfor i in range(self.nodeNum):\n\t\t\t\tif visited[i] == 0:\n\t\t\t\t\t\n\t\t\t\t\to = self._bfs(i,visited)\n\t\t\t\t\tif not o:\n\t\t\t\t\t\treturn \n\t\t\tprint('No Loop!')\n\t\n\tdef _bfs(self,node,visited):\n\t\t\n\t\t# \u904d\u5386\u8fc7\u7684\u8282\u70b9\u6309\u987a\u5e8f\u653e\u5728order list\u4e2d\n\t\torder = []\n\t\t# \u5165\u8fc7\u6808\u7684\u8282\u70b9\n\t\tinqueue = [0 for i in range(self.nodeNum)]\n\t\t# \u5f85\u8bbf\u95ee\u7684\u8282\u70b9\n\t\tstack = [(node,node)]\n\t\tinqueue[node] = 1\n\t\t\n\t\twhile stack:\n\t\t\tcur,father = stack.pop(0)\n\t\t\torder.append(cur)\n\t\t\tvisited[cur] = 1\n\t\t\tfor i in range(len(self.adjacentMatrix[cur])):\n\t\t\t\tif self.adjacentMatrix[cur][i] == 1:\n\t\t\t\t\tif inqueue[i] == 0:\n\t\t\t\t\t\tstack.append((i,cur))\n\t\t\t\t\t\tinqueue[i]=1\n\t\t\t\t\telif i != father:\n\t\t\t\t\t\tprint('Loop existed in graph!')\n\t\t\t\t\t\treturn None\n\t\treturn order\n\n\t\n\tdef _dfs(self, node, visited):\n\t\t# \u5df2\u7ecf\u5165\u8fc7\u6808\u7684\u8282\u70b9\uff0c\u800c\u4e0d\u662f\u5df2\u7ecf\u8bbf\u95ee\u8fc7\u7684\u8282\u70b9\n\t\tinqueue = [0 for i in range(self.nodeNum)]\n\t\t# \u5f85\u8bbf\u95ee\u7684\u8282\u70b9\n\t\tstack = [node]\n\t\t#\u4fdd\u5b58dfs\u904d\u5386\u987a\u5e8f\t\t\n\t\torder = []\n\t\t\n\t\tinqueue[node] = 1\n\t\twhile stack:\n\t\t\tcur = stack.pop()\n\t\t\tvisited[cur] = 1\n\t\t\torder.append(cur)\n\t\t\tfor i in range(len(self.adjacentMatrix[cur])):\n\t\t\t\tif self.adjacentMatrix[cur][i]==1 and inqueue[i] == 0:\n\t\t\t\t\tstack.append(i)\n\t\t\t\t\tinqueue[i] = 1\n\t\treturn order\n\n\n\n\tdef _kahn_uDAG(self, nodes, greeds):\n\t\tcount = 0 \n\t\tfor i in range(len(greeds)):\n\t\t\tif greeds[i]<=1 and nodes[i] == 1:\n\t\t\t\tcount += 1\n\t\t\t\tnodes[i] = 0\n\t\t\t\tfor j in range(len(self.adjacentMatrix[i])):\n\t\t\t\t\tif self.adjacentMatrix[i][j] == 1:\n\t\t\t\t\t\tgreeds[j] -= 1\n\t\tif count:\n\t\t\treturn self._kahn_DAG(nodes,greeds)\n\t\t\n\t\treturn 1 in nodes\n\t\n\t \n\n\nclass edgeParser:\n\t\n\tdef __init__(self):\n\t\tself.edges = []\n\t\t\n\t\t\n\tdef parsing(self,line):\n\t\tline = line.strip().split(' ')\n\t\tline = [s for s in line if s]\n\t\tif len(line)==2:\n\t\t\tself.edges.append(line)\n\t\t\n\t\t\n\tdef generateAdjacentMatrix(self,nodeNum):\n\t\tadjacentMatrix = [[0 for j in range(nodeNum)] for i in range(nodeNum)]\n\t\tfor edge in self.edges:\n\t\t\tedge[0],edge[1] = int(edge[0]),int(edge[1])\n\t\t\tadjacentMatrix[edge[0]][edge[1]] = 1\n\t\t\tadjacentMatrix[edge[1]][edge[0]] = 1\n\t\treturn adjacentMatrix\n\t\t\n\t\t\n\ndef main():\n\tnodes_num = None\n\t# \u8282\u70b9\u5e8f\u53f7\u4ece0 -> n-1\n\twhile not nodes_num:\n\t\tnodes_num = input('Please input number of vertices(required > 0): ')\n\tep = edgeParser()\n\twhile True:\n\t\tline = sys.stdin.readline()\n\t\tif line.rstrip().strip() == '':\n\t\t\tbreak\n\t\telse:\n\t\t\tep.parsing(line)\n\tnodes_num = int(nodes_num)\n\tadjacentMatrix = ep.generateAdjacentMatrix(nodes_num)\n\t\n\tG = graph(nodes_num, adjacentMatrix)\n\tG.traverse('bfs')\n\t#G.traverse('dfs')\t\n\tG.checkLoop('kahn')\n\t\nif __name__ == \"__main__\":\n\tmain()"} {"blob_id": "0a114b7f988d80aa8a2a9ccff9e54458ef3647a7", "repo_name": "offbynull/offbynull.github.io", "path": "/docs/data/learn/Modeling/input/stats_code/Percentile.py", "length_bytes": 2028, "score": 3.53125, "int_score": 4, "content": "from bisect import bisect_left, bisect_right\nfrom sys import stdin\nfrom typing import TypeVar\n\nT = TypeVar('T')\n\n\n# MARKDOWN\ndef percentile_boundary(data: list[T], percent: float) -> float:\n data.sort()\n percentile_idx = percent * (len(data) - 1)\n return percentile_idx\n\n\ndef percentile_at(data: list[float], percent: float) -> float:\n percentile_idx = percentile_boundary(data, percent)\n if percentile_idx.is_integer():\n return data[int(percentile_idx)]\n elif len(data) > 1: # Avg values in indexes to left and right (feels wishy-washy). More accurate ways available?\n prev_idx = int(percentile_idx)\n next_idx = prev_idx + 1\n return (data[prev_idx] + data[next_idx]) / 2\n else:\n return data[0]\n\n\ndef percentile_in(data: list[float], percent: float, test_val: float) -> bool:\n val = percentile_at(data, percent)\n return test_val <= val\n\n\ndef percentile_for(data: list[float], value: float) -> float:\n # Sort the data, then find out ...\n # * how many elements come before value (before_cnt)\n # * how many elements are value (cnt)\n # then calculate as (before_cnt + 0.5*cnt) / len. This came from the book and feels very wishy-washy. More accurate\n # ways available?\n data.sort()\n before_idx = bisect_left(data, value)\n if data[before_idx] == value:\n before_idx -= 1\n before_cnt = before_idx + 1\n cnt = 0\n at_idx = bisect_left(data, value)\n while at_idx < len(data) and data[at_idx] == value:\n cnt += 1\n at_idx += 1\n return (before_cnt + 0.5 * cnt) / len(data)\n# MARKDOWN\n\n\ndef main():\n print(\"
\", end=\"\\n\\n\")\n print(\"`{bm-disable-all}`\", end=\"\\n\\n\")\n try:\n data_raw = ''.join(stdin.readlines())\n print('```')\n exec(data_raw)\n print('```')\n print()\n finally:\n print(\"
\", end=\"\\n\\n\")\n print(\"`{bm-enable-all}`\", end=\"\\n\\n\")\n\n\nif __name__ == '__main__':\n percentile_for([1, 5, 4, 4, 5, 5, 6], 4.5)\n"} {"blob_id": "43dde63a9c6b5281d2739ffaa72e9adde7a08456", "repo_name": "GoldenShiber/AdventOfCoding2018", "path": "/RevisedCode/RevisedDay15verFin.py", "length_bytes": 4880, "score": 3.75, "int_score": 4, "content": "from itertools import count\nimport fileinput\nimport heapq\n\n'''\n\nThis Methods is in whole learned from Michael Fogleman and is different \nfrom my current method which utilizes arrowmaps to find the distance. \nMy own methods is significant slower for more complex types of dungeons,\nhowever it can be even fast if it uses smart mapping techniques.\n\nHis website is https://www.michaelfogleman.com/aoc18/ great read... \nto learn techniques and stuff.\n\n'''\n\n# General methods which are not class based\n\n# Shortest path chooses the shortest path from a target and its enemies.\ndef shortest_paths(source, targets, occupied):\n result = []\n best = None\n visited = set(occupied)\n queue = [(0, [source])]\n while queue:\n distance, path = heapq.heappop(queue)\n if best and len(path) > best:\n return result\n node = path[-1]\n if node in targets:\n result.append(path)\n best = len(path)\n continue\n if node in visited:\n continue\n visited.add(node)\n for neighbor in adjacent({node}):\n if neighbor in visited:\n continue\n heapq.heappush(queue, (distance + 1, path + [neighbor]))\n return result\n\n# Manhattan distance nuf said\ndef manhattan_distance(a, b):\n\treturn abs(a[0] - b[0]) + abs(a[1] - b[1])\n\n# adjacent returns all cells adjacent to the position\ndef adjacent(positions):\n return set((y + dy, x + dx)\n for y, x in positions\n for dy, dx in [(-1, 0), (0, -1), (0, 1), (1, 0)])\n\n# choose_target determines which tile to move forward to\ndef choose_target(position, targets, occupied):\n if not targets:\n return None\n if position in targets:\n return position\n paths = shortest_paths(position, targets, occupied)\n ends = [x[-1] for x in paths]\n return min(ends) if ends else None\n\n# choose_move chooses the move, that the unit moves by\ndef choose_move(position, target, occupied):\n\tif position == target:\n\t\treturn position\n\tpaths = shortest_paths(position, {target}, occupied)\n\tstarts = [x[1] for x in paths]\n\treturn min(starts) if starts else None\n\n# A unit can either be an Elf (E) or Goblin (G) dependable on postion.\nclass Unit:\n\tdef __init__(self, team, position):\n\t\tself.team = team\n\t\tself.position = position \n\t\tself.hp = 200\n\n# Then we need a model of the game which includes the models, units and round etc.\n# Elf damage is specific for part 2\nclass Model:\n\tdef __init__(self, lines, elf_attack=None):\n\t\tself.elf_attack = elf_attack\n\t\tself.walls = set()\n\t\tself.units = []\n\t\tself.rounds = 0\n\t\tfor y, line in enumerate(lines):\n\t\t\tfor x, c in enumerate(line.strip()):\n\t\t\t\tif c == \"#\":\n\t\t\t\t\tself.walls.add((y,x))\n\t\t\t\telif c in 'EG':\n\t\t\t\t\t# Seperate c as character, y and x as coordinates\n\t\t\t\t\tself.units.append(Unit(c, (y,x)))\n\n\tdef total_hp(self):\n\t\treturn sum(x.hp for x in self.units if x.hp > 0)\n\n\t# Occupied function return set of occupied squares \t\n\tdef occupied(self, unit=None):\n\t\tunits = set(x.position for x in self.units\n\t\t\t\t\tif x != unit and x.hp > 0)\n\t\treturn self.walls | units\n\t\n\t# get_move returns a new position for the unit during their turn\n\tdef get_move(self, unit):\n\t\toccupied = self.occupied(unit)\n\t\ttargets = set(x.position for x in self.units\n\t\t\t\t\t if x.team != unit.team and x.hp > 0)\n\t\tif not targets:\n\t\t\treturn None\n\t\tin_range = adjacent(targets) - occupied\n\t\ttarget = choose_target(unit.position, in_range, occupied)\n\t\tif target is None:\n\t\t\treturn unit.position\n\t\tmove = choose_move(unit.position, target, occupied)\n\t\treturn move\n\n\t# choose_attack choose the target to attack given an attacker\n\tdef get_attack(self, unit):\n\t\tunits = [[x.hp, x.position, x] for x in self.units\n\t\t\tif x.team != unit.team and x.hp > 0 and\n\t\t\t\tmanhattan_distance(unit.position, x.position) ==1]\n\t\treturn min(units)[-1] if units else None\n\n\t# The step method that goes through each round\n\tdef step(self):\n\t\tunits = sorted(self.units, key=lambda x: x.position)\n\t\tfor unit in units:\n\t\t\tif unit.hp <= 0:\n\t\t\t\tcontinue\n\t\t\tmove = self.get_move(unit)\n\t\t\tif move is None:\n\t\t\t\treturn False\n\t\t\tunit.position = move\n\t\t\tattack = self.get_attack(unit)\n\t\t\tif attack:\n\t\t\t\tif self.elf_attack:\n\t\t\t\t\tif unit.team == 'G':\n\t\t\t\t\t\tattack.hp -= 3\n\t\t\t\t\t\tif attack.hp <= 0:\n\t\t\t\t\t\t\traise Exception\n\t\t\t\t\telse:\n\t\t\t\t\t\tattack.hp -= self.elf_attack\n\t\t\t\telse:\n\t\t\t\t\tattack.hp -= 3\n\t\tself.rounds += 1\n\t\treturn True\n\t# After that there is a run method, to check if round is over or not\n\tdef run(self):\n\t\twhile True:\n\t\t\tif not self.step():\n\t\t\t\treturn self.rounds, self.total_hp()\n\t\n# Read in the lines \nlines = list(fileinput.input())\n\n# part 1\nrounds, hp = Model(lines).run()\nprint( \"The total score for part 1 is: \" + str(rounds * hp))\n\n# part 2\nfor elf_attack in count(4):\n\ttry:\n\t\trounds, hp = Model(lines, elf_attack).run()\n\t\tprint(\"The total score for part 2 is: \" + str(rounds * hp))\n\t\tbreak\n\texcept Exception:\n\t\tpass \n"} {"blob_id": "9400fbb2e0f63dd2ccbf8a4408c02f7d1ab235f6", "repo_name": "jjdblast/ml-1", "path": "/misc/impl_kpca.py", "length_bytes": 3229, "score": 3.96875, "int_score": 4, "content": "#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\r\n'''\r\nPCA implementation.\r\nPCA serves mainly as a dimensionality reduction technique.\r\n\r\nSeriously why do we use PCA?\r\nJust tranform the data to obtain uncorrelated features, or\r\nto represent the data using fewer features?\r\n\r\n--Cover:\r\nmax-variance interpretation (SVD/Eigen), conventional PCA.\r\nKernel PCA.\r\n\r\n--TODO:\r\nsparse PCA, haven't understand the idea yet, -_-//.\r\n\r\n--Math:\r\n1) Max-variance\r\nFind $w$ which solves\r\n\\begin{equation*}\r\n\\begin{aligned}\r\n&\\max_w & & \\|Xw\\|^2\\\\\r\n&\\text{s.t.} & & \\|w\\|=1\r\n\\end{aligned}\r\n\\end{equation*}\r\nSolve it via Lagrange multiplier, resulting into Eigen-decomposition.\r\nOr via SVD, which is more convinient solution to come up with.\r\n\r\n2) Min-reconstruction error\r\n'''\r\n\r\n\r\nimport numpy as np\r\nfrom scipy import ndimage\r\nimport matplotlib.pyplot as plt\r\nfrom scipy import spatial\r\n\r\n\r\n#---------------------------------------------------------\r\n# Conventional PCA\r\n# Code is obsolete, too easy, no need to write these functions.\r\n\r\ndef get_pc(X, eps=1e-8):\r\n '''\r\n Ignore those pc with $0$-singular-value, \r\n since they don't explain any variance.\r\n '''\r\n U,S,V = np.linalg.svd(X)\r\n return V[np.abs(S)>eps]\r\n \r\ndef get_score(X, C):\r\n return np.dot(X, C.T)\r\n\r\ndef reconstruct(M, C, k=3):\r\n '''\r\n Reconstruct original data.\r\n `M': score matrix,\r\n `C': pc matrix,\r\n `k': how many pc to use.\r\n '''\r\n return np.dot(M[:,:k], C[:k,:])\r\n\r\n#--------------------------------------------------------\r\n# Kernel PCA\r\n\r\ndef kernel_radial(X, c=10):\r\n # compute pairwise distance\r\n D = spatial.distance.pdist(X, metric='euclidean')\r\n D = spatial.distance.squareform(D)**2\r\n\r\n # kernel matrix \r\n K = np.exp(-D/c)\r\n return K\r\n\r\ndef kernel_poly(X, c=0, p=2):\r\n D = np.dot(X, X.T)\r\n C = c * np.outer(np.ones(X.shape[0]), np.ones(X.shape[0]))\r\n K = D + C\r\n K = K**p\r\n return K\r\n\r\ndef test_kpca():\r\n import o_stat\r\n X = o_stat.circle_sample([1.5,5.0,10.0,3.5], ndim=2)\r\n n = X.shape[0]\r\n m = 4\r\n\r\n # no centering\r\n K = kernel_poly(X, 10, 5)\r\n USV = np.linalg.svd(K)\r\n Z = USV[0]*np.sqrt(USV[1])\r\n \r\n # centering\r\n M = np.eye(N=n) - np.outer(np.ones(n), np.ones(n))\r\n K2 = np.dot(np.dot(M, K), M)\r\n USV2 = np.linalg.svd(K2)\r\n Z2 = USV2[0]*np.sqrt(USV2[1])\r\n\r\n color = 'bcrgm'\r\n fig = plt.figure()\r\n ax1 = fig.add_subplot(131)\r\n ax2 = fig.add_subplot(132)\r\n ax3 = fig.add_subplot(133)\r\n for i in range(m):\r\n f = i*n/m\r\n t = (i+1)*n/m\r\n ax1.scatter(X[f:t,0], X[f:t,1], color=color[i])\r\n ax2.scatter(Z[f:t,0], Z[f:t,1], color=color[i])\r\n ax3.scatter(Z2[f:t,0], Z2[f:t,1], color=color[i])\r\n plt.show()\r\n\r\ndef test_kpca2():\r\n import o_stat\r\n X = np.vstack((np.random.sample(size=(20,2))+(-1.0,1.0),\r\n np.random.sample(size=(30,2))+(1.0,1.0),\r\n np.random.sample(size=(15,2))+(0, -1.0)))\r\n K = kernel_poly(X, 1)\r\n U,S,V = np.linalg.svd(K)\r\n Z = U*np.sqrt(S)\r\n\r\n plt.subplot(1,2,1)\r\n plt.scatter(X[:,0], X[:,1])\r\n plt.subplot(1,2,2)\r\n plt.scatter(Z[:,0], Z[:,1])\r\n plt.show()\r\n\r\nif __name__ == '__main__':\r\n test_kpca()\r\n"} {"blob_id": "47a08329e304dd6307ef5a6b709166694422c118", "repo_name": "johnnylecy/Target-Offer-python", "path": "/\u5e73\u8861\u4e8c\u53c9\u6811.py", "length_bytes": 770, "score": 3.90625, "int_score": 4, "content": "'''\n\u9898\u76ee\n\u8f93\u5165\u4e00\u68f5\u4e8c\u53c9\u6811\uff0c\u5224\u65ad\u8be5\u4e8c\u53c9\u6811\u662f\u5426\u662f\u5e73\u8861\u4e8c\u53c9\u6811\u3002\n'''\n'''\n\u5206\u6790\uff1a\n\u9012\u5f52\u5224\u65ad\u8282\u70b9\u5e73\u8861\u56e0\u5b50\uff0c\u4f46\u6df1\u5ea6\u91cd\u590d\u8ba1\u7b97\uff1b\n\n'''\n#coding:utf-8\nclass TreNode():\n def __init_(self, x=None):\n self.x = x\n self.left = None\n self.right = None\n\nclass Slt():\n def depth(self, node):\n if node ==None:\n return 0\n else:\n return max(self.depth(node.left), self.depth(node.right)) + 1\n def mtd(self, node):\n if not node:\n return True\n else:\n lamd = self.depth(node.left) - self.depth(node.right)\n if abs(lamd) > 1:\n return False\n else:\n self.mtd(node.left)\n self.mtd(node.right)\n\n\n"} {"blob_id": "ab86cb9ac0de5f3c3e29b7183f0854573f9aecda", "repo_name": "dcalacci/ml-expectimax-agent", "path": "/multiagent/mazeUtils.py", "length_bytes": 3556, "score": 3.609375, "int_score": 4, "content": "def getSuccessorsInMaze(pos, walls):\n \"returns a list of successors limited by the design of the maze\"\n\n def notInWall(pos):\n \"returns true if the position is not in a wall\"\n x = pos[0]\n y = pos[1]\n\n # true if the position is in the boundaries of the maze\n inBounds = not (x <= 0 or \n x >= walls.width or \n y <= 0 or \n y >= walls.height)\n\n # returns true if the posn isn't in a wall or out of bounds\n return (not walls[pos[0]][pos[1]] ) and inBounds\n \n def getSuccessors():\n \"returns a list of all possible successors\"\n x = pos[0]\n y = pos[1]\n successors = []\n successors.append((x+1, y+1))\n successors.append((x+1, y))\n successors.append((x+1, y-1))\n successors.append((x, y-1))\n successors.append((x-1, y-1))\n successors.append((x-1, y))\n successors.append((x-1, y+1))\n successors.append((x, y+1))\n return successors\n\n return filter(notInWall, getSuccessors())\n\n\ndef getSuccessorsForBFS(position, walls):\n successors = []\n x = position[0]\n y = position[1]\n \n if(x - 1 >= 0):\n if(not walls[x - 1][y]):\n successors.append((x - 1, y))\n if(y - 1 >= 0):\n if(not walls[x - 1][y - 1]):\n successors.append((x - 1, y - 1))\n if(y + 1 < walls.height):\n if(not walls[x - 1][y + 1]):\n successors.append((x - 1, y + 1))\n \n if(x + 1 < walls.width):\n if(not walls[x + 1][y]):\n successors.append((x + 1, y))\n if(y - 1 >= 0):\n if(not walls[x + 1][y - 1]):\n successors.append((x + 1, y - 1))\n if(y + 1 < walls.height):\n if(not walls[x + 1][y + 1]):\n successors.append((x + 1, y + 1))\n \n if(y - 1 >= 0):\n if(not walls[x][y - 1]):\n successors.append((x, y - 1))\n \n if(y + 1 < walls.height):\n if(not walls[x][y + 1]):\n successors.append((x, y + 1))\n \n return successors\n\ndef distanceInMaze(start, goal, walls):\n \"bfs to find distance from start to goal in the maze\"\n import util\n frontier = util.Queue()\n visited = []\n #print \"pushing: \", start, \" and \", 0\n frontier.push((start, 0)) # each node is a tuple: (pos, dist)\n \n while not frontier.isEmpty():\n currentNode = frontier.pop()\n #print currentNode\n if currentNode[0] == goal:\n return currentNode[1]\n nonVisited = [successor for successor in \n getSuccessorsInMaze(currentNode[0], walls) \n if successor not in visited]\n for successor in nonVisited:\n visited.append(successor)\n frontier.push((successor, 1 + currentNode[1]))\n return None\n\n_walls = None\n\ndef distancesInMaze(walls, distanceDict):\n \"\"\"\n Returns a hash of (start, goal) -> distance\n where start and goal are both posns, and distance is the\n 'maze-distance' between the start and goal.\n \"\"\"\n posns = []\n for x in range(walls.width):\n for y in range(walls.height): \n posns.append((x, y))\n\n for start in posns:\n for goal in posns:\n sg = (start, goal)\n gs = (goal, start)\n if (sg not in distanceDict and \n gs not in distanceDict and\n not walls[start[0]][start[1]] and\n not walls[goal[0]][goal[1]]):\n # print distanceInMaze(start, goal, walls)\n distanceDict[sg] = distanceInMaze(start, goal, walls)\n"} {"blob_id": "ccf25f91ddcd0bf2b02a950702137c7e7872e33d", "repo_name": "WeijunZhu31/Rutgers-Master-Courses", "path": "/2020Spring/DL/Homework/code_hw02/hw2Q2.py", "length_bytes": 1310, "score": 3.5625, "int_score": 4, "content": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nTitle : Homework02-02\r\nCreated on Mon Mar 23 22:45:36 2020\r\n@author: Weijun Zhu\r\n\"\"\"\r\n#%%\r\nimport tensorflow as tf\r\nprint(\"Tensorflow version: {}\".format(tf.__version__))\r\n\r\n#%%\r\n# a). \r\n# f2: \r\nwith tf.GradientTape() as gt:\r\n # Define the variables\r\n x = tf.Variable(1, dtype=tf.float32, name=\"x\") \r\n y = tf.Variable(1, dtype=tf.float32, name=\"y\")\r\n z = tf.Variable(1, dtype=tf.float32, name=\"z\")\r\n \r\n n1 = x*y\r\n n2 = n1*y\r\n n3 = tf.math.sigmoid(n1+y)\r\n n4 = 2*n3+x\r\n f2 = (tf.math.exp(n3))/(tf.math.exp(n1)+tf.math.exp(n3)+tf.math.exp(n4))\r\n\r\ngt = gt.gradient(f2,[x,y,z])\r\ngt1 = gt[0].numpy()\r\ngt2 = gt[1].numpy()\r\n\r\nprint(\"f2 function: \")\r\nprint(\"x=\", x.numpy(), \"y=\", y.numpy(), \"z=\", z.numpy())\r\nprint(\"n1=\", n1.numpy(),\"n2=\", n2.numpy(), \"n3=\", n3.numpy(), \"n4=\", n4.numpy())\r\nprint(\"f2=\", f2.numpy())\r\nprint(\"g1=\", gt1, \"g2=\", gt2)\r\n\r\n#%%\r\n# The value of the gradient vector of f2\r\ndef gradient_value(g1, g2, g3):\r\n x = g1\r\n y = g2\r\n z = g3\r\n \r\n n1 = x*y\r\n n2 = n1*y\r\n n3 = tf.math.sigmoid(n1+y)\r\n n4 = 2*n3+x\r\n f2 = (tf.math.exp(n3))/(tf.math.exp(n1)+tf.math.exp(n3)+tf.math.exp(n4))\r\n return f2\r\n\r\nprint(\"The value of the gradient vector of f2 is: {}\"\\\r\n .format(gradient_value(gt1, gt2, g3=None)))\r\n\r\n"} {"blob_id": "6dc3712c70bc40723995f792061e923e00e8fdc2", "repo_name": "catapult-project/catapult", "path": "/dashboard/dashboard/pinpoint/models/compare/thresholds_functional.py", "length_bytes": 2638, "score": 3.71875, "int_score": 4, "content": "#!/usr/bin/env python\n# Copyright 2018 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\"\"\"Calculates significance thresholds for functional comparisons.\"\"\"\nfrom __future__ import print_function\nfrom __future__ import division\nfrom __future__ import absolute_import\n\nimport itertools\nimport math\n\nfrom scipy import stats\n\n# The approximate false negative rate.\nP_VALUE = 0.01\n\n\ndef main():\n # failure_rate is the size of differences we are trying to detect\n # with a P_VALUE false negative rate. Smaller differences need\n # larger samples to have the same false negative rate.\n for failure_rate in (.1, .2, .3, .4, .5, .6, .7, .8, .9, 1):\n # Calculate the threshold for every sample_size, stopping\n # when the threshold is lower than P_VALUE.\n thresholds = []\n for sample_size in itertools.count(1):\n threshold = _Threshold(P_VALUE, failure_rate, sample_size)\n thresholds.append(threshold)\n if threshold < P_VALUE:\n break\n\n _PrintThresholds(failure_rate, thresholds)\n\n\ndef _Threshold(p_value, failure_rate, sample_size):\n \"\"\"Calculates a significance threshold.\n\n Arguments:\n p_value: The approximate target false negative rate.\n failure_rate: The size of differences we are trying to detect with a p_value\n false negative rate. If we want to detect that a test went from 0%\n failing to 40% failing, this is 0.4.\n sample_size: The number of values in each sample. The bigger the samples,\n the more statistical power we have, and the lower the threshold.\n\n Returns:\n The significance threshold.\n \"\"\"\n # Use the binomial distribution to find the sample of pass/fails where the\n # given sample or more extreme samples have p_value probability of occurring.\n failure_count = int(stats.binom(sample_size, failure_rate).ppf(p_value))\n a = [0] * sample_size\n b = [0] * (sample_size - failure_count) + [1] * failure_count\n try:\n return stats.mannwhitneyu(a, b, alternative='two-sided').pvalue\n except ValueError:\n return 1.0\n\n\ndef _PrintThresholds(distance, thresholds):\n \"\"\"Groups values into lines of 10 so they fit in the 80-character limit.\"\"\"\n print('# ' + '%.1f' % distance)\n for i in range(0, len(thresholds), 10):\n threshold_line = thresholds[i:i + 10]\n print(', '.join(_Format(threshold) for threshold in threshold_line) + ',')\n\n\ndef _Format(number):\n \"\"\"Makes all numbers a consistent length.\"\"\"\n if number == 1:\n return '1.000'\n return ('%.4f' % (math.ceil(number * 10000) / 10000)).lstrip('0')\n\n\nif __name__ == '__main__':\n main()\n"} {"blob_id": "4698415fd2986c7825d25d2946aa5023322ce0a3", "repo_name": "Rohan669/CAI_500", "path": "/sieveoferatosthenes.py", "length_bytes": 718, "score": 4.125, "int_score": 4, "content": "\r\n\r\n\"\"\" Sieve of Erosthenes\"\"\"\r\nfrom math import sqrt\r\nn=input(\"enter the number upto which you want to find the primes\\n\")\r\nn=int(n)\r\na=[i for i in range(2,n+1)]\r\nprime_list=[]\r\nnon_prime_list=[]\r\n\r\n\"\"\"Implementation of algorithm\"\"\"\r\na_logic=[[i,True] for i in a]\r\na_logic=dict(a_logic)\r\ni=0\r\n\r\nfor i in range(2,int(sqrt(n)+1)):\r\n if a_logic[i]==True:\r\n j=0\r\n while i**2+j*i<=n:\r\n a_logic[i**2+j*i]=False\r\n j+=1\r\n \r\n\"\"\" finding the prime number positions for false\"\"\" \r\nfor i in a:\r\n if a_logic[i]==True:\r\n prime_list.append(i)\r\n print(i)\r\n else:\r\n non_prime_list.append(i)\r\n \r\n \r\n\r\n \r\n \r\n \r\n\r\n \r\n\r\n"} {"blob_id": "69b3b77439bab4e8e6dc0290eca23a6b29ff0a7e", "repo_name": "mgorgei/codeeval", "path": "/Medium/c46 Prime Numbers.py", "length_bytes": 1237, "score": 3.90625, "int_score": 4, "content": "'''PRIME NUMBERS\n\nPrint out the prime numbers less than a given number N. For bonus points your\nsolution should run in N*(log(N)) time or better. You may assume that N is\nalways a positive integer.\n\nINPUT SAMPLE:\n\nYour program should accept as its first argument a path to a filename. Each line\nin this file is one test case. Each test case will contain an integer\nn < 4,294,967,295. E.g.\n\n10\n20\n100\n\nOUTPUT SAMPLE:\n\nFor each line of input, print out the prime numbers less than N, in ascending\norder, comma delimited. (There should not be any spaces between the comma and\nnumbers) E.g.\n\n2,3,5,7\n2,3,5,7,11,13,17,19\n2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97\n'''\ndef f(test='10'):\n n = int(test.strip())\n nlist = []\n for i in range(0, n+1):\n nlist.append([i, True])\n start = 2\n while start < n:\n for j in range(start, n+1, start):\n if j != start:\n nlist[j][1] = False\n for j in range(start+1, n+1):\n if nlist[j][1] == True:\n start = j\n break\n else:\n break\n result = \"\"\n for i in range(2, n):\n if nlist[i][1]:\n result+=str(nlist[i][0]) + ','\n print(result[:-1])\n"} {"blob_id": "a42ecee3f025f4e26fb624d34ed9ddb0746350ac", "repo_name": "xk005/mooc", "path": "/Data_structure_and_algorithm/3_1.py", "length_bytes": 1652, "score": 3.71875, "int_score": 4, "content": "class Stack:\n def __init__(self):\n self.items = []\n def isEmpty(self):\n return self.items == []\n def push(self, item):\n self.items.append(item)\n def pop(self):\n return self.items.pop()\n def peek(self):\n return self.items[len(self.items)-1]\n def size(self):\n return len(self.items)\n def stack(self):\n return self.items\n \ndef calculate(s):\n\n\n opStack=Stack()\n numStack=Stack()\n prec={}\n prec['^']=4\n prec['*']=3\n prec['/']=3\n prec['+']=2\n prec['-']=2\n prec['(']=1\n s=list(s)\n for token in s: \n if token.isdigit():\n numStack.push(int(token))\n elif token=='(':\n opStack.push(token)\n elif token==')':\n toptoken=opStack.pop()\n while toptoken!='(':\n operand2=numStack.pop()\n operand1=numStack.pop()\n result=eval(str(operand1)+str(toptoken)+str(operand2))\n numStack.push(result)\n toptoken=opStack.pop()\n else:\n while(not opStack.isEmpty())and (prec[opStack.peek()]>=prec[token]):\n op=opStack.pop()\n operand2=numStack.pop()\n operand1=numStack.pop()\n result=eval(str(operand1)+str(op)+str(operand2))\n numStack.push(result)\n opStack.push(token)\n while not opStack.isEmpty():\n op=opStack.pop()\n operand2=numStack.pop()\n operand1=numStack.pop()\n result=eval(str(operand1)+str(op)+str(operand2))\n numStack.push(result)\n return numStack.pop()\nprint(calculate(input()))"} {"blob_id": "b8c49654e5140e998d427de2060a2b6471fac194", "repo_name": "arkhebuz/spaceismore", "path": "/code/distances.py", "length_bytes": 8554, "score": 3.53125, "int_score": 4, "content": "# -*- coding: utf-8 -*-\nfrom numpy import matrix, cos, sin\nfrom PyKEP import DEG2RAD\n\n\nclass pos(object):\n def __init__(self):\n self.trajectory_positions = []\n\n axtl = 23.43929*DEG2RAD # Earth axial tlit\n # Macierz przejscia z ECI do helio\n self.mactran = matrix([ [1, 0, 0],\n [0, cos(axtl), sin(axtl)],\n [0, -sin(axtl), cos(axtl)] ])\n self.day = 86400.0\n\n def positions_lambert(self, l, sol=0, units = 1.0, index = 0):\n \"\"\"\n Plots a particular solution to a Lambert's problem\n\n USAGE: plot_lambert(ax,l, N=60, sol=0, units = 'PyKEP.AU', legend = 'False')\n * l: PyKEP.lambert_problem object\n * sol: solution to the Lambert's problem we want to plot (must be in 0..Nmax*2)\n where Nmax is the maximum number of revolutions for which there exist a solution.\n * units: the length unit to be used in the plot\n \"\"\"\n from PyKEP import propagate_lagrangian, AU\n\n if sol > l.get_Nmax()*2:\n raise ValueError(\"sol must be in 0 .. NMax*2 \\n * Nmax is the maximum number of revolutions for which there exist a solution to the Lambert's problem \\n * You can compute Nmax calling the get_Nmax() method of the lambert_problem object\")\n\n #We extract the relevant information from the Lambert's problem\n r = l.get_r1()\n v = l.get_v1()[sol]\n T = l.get_tof()\n mu = l.get_mu()\n\n #We define the integration time ...\n if T/86400. < 1:\n N = int(T) #...compute number of points...\n dt = T / (N-1.)\n else:\n N = int(2*T/86400.) #...compute number of points...\n dt = T / (N-1.)\n timetuple = [i*dt for i in range(N)]\n\n #... and alocate the cartesian components for r\n x = [0.0]*N\n y = [0.0]*N\n z = [0.0]*N\n\n #We calculate the spacecraft position at each dt\n for i in range(N):\n x[i] = r[0]/units\n y[i] = r[1]/units\n z[i] = r[2]/units\n r,v = propagate_lagrangian(r,v,dt,mu)\n\n self.trajectory_positions.append([index, x, y, z, timetuple])\n\n def positions_kepler(self, r,v,t,mu, units = 1, index = 0):\n \"\"\"\n Plots the result of a keplerian propagation\n\n USAGE: plot_kepler(ax,r,v,t,mu, N=60, units = 1, color = 'b', legend = False):\n * r: initial position (cartesian coordinates)\n * v: initial velocity (cartesian coordinates)\n * t: propagation time\n * mu: gravitational parameter\n * units: the length unit to be used in the plot\n \"\"\"\n\n from PyKEP import propagate_lagrangian\n\n #We define the integration time ...\n if t/86400. < 1:\n N = int(t) #...compute number of points...\n dt = t / (N-1.)\n else:\n N = int(2*t/86400.) #...compute number of points...\n dt = t / (N-1.)\n timetuple = [i*dt for i in range(N)]\n\n #... and calcuate the cartesian components for r\n x = [0.0]*N\n y = [0.0]*N\n z = [0.0]*N\n\n #We calculate the spacecraft position at each dt\n for i in range(N):\n x[i] = r[0]/units\n y[i] = r[1]/units\n z[i] = r[2]/units\n r,v = propagate_lagrangian(r,v,dt,mu)\n\n self.trajectory_positions.append([index, x, y, z, timetuple])\n\n def return_sc_positions(self):\n return self.trajectory_positions\n\n def set_launch_epoch(self, mjd2000_epoch):\n self.Lepoch = mjd2000_epoch\n\n def rework_time(self):\n T = self.trajectory_positions\n n = len(T)\n\n ep = self.Lepoch\n timespans = [T[i][4][-1]/86400. for i in range(n)]\n beginings = [ep + sum(timespans[:i]) for i in range(n)]\n\n # initialize lists...\n t = []\n x = []\n y = []\n z = []\n\n # ...and join values, correcting for time\n for g in range(n):\n t = t + [beginings[g]+i/86400. for i in T[g][4]]\n x = x + T[g][1]\n y = y + T[g][2]\n z = z + T[g][3]\n\n # save spacecraft state\n self.sc_state = [x, y, z, t]\n\n def eq2eclipt(self, xyz):\n macxyz = matrix(xyz)\n return self.mactran.dot(macxyz)\n\n def planets_pos(self):\n from jplephem import Ephemeris\n import de421\n from PyKEP import epoch\n self.eph = Ephemeris(de421)\n\n earthpos = []\n marspos = []\n venuspos = []\n\n for ep in self.sc_state[3]:\n posSun, __ = self.eph.position_and_velocity('sun', epoch(ep, epoch.epoch_type.MJD2000).jd)\n\n positione, __ = self.eph.position_and_velocity('earthmoon', epoch(ep, epoch.epoch_type.MJD2000).jd)\n positione = self.eq2eclipt(positione - posSun)\n earthpos.append(positione)\n\n positionm, __ = self.eph.position_and_velocity('mars', epoch(ep, epoch.epoch_type.MJD2000).jd)\n positionm = self.eq2eclipt(positionm - posSun)\n marspos.append(positionm)\n\n positionv, __ = self.eph.position_and_velocity('venus', epoch(ep, epoch.epoch_type.MJD2000).jd)\n positionv = self.eq2eclipt(positionv - posSun)\n venuspos.append(positionv)\n\n self.earthpos_km = [earthpos[i].reshape((1,3)).tolist()[0] for i in range(len(earthpos))]\n self.marspos_km = [marspos[i].reshape((1,3)).tolist()[0] for i in range(len(earthpos))]\n self.venuspos_km = [venuspos[i].reshape((1,3)).tolist()[0] for i in range(len(earthpos))]\n\n def distance_to_planets(self):\n dre = []\n drm = []\n drv = []\n\n for i in range(len(self.sc_state[3])):\n ep = self.earthpos_km[i]\n dist = [ep[0] - self.sc_state[0][i] / 1000.,\n ep[1] - self.sc_state[1][i] / 1000.,\n ep[2] - self.sc_state[2][i] / 1000.]\n dre.append((sum([g**2 for g in dist]))**.5)\n\n mp = self.marspos_km[i]\n dist = [mp[0] - self.sc_state[0][i] / 1000.,\n mp[1] - self.sc_state[1][i] / 1000.,\n mp[2] - self.sc_state[2][i] / 1000.]\n drm.append((sum([g**2 for g in dist]))**.5)\n\n vp = self.venuspos_km[i]\n dist = [vp[0] - self.sc_state[0][i] / 1000.,\n vp[1] - self.sc_state[1][i] / 1000.,\n vp[2] - self.sc_state[2][i] / 1000.]\n drv.append((sum([g**2 for g in dist]))**.5)\n\n return dre,drm, drv, self.sc_state[3]\n\n\ndef pl3_plot(earth, mars, venus, time, filename = False):\n import matplotlib.pyplot as plt\n import matplotlib.dates as mdates\n from datetime import datetime, timedelta\n from PyKEP import AU\n AU = AU/1000\n\n time = [datetime(2000, 01, 01) +timedelta(x) for x in time]\n\n plt.plot(time, [i/AU for i in earth], label='Earth')\n plt.plot(time, [i/AU for i in venus], label='Venus')\n plt.plot(time, [i/AU for i in mars], label='Mars')\n\n plt.legend(loc='upper left', prop={'size':13})\n plt.ylabel('Distance to spacecraft [$AU$]')\n\n # Axis and grid modyfications\n plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))\n plt.gca().xaxis.set_major_locator(mdates.AutoDateLocator(minticks=6, maxticks=10))\n plt.gca().xaxis.set_minor_locator(mdates.MonthLocator())\n plt.gcf().autofmt_xdate()\n\n #plt.gca().yaxis.set_major_locator(plt.MultipleLocator(1.0))\n #plt.gca().yaxis.set_minor_locator(plt.MultipleLocator(0.1)\n\n plt.gca().xaxis.grid(True,'minor')\n #plt.gca().yaxis.grid(True,'minor')\n plt.gca().xaxis.grid(True,'major', linewidth=1)\n plt.gca().yaxis.grid(True,'major', linewidth=1)\n\n plt.tight_layout()\n if filename:\n plt.savefig(filename+'.png', dpi=200)\n plt.show()\n\n\nif __name__ == '__main__':\n from planets import de421_planets\n from mga import mga_1dsm\n import pandas as pd\n\n prt = pd.read_hdf('protolod.hdf', 'eme_500day_2018_single')\n prt = pd.read_hdf('protolod.hdf', 'eme_700day_2018_single')\n prt = pd.read_hdf('protolod.hdf', 'evme_2021_single')\n\n a = de421_planets()\n FBseq = a.evme_2021(400*1000,100*1000)\n prob = mga_1dsm(seq = FBseq)\n\n b = prt.ix[139:139, :]\n gen = b.values.tolist()[0][:14]\n\n posinst = pos()\n posinst = prob.AIO(gen, 0,0,0, posinst)\n\n posinst.rework_time()\n posinst.planets_pos()\n drz, drm, drv, t = posinst.distance_to_planets()\n pl3_plot(drz, drm, drv, t, filename = 0)\n\n\n"} {"blob_id": "f7aa291e4b5075d1f89d2dce96810a212c4e34fd", "repo_name": "atrobman/Complex", "path": "/Complex.py", "length_bytes": 2286, "score": 3.578125, "int_score": 4, "content": "from math import cos, sin, exp, log, atan2\r\n\r\nclass Complex:\r\n\r\n\tdef __init__(self, real, imag):\r\n\t\tself.real = real\r\n\t\tself.imag = imag\r\n\r\n\tdef mul(self, comp):\r\n\t\tn_real = self.real * comp.real - self.imag * comp.imag\r\n\t\tn_imag = self.real * comp.imag + self.imag * comp.real\r\n\r\n\t\treturn Complex(n_real, n_imag)\r\n\r\n\tdef add(self, comp):\r\n\t\tn_real = self.real + comp.real\r\n\t\tn_imag = self.imag + comp.imag\r\n\r\n\t\treturn Complex(n_real, n_imag)\r\n\r\n\tdef sub(self, comp):\r\n\t\tn_real = self.real - comp.real\r\n\t\tn_imag = self.imag - comp.imag\r\n\r\n\t\treturn Complex(n_real, n_imag)\r\n\r\n\tdef div(self, comp):\r\n\t\tif (comp.real ** 2 + comp.imag ** 2) != 0:\r\n\t\t\tn_real = (self.real * comp.real + self.imag * comp.imag) / (comp.real ** 2 + comp.imag ** 2)\r\n\t\t\tn_imag = (self.imag * comp.real - self.real * comp.imag) / (comp.real ** 2 + comp.imag ** 2)\r\n\r\n\t\t\treturn Complex(n_real, n_imag)\r\n\t\telse:\r\n\t\t\traise ZeroDivisionError(\"division by zero\")\r\n\r\n\r\n\tdef pow(self, comp):\r\n\r\n\t\tif self.real == 0 and self.imag == 0 and comp.real == 0 and comp.imag == 0:\r\n\t\t\traise ArithmeticError(\"indefinite power\")\r\n\r\n\t\telif self.real == 0 and self.imag == 0:\r\n\t\t\treturn Complex(0, 0)\r\n\r\n\t\telif self.real == 1 and self.imag == 0:\r\n\t\t\treturn Complex(1, 0)\r\n\r\n\t\telif comp.real == 0 and comp.imag == 0:\r\n\t\t\treturn Complex(1, 0)\r\n\r\n\t\telif comp.real == 1 and comp.imag == 0:\r\n\t\t\treturn Complex(self.real, self.imag)\r\n\r\n\t\telse:\r\n\t\t\tmult1 = (self.real ** 2 + self.imag ** 2) ** (comp.real / 2) * exp(-comp.imag * atan2(self.imag, self.real))\r\n\t\t\treal_mult = cos(comp.real * atan2(self.imag, self.real) + .5 * comp.imag * log(self.real**2 + self.imag**2))\r\n\t\t\timag_mult = sin(comp.real * atan2(self.imag, self.real) + .5 * comp.imag * log(self.real**2 + self.imag**2))\r\n\r\n\t\t\tn_real = mult1 * real_mult\r\n\t\t\tn_imag = mult1 * imag_mult\r\n\r\n\t\t\treturn Complex(n_real, n_imag)\r\n\r\n\tdef __str__(self):\r\n\r\n\t\tmsg = \"\"\r\n\t\tif self.real != 0:\r\n\t\t\tmsg += f\"{self.real} \"\r\n\r\n\t\tif self.imag != 0:\r\n\t\t\tif self.imag > 0 and self.real != 0:\r\n\t\t\t\tmsg += f\"+ {self.imag}*i\"\r\n\t\t\telif self.imag < 0 and self.real != 0:\r\n\t\t\t\tmsg += f\"- {self.imag*-1}*i\"\r\n\t\t\telif self.imag > 0 and self.real == 0:\r\n\t\t\t\tmsg += f\"{self.imag}*i\"\r\n\t\t\telif self.imag < 0 and self.real == 0:\r\n\t\t\t\tmsg += f\"{self.imag}*i\"\r\n\r\n\t\telif msg == \"\":\r\n\t\t\t\tmsg = \"0\"\r\n\r\n\t\treturn msg"} {"blob_id": "b3bde985632bef3dd48627d34fa70a12d7222330", "repo_name": "hanrick2000/LC-1", "path": "/lc_ladder/Basic_Algo/graph-bfs-dfs/Word_Ladder_II.py", "length_bytes": 4438, "score": 3.75, "int_score": 4, "content": "#! /usr/local/bin/python3\n\n# https://www.lintcode.com/problem/word-ladder-ii/description\n# Example\n# \u7ed9\u51fa\u4e24\u4e2a\u5355\u8bcd\uff08start\u548cend\uff09\u548c\u4e00\u4e2a\u5b57\u5178\uff0c\u627e\u51fa\u6240\u6709\u4ecestart\u5230end\u7684\u6700\u77ed\u8f6c\u6362\u5e8f\u5217\u3002\n#\n# \u53d8\u6362\u89c4\u5219\u5982\u4e0b\uff1a\n#\n# \u6bcf\u6b21\u53ea\u80fd\u6539\u53d8\u4e00\u4e2a\u5b57\u6bcd\u3002\n# \u53d8\u6362\u8fc7\u7a0b\u4e2d\u7684\u4e2d\u95f4\u5355\u8bcd\u5fc5\u987b\u5728\u5b57\u5178\u4e2d\u51fa\u73b0\u3002\n# \u6837\u4f8b\n# \u7ed9\u51fa\u6570\u636e\u5982\u4e0b\uff1a\n#\n# start = \"hit\"\n# end = \"cog\"\n# dict = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\"]\n#\n# \u8fd4\u56de\n#\n# [\n# [\"hit\",\"hot\",\"dot\",\"dog\",\"cog\"],\n# [\"hit\",\"hot\",\"lot\",\"log\",\"cog\"]\n# ]\n# \u6ce8\u610f\u4e8b\u9879\n# \u6240\u6709\u5355\u8bcd\u5177\u6709\u76f8\u540c\u7684\u957f\u5ea6\u3002\n# \u6240\u6709\u5355\u8bcd\u90fd\u53ea\u5305\u542b\u5c0f\u5199\u5b57\u6bcd\u3002\n\"\"\"\nAlgo:\nD.S.:\n\nSolution:\n\n\nCorner cases:\n\"\"\"\n\nclass Solution1:\n \"\"\"\n @param: start: a string\n @param: end: a string\n @param: dict: a set of string\n @return: a list of lists of string\n \"\"\"\n def findLadders(self, start, end, dict):\n # write your code here\n dict.add(start)\n dict.add(end)\n distance = {} # key: node, val: distance to end, end to end is 0\n self.bfs(end, start, distance, dict)\n path = [start]\n res = []\n self.dfs(start, end, distance, dict, path, res)\n return res\n\n def bfs(self, from_word, to_word, distance, dict):\n from collections import deque\n distance[from_word] = 0\n q = deque([from_word])\n while q:\n cur_word = q.popleft()\n next_words = self._get_next_words(cur_word, dict)\n for word in next_words:\n if word not in distance:\n # same check as if word not visited\n distance[word] = distance[cur_word] + 1\n q.append(word)\n\n def dfs(self, from_word, to_word, distance, dict, path, res):\n if from_word == to_word:\n res.append(path[:])\n return\n for word in self._get_next_words(from_word, dict):\n if word in distance and distance[word] < distance[from_word]:\n path.append(word)\n self.dfs(word, to_word, distance, dict, path, res)\n path.pop()\n\n def _get_next_words(self, word, dict):\n res = []\n for i in range(len(word)):\n for char in \"abcdefghijklmnopqrstuvwxyz\":\n # str is not mutable, cannot modify on word\n next_word = word[:i] + char + word[i + 1:]\n if next_word in dict:\n res.append(next_word)\n return res\n\nclass Solution2:\n \"\"\"\n @param: start: a string\n @param: end: a string\n @param: dict: a set of string\n @return: a list of lists of string\n \"\"\"\n def findLadders(self, start, end, dict):\n # write your code here\n dict.add(start)\n dict.add(end)\n distance = {} # key: node, val: distance to end, end to end is 0\n self.bfs(end, start, distance, dict)\n path = [start]\n res = []\n self.dfs(start, end, distance, dict, path, res)\n return res\n\n def bfs(self, from_word, to_word, distance, dict):\n from collections import deque\n distance[from_word] = 0\n q = deque([from_word])\n while q:\n cur_word = q.popleft()\n next_words = self._get_next_words(cur_word, dict)\n for word in next_words:\n if word not in distance:\n # same check as if word not visited\n distance[word] = distance[cur_word] + 1\n q.append(word)\n if to_word in distance and distance[word] > distance[to_word]:\n return\n\n def dfs(self, from_word, to_word, distance, dict, path, res):\n if from_word == to_word:\n res.append(path[:])\n return\n for word in self._get_next_words(from_word, dict):\n if word in distance and distance[word] < distance[from_word]:\n path.append(word)\n self.dfs(word, to_word, distance, dict, path, res)\n path.pop()\n\n def _get_next_words(self, word, dict):\n res = []\n for i in range(len(word)):\n for char in \"abcdefghijklmnopqrstuvwxyz\":\n # str is not mutable, cannot modify on word\n next_word = word[:i] + char + word[i + 1:]\n if next_word in dict:\n res.append(next_word)\n return res\n# Test Cases\nif __name__ == \"__main__\":\n solution = Solution()\n"} {"blob_id": "2a8152a1ee1c60d28c9603c0bde54e808f28641a", "repo_name": "AjaykumarGP/MyDataStructures_SolvedProblems", "path": "/Data structure/Array/Rearrange an array in maximum minimum form | Set 2 (O(1) extra space).py", "length_bytes": 688, "score": 3.953125, "int_score": 4, "content": "\n\n\n\n\n# Rearrange an array in maximum minimum form | Set 2 (O(1) extra space)\n\ndef rearrange(array):\n arraySize = len(array)\n minElement = 0\n maxElement = arraySize-1\n\n for i in range(0, len(array)):\n \n if i%2 == 0: #Odd position\n array[i] = array[i] + ((array[maxElement] % (arraySize+1)) * (arraySize+1))\n maxElement -= 1\n else: #Even position\n array[i] = array[i] + ((array[minElement] % (arraySize+1)) * (arraySize+1))\n minElement += 1\n \n print(array)\n\n for i in range(0, len(array)):\n print(array[i]//(arraySize+1), end=\" \")\n\n\n\narray = [1, 2, 3, 4, 5, 6, 7]\nrearrange(array)\n\n"} {"blob_id": "c834869fff1b661682d80ed78052da42ac5dcc7f", "repo_name": "AidanOrefice/Hexagonal-Model", "path": "/Hexagon.py", "length_bytes": 24825, "score": 3.71875, "int_score": 4, "content": "\"\"\"\r\nStart Date: 12/10/2020\r\nAuthors: Daniel Loughran and Aidan Orefice\r\nScript to initialise the hexagonal lattice\r\n\r\nCreate a simple animation to highlight the basic mechanics of lattice are working. \r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport time\r\nimport matplotlib.pyplot as plt\r\nfrom configuration import *\r\nimport pandas as pd\r\nfrom itertools import groupby\r\nfrom operator import itemgetter\r\nfrom matplotlib.lines import Line2D\r\nfrom scipy.spatial.distance import euclidean\r\nfrom hexalattice.hexalattice import *\r\nimport matplotlib as mpl\r\n\r\nmpl.rcParams.update({\r\n 'figure.figsize' : [16,9],\r\n 'xtick.labelsize' : 15,\r\n 'ytick.labelsize' : 15,\r\n 'axes.labelsize' : 25,\r\n 'legend.fontsize' : 17,\r\n 'savefig.bbox' : 'tight',\r\n})\r\n\r\ndef choose_numbers(list1, prob):\r\n new_list = []\r\n deleted_list = []\r\n for i in list1:\r\n p = np.random.uniform(0,1)\r\n if p < prob:\r\n new_list.append(i)\r\n else:\r\n deleted_list.append(i)\r\n return new_list, deleted_list\r\n\r\nclass HexagonalLattice():\r\n '''\r\n Class that controls the physical attributes of the hexagonal lattice.\r\n\r\n Parameters:\r\n height - vertical length of the hexagonal lattice, in units of # of cells.\r\n width - horizontal length of the vertical lattice, in units of # of cells.\r\n\r\n Attributes:\r\n height - vertical length of the hexagonal lattice, in units of # of cells.\r\n width - horizontal length of the hexagonal lattice, in units of # of cells.\r\n hexagon - hexagonal lattice unrolled into 1d array - used for charge spread.\r\n ref - hexagonal lattice unrolled into 1d array - used for keeping track of state of cell.\r\n neighbours - dictionary of the neighbours of each lattice site.\r\n '''\r\n def __init__(self, width, height, runtime, threshold, sigmoid_strength, coupling = 1, refractory_period = 10,\r\n graph = False, FullStateMethod = False, stats = False, seed = 0, x = 0, multiplier = 7):\r\n self.height = height\r\n self.width = width\r\n self.dt = 1 #Discrete time width of lattice.\r\n self.threshold = threshold\r\n self.runtime = runtime #Total time we want to run for.\r\n self.sig_st = sigmoid_strength\r\n self.coupling = pow(coupling, 1/2)\r\n self.ref_per = refractory_period + 2\r\n self.graph = graph\r\n self.full_save = FullStateMethod #Options r full (whole run), any number (last x timesteps), transition (150 before AF, 150 after AF), False (Nothign saved)\r\n self.pacing_period = width * 2\r\n self.stats = stats\r\n self.x_graph = x\r\n self.multiplier = multiplier\r\n \r\n if seed == 0:\r\n self.seed = np.random.randint(0,int(2**32 - 1))\r\n else:\r\n self.seed = seed\r\n np.random.seed(self.seed)\r\n\r\n self.title = title + str(self.seed)\r\n\r\n #Ensuring lattice is of the correct dimensions - for toroidal geometry lattice must be even int x even int\r\n if not(self.width % 2 == 0) or not(self.height % 2 == 0):\r\n raise ValueError('The lattice must be of dimensions (even integer) x (even integer).')\r\n\r\n def CreateLattice(self):\r\n self.hexagon = np.zeros((self.width * self.height), dtype = np.float16) #Hexagonal Lattice in 1d array.\r\n self.ref = np.zeros((self.width * self.height), dtype = np.float16) #Identical for recording refractoriness.\r\n self.Neighbours()\r\n\r\n def CreateLatticeNoNeighbours(self):\r\n self.hexagon = np.zeros((self.width * self.height), dtype = np.float16) #Hexagonal Lattice in 1d array.\r\n self.ref = np.zeros((self.width * self.height), dtype = np.float16) #Identical for recording refractoriness.\r\n\r\n def Neighbours(self):\r\n \"\"\"\r\n Method to initially identify the neighbours of each site on the hexagonal lattice.\r\n Only used during initialisation period of main script.\r\n\r\n\r\n Boundary Conditions:\r\n Currently modelled with a toroidal topology i.e. periodic in x and y plane.\r\n Next step could be to introduce a clindrical topology - this would mean create a discontinuity at the ends of\r\n the lattice in x plane. To implement this all j=0 or j =self.width - 1 sites, i.e all sites in the first and\r\n last columns, should be altered to not connect to sites on opposing side of lattice.\r\n\r\n\r\n Returns:\r\n neighbours - A dictionary with each lattice site (key) having a 1d array of it's lattice neighbours (value).\r\n \"\"\"\r\n self.neighbours = {}\r\n for i in range(self.height):\r\n if i == 0: #First row always even\r\n for j in range(0, self.width):\r\n if j == 0: # (0,0) root cell of the hexagonal lattice (bottom left).\r\n self.neighbours[0] = np.asarray([self.width * (self.height -1), 1, self.width])\r\n #, (self.width * 2) - 1, self.width - 1, self.width * self.height - 1\r\n elif j == self.width - 1: #bottom right corner\r\n self.neighbours[j] = np.asarray([self.width * self.height - 1, j + self.width, j - 1, j + self.width - 1,\r\n self.width * self.height - 2])\r\n #, 0\r\n else:\r\n self.neighbours[j] = np.asarray([self.width * (self.height - 1) + j, j + 1, j + self.width,\r\n j - 1, j + self.width - 1, self.width * (self.height - 1) + j - 1])\r\n elif i == self.height - 1: #Last row always odd\r\n for j in range(0, self.width):\r\n index = i * self.width + j\r\n if j == 0: #top left corner\r\n self.neighbours[index] = np.asarray([index - self.width + 1, index + 1, 1, index - self.width,\r\n 0])\r\n #, self.width * self.height - 1\r\n elif j == self.width - 1: #top right corner\r\n self.neighbours[index] = np.asarray([ index - self.width,\r\n index - 1, self.width - 1])\r\n #, index - self.width + 1, 0,index - (self.width * 2) + 1,\r\n else:\r\n self.neighbours[index] = np.asarray([index - self.width + 1, index + 1, j + 1, index - self.width,\r\n index - 1, j])\r\n else: #All intermediate rows.\r\n if_even = i % 2 == 0 #False is odd True is even\r\n for j in range(0, self.width):\r\n index = i * self.width + j\r\n if j == 0: #left-most column\r\n if if_even:\r\n self.neighbours[index] = np.asarray([index - self.width, index + 1,\r\n index + self.width])\r\n #index - 1, index + self.width - 1,, index + (self.width * 2) - 1\r\n else:\r\n self.neighbours[index] = np.asarray([ index - self.width + 1, index + 1,\r\n index + self.width + 1, index + self.width, index - self.width])\r\n # index + self.width - 1,\r\n elif j == self.width - 1: #right-most column\r\n if if_even:\r\n self.neighbours[index] = np.asarray([index - self.width, index + self.width, index - 1,\r\n index + self.width - 1, index - self.width - 1])\r\n #index - self.width + 1,\r\n else:\r\n self.neighbours[index] = np.asarray([index - 1,\r\n index + self.width, index - self.width])\r\n #, index + 1, index - (self.width * 2) + 1, index - self.width + 1\r\n else: #All non-edge sites.\r\n if if_even:\r\n self.neighbours[index] = np.asarray([index - self.width, index + 1, index + self.width,\r\n index + self.width - 1, index - self.width - 1, index - 1])\r\n else:\r\n self.neighbours[index] = np.asarray([ index - self.width + 1, index + 1, index + self.width + 1,\r\n index - 1, index + self.width, index - self.width])\r\n \r\n def index_to_xy(self, index):\r\n row = np.floor(index / self.width)\r\n y = row - row*(1-(np.sqrt(3)/2)) #fix.\r\n if_even = row % 2 == 0\r\n if if_even:\r\n x = index - (row * self.width)\r\n else:\r\n x = index - (row * self.width) + 0.5\r\n return (x,y)\r\n\r\n def number_of_bonds(self):\r\n bonds = 0\r\n for i in self.neighbours.keys():\r\n for j in self.neighbours[i]:\r\n bonds += 1 \r\n return bonds/2\r\n \r\n def sinusoid2D(self, x, y, A, amp, mean):\r\n #Amplitude - directly sets the amplitude of the function\r\n #Mean - directly sets the offset/mean of the function.\r\n # 0 < (Mean +/- amp) < 1 \r\n #A stretch out the modes.\r\n #Ay must be an integer value to ensure periodicity.\r\n amp = float(amp)\r\n mean = float(mean)\r\n A = float(A)\r\n return (amp/2)*(np.sin(A*x*(2*np.pi/self.width))+np.sin(A*y*(2*np.pi/self.index_to_xy(self.height* self.width -1)[1]))) + mean\r\n\r\n def CouplingMethod(self, sinusoid_params = [1,0.1,0.6]):\r\n keys = self.neighbours.keys()\r\n copy = self.neighbours.copy()\r\n #new_dic = {i : [] for i in range(len(keys))}\r\n deleted_dic = {i : [] for i in range(len(keys))} \r\n counter = 0\r\n for i in keys:\r\n if i % self.width == self.width - 1:\r\n if np.floor(i/self.width) % 2 == 0:\r\n no_neighbours = 2\r\n else:\r\n no_neighbours = 0\r\n else:\r\n no_neighbours = 3\r\n for j in self.neighbours[i][:no_neighbours]:\r\n counter += 1\r\n x1, x2 = self.index_to_xy(i), self.index_to_xy(j)# change this x,y\r\n x,y = 0.5*(x1[0] + x2[0]), 0.5*(x1[1] + x2[1])\r\n grad_coupling = self.sinusoid2D(x, y, *sinusoid_params)\r\n p = np.random.uniform(0,1)\r\n if p < grad_coupling:\r\n pass #keep bond\r\n else:\r\n deleted_dic[i].append(j)\r\n deleted_dic[j].append(i)\r\n\r\n #If we want to look at the unique counts.\r\n #unique, counts = np.unique(self.coupling_samp, return_counts=True)\r\n #print(np.asarray((unique,counts)).T)\r\n \r\n for i in deleted_dic.keys():\r\n neighbours = deleted_dic[i]\r\n for j in neighbours:\r\n index = list(self.neighbours[i]).index(j)\r\n self.neighbours[i] = np.delete(self.neighbours[i], index)\r\n\r\n self.coupling_samp = np.asarray([len(self.neighbours[i])/len(copy[i]) for i in self.neighbours.keys()])\r\n self.mean, self.var = np.mean(self.coupling_samp), np.var(self.coupling_samp)\r\n\r\n def Coupling_Sample(self, A, amp, offs):\r\n fig,(ax1,ax2) = plt.subplots(1,2)\r\n\r\n\r\n hex_centers, ax1 = create_hex_grid(nx=self.width,ny=self.height, do_plot=True, align_to_origin = False, h_ax = ax1)\r\n x = [i[0] for i in hex_centers]\r\n y = [i[1] for i in hex_centers] \r\n\r\n sin_z = [self.sinusoid2D(x[i], y[i], A, amp, offs) for i in range(len(x))]\r\n a = ax1.scatter(x,y,marker = 'h', s=15, c = sin_z) #s=17\r\n plt.colorbar(a, ax = ax1, shrink=0.6)\r\n\r\n ax2.yaxis.set_tick_params(labelsize=0)\r\n hex_centers, ax2 = create_hex_grid(nx=self.width,ny=self.height, do_plot=True, align_to_origin = False, h_ax = ax2)\r\n x = [i[0] for i in hex_centers]\r\n y = [i[1] for i in hex_centers] \r\n b = ax2.scatter(x,y,marker = 'h', s=15, c = self.coupling_samp, cmap=plt.cm.get_cmap('viridis', 7))\r\n cbar = plt.colorbar(b,ax = ax2, ticks=np.arange(1/14,17/14,1/7), shrink = 0.6)\r\n cbar.set_ticklabels([\"0\", \"1/6\", \"1/3\", \"1/2\", \"2/3\", \"5/6\", \"1\"])\r\n #plt.clim(0,1)\r\n\r\n\r\n #Adding common X and Y axis labels\r\n '''fig.add_subplot(111, frameon=False)\r\n plt.tick_params(labelcolor='none', top=False, bottom=False, left=False, right=False)\r\n plt.xlabel(\"X position\")\r\n plt.ylabel(\"Y position\")'''\r\n\r\n plt.tight_layout()\r\n \r\n \r\n \"\"\"label_offs = 'Offset = ' + str(offs)\r\n label_amp = 'Amplitude = ' + str(amp)\r\n label_a = r'$A$ = ' + str(A)\r\n label_mean = 'Mean = ' + str(round(self.mean,3))\r\n label_variance = 'Variance = ' + str(round(self.var,3))\r\n label_seed = 'Seed = ' + str(self.seed)\r\n\r\n legend_elements = [Line2D([0], [0], marker='o', color='white', label=label_offs, markerfacecolor='white', markersize=0),\r\n Line2D([0], [0], marker='o', color='white', label=label_amp, markerfacecolor='white', markersize=0),\r\n Line2D([0], [0], marker='o', color='white', label=label_a, markerfacecolor='white', markersize=0),\r\n Line2D([0], [0], marker='o', color='white', label=label_mean, markerfacecolor='white', markersize=0),\r\n Line2D([0], [0], marker='o', color='white', label=label_variance, markerfacecolor='white', markersize=0),\r\n Line2D([0], [0], marker='o', color='white', label=label_seed, markerfacecolor='white', markersize=0)]\r\n\r\n fig.set_size_inches(16,9)\r\n plt.legend(handles = legend_elements, loc='upper center', bbox_to_anchor=(0.5, -0.025), ncol=3, fontsize = 14)\r\n plt.axis('scaled')\r\n plt.title(r\"Sample of $\\frac{Amplitude}{2} \\times \\left( \\sin(A\\frac{2\\pi x}{length}) + \\sin(A\\frac{2\\pi y}{height}) \\right) + Offset$\", fontsize = 20)\"\"\"\r\n plt.savefig('SpaceViz_%i,%i,%i,%i.png' %(amp*100,offs*100,A,self.seed))\r\n plt.close()\r\n \r\n def Initialise(self):\r\n self.index_int = [i*self.width for i in range(self.height)] #Left hand side\r\n self.ref[self.index_int] = 1\r\n\r\n def SigmoidDist(self,charges):\r\n return 1/(1+np.exp(-self.sig_st*(charges-self.threshold)))\r\n\r\n def ActivationCheck(self):\r\n index_charged = np.where(self.hexagon > 0)[0]\r\n p = (1 - self.SigmoidDist(self.hexagon[index_charged])) * self.multiplier\r\n a = np.random.rand(len(index_charged))\r\n self.index_act = index_charged[a>p]\r\n self.ref[self.index_act] = 1 #Set sites to activated.\r\n self.hexagon[index_charged] = 0\r\n if self.t % self.pacing_period == 0:\r\n self.index_act = np.concatenate((self.index_act,self.index_int))\r\n \r\n #Uses sites that have been set to activated and spreads their charge. Resets charge to zero of activated sites.\r\n def ChargeProp(self):\r\n #index_act = np.where(self.ref == 1)[0] #sites that are activated - need to spread their charge\r\n for ind in self.index_act:\r\n neighbours = self.neighbours[ind]\r\n avail_neighbours = [i for i in neighbours if self.ref[i] == 0]\r\n if len(avail_neighbours) > 0:\r\n self.hexagon[avail_neighbours] += 1/len(avail_neighbours)\r\n\r\n #Develops the states of each site.\r\n def StateDevelop(self):\r\n self.ref[self.ref >= 1] += 1\r\n self.ref[self.ref == self.ref_per] = 0\r\n\r\n def Per_check(self, per):\r\n indi = [(i*self.width) - 1 for i in range(1,self.height + 1)]#Indexs of right hand side\r\n pre_length = len(indi)\r\n for i in range(self.width - int(self.width/5), self.pacing_period):\r\n data = self.RefHistory[(self.t - self.pacing_period + i) * len(self.ref) : (self.t - self.pacing_period + i + 1) * len(self.ref)]\r\n indi = [j for j in indi if data[j] == 0]\r\n if len(indi) < pre_length: #Arbitrary fraction, len(indi) is number of edge sites not activated yet\r\n self.per = True\r\n return [per[0] + 1, per[1] + 1]\r\n return [per[0], per[1] + 1]\r\n\r\n def Stats_check(self):\r\n if self.in_AF == False:\r\n self.percolating = self.Per_check(self.percolating)\r\n if self.AF_check():\r\n self.in_AF = True\r\n self.AF_bool.append((self.t, self.in_AF))\r\n else:\r\n self.AF_bool.append((self.t, self.in_AF))\r\n else:\r\n if self.AF_check():\r\n self.in_AF = True\r\n else:\r\n self.in_AF = False\r\n self.AF_bool.append((self.t, self.in_AF))\r\n\r\n def AF_check(self):\r\n if sum(self.AF[self.t - self.pacing_period:self.t]) > len(self.AF[self.t - self.pacing_period:self.t]) * self.height * 1.1:\r\n return True #If sum of activ. sites over pacing period > 1.1 * expected number of activate --> FIBRILLATION.\r\n width_dif = int((self.pacing_period - self.width) / 4) #Checking if sites are activated at end of beat - trying to catch special cases\r\n avg_over_dif = sum(self.AF[self.t - width_dif:self.t]) / width_dif\r\n avg_over_norm = sum(self.AF[self.t + 1 - self.pacing_period:self.t - width_dif * 2]) / len(self.AF[self.t + 1 - self.pacing_period:self.t - width_dif * 2])\r\n if avg_over_dif > avg_over_norm / 6: #6 is an arbitrary fraction\r\n if self.AF[self.t - 1] > 0:\r\n return True\r\n else:\r\n return False\r\n else:\r\n return False\r\n\r\n def Search_Meth2(self): #Searches for the 2nd, 3rd and 4th re-excited sites. Returns time of 2nd re-excitation.\r\n sites = {}\r\n re_sites = {2:True, 3:True, 4:True}\r\n for j in range(self.AF_first_beat + 1, self.AF_last_beat):\r\n time_data = self.RefHistory[j*len(self.ref):(j+1)*len(self.ref)]\r\n activated_sites = np.where(time_data == 1)[0]\r\n for i in activated_sites:\r\n if i in list(sites.keys()):\r\n sites[i] += 1\r\n if re_sites[2] == True:\r\n if sites[i] == 2:\r\n re_sites[2] = i\r\n self.AF_time = (max(j-100,1), j+100) #Increased the range from 30 to 100\r\n #print(self.AF_time) #Transition time range\r\n k = self.ref_per - 1\r\n while k < j - self.AF_first_beat:\r\n new_time = j - k\r\n time_data = self.RefHistory[new_time*len(self.ref):(new_time+1)*len(self.ref)]\r\n activated_sites = np.where(time_data == 1)[0]\r\n if i in activated_sites:\r\n self.new_time = new_time\r\n self.ham_dis_time, self.x_mean_time = self.Hamming_distance(new_time)\r\n set_time = new_time\r\n k = self.runtime + 1\r\n k += 1\r\n self.Hamming_distance_arr = []\r\n for k in range(set_time - 10, set_time + 6):\r\n self.Hamming_distance_arr.append(self.Hamming_distance(k)[0])\r\n if re_sites[3] == True:\r\n if sites[i] == 3:\r\n re_sites[3] = i\r\n if re_sites[4] == True:\r\n if sites[i] == 4:\r\n re_sites[4] = i\r\n return re_sites\r\n else:\r\n sites[i] = 1\r\n return re_sites\r\n\r\n def Hamming_distance(self, AF_time):\r\n time_data = self.RefHistory[AF_time*len(self.ref):(AF_time+1)*len(self.ref)]\r\n activated_sites = np.where(time_data == 1)[0]\r\n activated_sites_x = [self.index_to_xy(i)[0] for i in activated_sites]\r\n if len(activated_sites) > 0:\r\n x_mean = np.mean(activated_sites_x)\r\n Ham_dis = np.sum((activated_sites_x-x_mean)**2)/(len(activated_sites_x)) \r\n return np.sqrt(Ham_dis), x_mean\r\n else:\r\n return 0, 0\r\n\r\n def Location_Check(self, site2, site3, site4):\r\n locs = [self.index_to_xy(site2), self.index_to_xy(site3), self.index_to_xy(site4)]\r\n verify = True\r\n err = 5.01\r\n height_y = self.index_to_xy(self.width*self.height -1)[1]\r\n for i in range(len(locs)-1):\r\n for j in range(1,len(locs)-i):\r\n if euclidean(locs[i],locs[i+j]) > err:\r\n verify = False\r\n if verify == False:\r\n val1 = (locs[i][0], locs[i][1] + height_y)\r\n val2 = (locs[i+j][0], locs[i+j][1] + height_y)\r\n if euclidean(val1,locs[i+j]) < err:\r\n verify = True\r\n elif euclidean(locs[i],val2) < err:\r\n verify = True\r\n return verify\r\n\r\n def Graph(self):\r\n f, ax = plt.subplots()\r\n x = [i for i in range(len(self.AF))]\r\n ax.plot(x, self.AF, ls = '-', label = 'Number of activated sites')\r\n ax.set_ylabel(\"Number of activated cells\")\r\n ax.set_xlabel(\"Time\")\r\n plt.savefig('Graphed_{}'.format(self.x_graph) + '.png') #################################\r\n plt.close()\r\n\r\n def save_choice(self): #Run once at end\r\n #AF Start time and location\r\n beat_af = [i[0] // self.pacing_period for i in self.AF_bool if i[1] == True]\r\n consec_AF_beats = [list(map(itemgetter(1), g)) for tk, g in groupby(enumerate(beat_af), lambda ix : ix[0] - ix[1])]\r\n consec_AF_beats_3 = [i for i in consec_AF_beats if len(i) > 2]\r\n #print(consec_AF_beats_3)\r\n if len(consec_AF_beats_3) > 0:\r\n self.AF_first_beat = (consec_AF_beats_3[0][0] - 1) * self.pacing_period #first beat after fib starts\r\n self.AF_last_beat = consec_AF_beats_3[0][-1] * self.pacing_period #last beat after fib starts\r\n #print(self.AF_first_beat, self.AF_last_beat)\r\n self.re_sites = self.Search_Meth2() #2nd,3rd,4th activated sites. Uncomment when doing location stuff\r\n self.kill = True\r\n\r\n def RunIt(self):\r\n self.t = 0\r\n self.RefHistory = np.zeros(((self.runtime) * len(self.ref)), dtype = np.int16)\r\n self.AF = np.zeros(self.runtime, dtype = np.int16)\r\n self.done = True\r\n self.in_AF = False\r\n self.AF_bool = []\r\n self.kill = False\r\n self.percolating = [0,0]\r\n while self.t < self.runtime:\r\n if self.t == 0:\r\n self.Initialise()\r\n self.ActivationCheck()\r\n self.AF[0] = len(self.index_act)\r\n self.ChargeProp()\r\n if self.full_save != False:\r\n self.RefHistory[0:len(self.ref)] = self.ref\r\n self.StateDevelop()\r\n self.t += self.dt\r\n elif self.t % self.pacing_period == 0:\r\n self.Stats_check()\r\n self.Initialise()\r\n self.save_choice()\r\n elif self.t == self.runtime - 1:\r\n self.Stats_check()\r\n self.save_choice()\r\n self.ActivationCheck()\r\n self.RefHistory[self.t*len(self.ref):(self.t+self.dt)*len(self.ref)] = self.ref\r\n self.AF[self.t] = len(self.index_act)\r\n self.ChargeProp()\r\n self.StateDevelop()\r\n self.t += self.dt\r\n if self.kill:\r\n self.t = self.runtime + 1 #To kill when AF starts\r\n if self.graph:\r\n self.Graph()\r\n if self.full_save == 'full':\r\n np.save(self.title + '.npy', self.RefHistory)\r\n elif self.full_save == 'transition' and self.in_AF:\r\n np.save(self.title + '.npy', self.RefHistory[self.AF_time[0] * len(self.ref):self.AF_time[1] * len(self.ref)])\r\n run = list(config.values())\r\n run.append(self.seed)\r\n #'location_2', 'location_3', 'location_4', 'AF_time',\r\n if self.kill:\r\n #self.Location_Check(self.re_sites[2],self.re_sites[3],self.re_sites[4])\r\n run.append(self.re_sites[2])\r\n run.append(self.re_sites[3])\r\n run.append(self.re_sites[4])\r\n run.append(self.Location_Check(self.re_sites[2],self.re_sites[3],self.re_sites[4]))\r\n run.append(self.AF_time)\r\n run.append([self.Hamming_distance_arr])\r\n run.append(self.ham_dis_time)\r\n run.append(self.x_mean_time)\r\n else:\r\n run.extend([False]*8)\r\n run.append(self.percolating[0] / self.percolating[1])\r\n run.append(self.title)\r\n return run\r\n\r\n\r\n\r\n\r\n\r\n"} {"blob_id": "41b5c621a8af4a0ee0078044df164746bb08d7f8", "repo_name": "matt123miller/Learning-Python-ML", "path": "/FYP/kernels.py", "length_bytes": 990, "score": 3.6875, "int_score": 4, "content": "# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport numpy.linalg as la\n\n\nclass Kernel(object):\n \"\"\"\n Implemented following definitions at found at http://en.wikipedia.org/wiki/Support_vector_machine\n \n For these ones do I have to choose my kernel and pass arguments defined in the outer def, \n later passing x and y args to the nested f function? How does this work?\n \"\"\"\n @staticmethod\n def linear_kernel(**kwargs):\n def f(x1, x2):\n return np.inner(x1, x2) # inner is the dot product\n return f\n\n @staticmethod\n def gaussian(sigma):\n def f(x, y):\n left = la.norm(x-y) ** 2\n right = (2 * sigma ** 2)\n exponent = np.sqrt(left / right) * -1\n return np.exp(exponent)\n return f\n\n @staticmethod\n def polynomial_kernel(exponent, coef, **kwargs):\n def f(x1, x2):\n dotProduct = np.inner(x1, x2)\n return (dotProduct + coef)**exponent\n return f\n\n"} {"blob_id": "5f474f1e26b16b07255f68698b23d70d45d3de65", "repo_name": "SimonHanrath/Projects", "path": "/RSA_cryptosystem/RSA_gen.py", "length_bytes": 1474, "score": 3.734375, "int_score": 4, "content": "import prime_gen\n\nfirst_primes_list = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29,\n 31, 37, 41, 43, 47, 53, 59, 61, 67,\n 71, 73, 79, 83, 89, 97, 101, 103,\n 107, 109, 113, 127, 131, 137, 139,\n 149, 151, 157, 163, 167, 173, 179,\n 181, 191, 193, 197, 199, 211, 223,\n 227, 229, 233, 239, 241, 251, 257,\n 263, 269, 271, 277, 281, 283, 293,\n 307, 311, 313, 317, 331, 337, 347, 349]\n\n\n# finds x and y such that s*a+t*b = gcd(a,b)\ndef gcdExtended(a, b):\n # Base Case\n if a == 0:\n return b, 0, 1\n\n gcd, x1, y1 = gcdExtended(b % a, a)\n\n # Update x and y using results of recursive\n # call\n x = y1 - (b // a) * x1\n y = x1\n\n return gcd, x, y\n\n\n# find a prime that is not in the given number\ndef find__prime_not_in(m):\n for prime in first_primes_list:\n if m % prime != 0:\n return prime\n return False\n\n\n# generates numbers private and public key\ndef gen_key_numbers(size):\n p = prime_gen.random_prime(size)\n q = prime_gen.random_prime(size)\n n = p * q\n m = (p - 1) * (q - 1)\n\n e = find__prime_not_in(m)\n if (e == False):\n keys(size)\n\n d = gcdExtended(m, e)[2] % m\n\n return (n, e), (n, d)\n\n\ndef encrypt(key, num):\n n = key[0]\n e = key[1]\n return pow(num, e, n)\n\n\ndef decrypt(key, num):\n n = key[0]\n d = key[1]\n return pow(num, d, n)\n"} {"blob_id": "5a3c3da67dd35481ba56df7d73018a2264a48927", "repo_name": "connorjtoth/project-euler", "path": "/problem_000021.py", "length_bytes": 1323, "score": 3.796875, "int_score": 4, "content": "'''\nProject Euler\nProblem 21\n2/20/2021\n\nLet d(n) be defined as the sum of proper divisors of n (numbers less than n\nwhich divide evenly into n).\nIf d(a) = b and d(b) = a, where a \u2260 b, then a and b are an amicable pair and\neach of a and b are called amicable numbers.\n\nFor example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55\nand 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71\nand 142; so d(284) = 220.\n\nEvaluate the sum of all the amicable numbers under 10000.\n'''\n\nfrom utils import get_divisors\n\n\ndef is_amicable_number(n, memo, primes):\n divisors = \\\n get_divisors(n, memo, primes, proper=True)\n candidate_pair = sum(divisors)\n if n == candidate_pair:\n return False, 0\n candidate_divisors = \\\n get_divisors(candidate_pair, memo, primes, proper=True)\n\n if n == sum(candidate_divisors):\n return True, candidate_pair\n else:\n return False, 0\n\n\ndef solution(upper_bound, memo={1: {1}}, primes=[2, 3]):\n amicable_numbers = set()\n for n in range(2, upper_bound):\n if n not in amicable_numbers:\n is_amicable, amicable_pair = is_amicable_number(n, memo, primes)\n if is_amicable:\n amicable_numbers |= {n, amicable_pair}\n return sum(amicable_numbers)\n\n\nprint(solution(10000))\n"} {"blob_id": "650bedb39a2c83e7131c07cfebe7ef8de353f1b3", "repo_name": "KyleRoarty/project_euler", "path": "/python/p043.py", "length_bytes": 1471, "score": 3.578125, "int_score": 4, "content": "#!/usr/bin/env python3\n\nimport itertools\nfrom functools import reduce\n\n'''\nThe number, 1406357289, is a 0 to 9 pandigital number because it is made up of\neach of the digits 0 to 9 in some order, but it also has a rather interesting\nsub-string divisibility property.\n\nLet d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note the following:\n\n d2d3d4=406 is divisible by 2\n d3d4d5=063 is divisible by 3\n d4d5d6=635 is divisible by 5\n d5d6d7=357 is divisible by 7\n d6d7d8=572 is divisible by 11\n d7d8d9=728 is divisible by 13\n d8d9d10=289 is divisible by 17\n\nFind the sum of all 0 to 9 pandigital numbers with this property.\n'''\n\n\npd_nums = []\n\n# Need to generate all possible permutations of 0,1,2,3,4,5,6,7,8,9\nnums = list(range(10))\nall_perms = list(itertools.permutations(nums))\n\n# Check that the permutations follow the rules listed above\nfor perm in all_perms:\n if (perm[3] % 2) != 0:\n continue\n if (reduce(lambda x,y: x*10+y, perm[2:5]) % 3) != 0:\n continue\n if (perm[5] % 5) != 0:\n continue\n if (reduce(lambda x,y: x*10+y, perm[4:7]) % 7) != 0:\n continue\n if (reduce(lambda x,y: x*10+y, perm[5:8]) % 11) != 0:\n continue\n if (reduce(lambda x,y: x*10+y, perm[6:9]) % 13) != 0:\n continue\n if (reduce(lambda x,y: x*10+y, perm[7:10]) % 17) != 0:\n continue\n\n pd_nums.append(reduce(lambda x,y: x*10+y, perm))\n\n\nprint('The winner is: {}'.format(sum(pd_nums)))\n"} {"blob_id": "b13568fd1c99072c3b47a3017e89f7cc42208921", "repo_name": "liukuannn/learning-notes", "path": "/02_CS/03_python/Practices/CanBeEqual.py", "length_bytes": 820, "score": 4.0, "int_score": 4, "content": "def searchEqual(l, target):\n if target == 0:\n return True\n \n elif not l:\n return False\n\n else:\n tar = target - l[0]\n return searchEqual(l[1:], target) or searchEqual(l[1:], tar)\n\n\nwhile True:\n try:\n length = int(input())\n numbers = list(map(int, input().split()))\n\n five = []\n three = []\n others = []\n\n for e in numbers:\n if e % 5 == 0:\n five.append(e)\n elif e % 3 == 0:\n three.append(e)\n else:\n others.append(e)\n\n diff_1 = abs(sum(five) - sum(three))\n diff_2 = sum(others) - diff_1\n\n if diff_2 % 2 != 0:\n print('false')\n else:\n print(str(searchEqual(others, diff_2 / 2)).lower())\n except:\n break\n"} {"blob_id": "0d3690b3482f15073597360c8041ff726417246b", "repo_name": "chaozc/leetcode", "path": "/python/p044.py", "length_bytes": 1496, "score": 3.515625, "int_score": 4, "content": "class Solution(object):\n def isMatch(self, s, p):\n \"\"\"\n :type s: str\n :type p: str\n :rtype: bool\n \"\"\"\n if len(p) == 0:\n return len(s) == 0\n tmp = p\n p = \"\"\n i = 0\n while i < len(tmp):\n p += tmp[i]\n if tmp[i] == '*':\n j = i+1\n while j < len(tmp) and tmp[j] == '*':\n j += 1\n i = j\n else:\n i += 1\n print p\n if (p[0] == '?') or (p[0] == '*'):\n f = [True for i in range(len(s)+1)]\n else:\n f = [False for i in range(len(s)+1)]\n\n for i in range(1, len(p)):\n for j in range(len(s), 0, -1):\n if p[i] == '?':\n f[j] = f[j-1]\n elif p[i] == '*':\n for k in range(j-1, -1, -1):\n f[j] = f[j] or f[k]\n if f[j]:\n break\n else:\n f[j] = f[j-1] and (p[i] == s[j-1])\n f[0] = f[0] and ((p[i] == '?') or (p[i] == '*'))\n return f[-1]\na = Solution()\nprint a.isMatch(\"baabbabaaaabababbbabbaabbabbabbbbbbabaaaaababbbaababaaabaaaabbbaaaaaaaaaabbaaaaaaabaabbabaaabaaaaaabaabbbabbbbbbaabababbabbabaaaaabbaaabbbaaabbababaaabbbbbbbbbbbaabaaabbababaaaababbaabbbaaabbbbaabaaba\",\n\"a*a*b*bb*ba***aab***b******aabaa*a*a*a*b**abbb***a*b*a*a*bb**ba****baa*****a*b***aaab*bab*****bb*a**\")"} {"blob_id": "096fb90f89c54219c36adc11d6696fb281812a61", "repo_name": "zackmcnulty/CSE_446-Machine_Learning", "path": "/hw/hw2/lasso.py", "length_bytes": 8839, "score": 3.75, "int_score": 4, "content": "'''\nlasso.py\n\nimplements the coordinate descent algorithm for LASSO regression.\nLASSO promotes sparsity by regularizing the Least Squared Error \nwith an L1 norm.\n\nX --> rows are data measurements, columns are specific features\ny = vector of response variables\n\n'''\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time\n\n\ndef generate_synthetic_data(n, d, k, variance, seed=123):\n '''\n Generates synthetic data following to procedure in the homework specification.\n n = number of data samples\n d = number of features per data sample\n k = number of relevant features (i.e. whose coefficient in w we expect to be non-negative)\n variance = variance for the zero-mean gaussian noise added on top of the true system\n seed = RNG seed for reproducibility\n\n '''\n if k > d:\n raise ValueError(\"The number of relevant features cannot be more than the number of features\")\n elif n < 1 or d < 1 or k < 0 or variance < 0:\n raise ValueError(\"Parameters n,d >= 1 and k,variance >= 0 must be true\")\n\n w_true = np.zeros((d ,1))\n \n # j+1 is to account for zero-based indexing in python\n for j in range(k): w_true[j] = (j+1) / k\n\n np.random.seed(seed)\n X = np.random.normal(size = (n,d))\n errors = np.random.normal(scale = np.sqrt(variance), size=(n,))\n\n y = np.reshape(np.dot(w_true.T, X.T) + errors.T, (n,))\n return (X, y)\n\n\n\ndef min_null_lambda(X, y):\n '''\n Returns the smallest lambda value that generates a null solution\n (i.e. w is entirely zeros). Start with lambda at this value and\n decrease over time\n Assuming y is a column vector of responses and X is a matrix with each column a feature\n and each row a measurement (i.e. the data matrix)\n '''\n return 2*np.max(np.abs(np.dot(y.T - np.mean(y), X)))\n\n\n\ndef lasso_coordinate_descent(X, y, lam, w_init = None, delta = 10e-4):\n '''\n Runs the coordinate descent algorithm on the LASSO regression problem.\n\n X = data matrix with each measurement stored as a row (columns are features) n x features\n y = response variable : n x 1\n lam = lambda value used for regularization\n delta = stopping condition; if no element in w changes by more than delta in a single iteration, stop.\n\n '''\n\n n = X.shape[0]\n d = X.shape[1]\n prev_w = np.ones((d,1))\n if w_init is None:\n w = np.zeros((d,))\n else:\n w = w_init\n\n c = np.zeros((d,))\n\n # a_k is just summing over all the rows of the squared entries. Thus, we can calculate it\n # quickly by squaring every entry in X (elementwise) then summing along the rows\n a = 2*np.sum(np.square(X), axis=0)\n\n # while we still have elements in w that changed by more than delta in last iteration\n while np.max(np.abs(w - prev_w)) > delta:\n\n prev_w = np.copy(w)\n\n wTXT = np.dot(w.T, X.T)\n\n b = 1/n * np.sum(y - wTXT)\n\n for k in range(d):\n\n # NOTE: Can use updated w_k values from SAME ROUND OF ITERATION piazza @199\n # For this reason, we have to recalculate wTXT at every iteration\n c[k] = 2*np.dot(X[:, k], y - (b + np.dot(w.T, X.T) - w[k]*X[:, k]))\n\n if c[k] < -1*lam:\n w[k] = (c[k] + lam) / a[k]\n elif c[k] > lam:\n w[k] = (c[k] - lam) / a[k]\n else:\n w[k] = 0\n\n return (w, b)\n\n\n # ===============================================================================\n\n # problem 7a)\n\n\nn = 500\nd = 1000\nk = 100\nvariance = 1\n(X, y) = generate_synthetic_data(n, d, k, variance, seed=3853)\n\nlam_max = min_null_lambda(X, y)\nlam_ratio = 1.5 # ratio to decrease lambda by during each iteration\ndelta = 10e-4 # threshold to stop iteration (search for better w)\n\ncurrent_lam = lam_max\nlam_vals = [lam_max]\nprev_w = None\n\nW = np.zeros((d, 1)) # we will store the resulting w for each lambda as a column in this matrix\nwhile np.count_nonzero(W[:, -1]) != d:\n current_lam = current_lam / lam_ratio\n lam_vals.append(current_lam)\n\n print(\"Running using lambda = \", current_lam)\n\n # Initialize current round of coordinate descent to w found in last round\n (w_new, b) = lasso_coordinate_descent(X, y, w_init=prev_w, lam=current_lam, delta=delta)\n W = np.concatenate((W, np.expand_dims(w_new, axis=1)), axis=1)\n prev_w = np.copy(w_new)\n\nplt.figure(1)\nplt.semilogx(lam_vals, np.count_nonzero(W, axis=0), 'r-')\nplt.xlabel('Lambda')\nplt.ylabel('Nonzero Coefficients in w')\nplt.title('7a: Nonzero Coefficients versus Lambda')\nplt.show()\n\n# Problem 7b)\n\n# Based on the definition of w_true, only the first k entries in w are truly nonzero. To calculate the\n# FDR rate all we have to do is count the nonzero entries in the other d-k slots as incorrect\n# Here we skip the first column of W as it corresponds to the w found using lambda_max, which generates\n# a w with all zeros. To avoid division by zero, we define FDR = 0 at this point\nFDR = np.append([0], np.count_nonzero(W[k:, 1:], axis=0) / np.count_nonzero(W[:,1:], axis=0))\n\n# Based on the definition of w_true only the first k entries in w are truly nonzero.\nTPR = np.count_nonzero(W[:k, :], axis=0) / k\n\nplt.figure(2)\nplt.plot(FDR, TPR)\nplt.title('7b: False Discoveries and True Positives')\nplt.xlabel('FDR')\nplt.ylabel('TPR')\nplt.show()\n\n\n# ========================================================================================\n# Problem 8)\n\n\nimport pandas as pd\ndf_train = pd.read_table(\"data/crime-train.txt\")\ndf_test = pd.read_table(\"data/crime-test.txt\")\n\ny_train = df_train[\"ViolentCrimesPerPop\"].values\nX_train = df_train.drop(\"ViolentCrimesPerPop\", axis=1).values\ny_test = df_test[\"ViolentCrimesPerPop\"].values\nX_test = df_test.drop(\"ViolentCrimesPerPop\", axis=1).values\n\n\nlam_max = min_null_lambda(X_train, y_train)\nlam_ratio = 2 # factor to decrease lambda by after each iteration\n\ncurrent_lam = lam_max\nlam_vals = []\ndelta = 10e-5 # threshold used to determine when to stop searching for optimal w\nprev_w = None\n\n# matrix with each column the weights vector generated by the corresponding lambda\nW = None\nB = []\nwhile current_lam >= 0.01:\n\n lam_vals.append(current_lam)\n\n (w, b) = lasso_coordinate_descent(X_train, y_train, lam=current_lam, w_init=prev_w, delta=delta)\n\n if W is None:\n W = np.expand_dims(w, axis=1)\n else:\n W = np.concatenate((W, np.expand_dims(w, axis=1)), axis=1)\n\n B.append(b)\n\n prev_w = np.copy(w)\n current_lam /= lam_ratio\n\n# Part a: Number non-zero entries vs lambda\nplt.figure(3)\nplt.semilogx(lam_vals, np.count_nonzero(W, axis=0), 'r-')\nplt.xlabel('Lambda')\nplt.ylabel('Nonzero Coefficients in w')\nplt.title('8a: Nonzero coefficients vs Lambda')\n#plt.show()\n\n# Part b: Regularization Paths: agePct12t29, pctWSocSec, pctUrban, agePct65up, householdsize\n\n# find where these columns reside; - 1 to account for the fact that the first column of df_train is our response\n# variable y and thus has no associated weight\ni1 = np.where(df_train.columns == \"agePct12t29\")[0] - 1\ni2 = np.where(df_train.columns == \"pctWSocSec\")[0] - 1\ni3 = np.where(df_train.columns == \"pctUrban\")[0] - 1\ni4 = np.where(df_train.columns == \"agePct65up\")[0] - 1\ni5 = np.where(df_train.columns == \"householdsize\")[0] - 1\n\n\nk = len(lam_vals)\n\nplt.figure(4)\nplt.semilogx(lam_vals, np.reshape(W[i1, :], (k, )), \\\n lam_vals, np.reshape(W[i2, :], (k,)), \\\n lam_vals, np.reshape(W[i3, :], (k,)), \\\n lam_vals, np.reshape(W[i4, :], (k,)), \\\n lam_vals, np.reshape(W[i5, :], (k,)))\n\nplt.xlabel('Lambda')\nplt.ylabel('Coefficient Value')\nplt.title('8b: Regularization Paths')\nplt.legend([\"agePct12t29\", \"pctWSocSec\", \"pctUrban\", \"agePct65up\", \"householdsize\"])\n#plt.show()\n\n# Part c: Squared Error on training/test data\n\ny_pred_train = np.dot(W.T, X_train.T) + np.expand_dims(B, axis=1)\nSSE_train = 1/X_train.shape[0] * np.sum(np.square(y_pred_train - y_train), axis=1)\ny_pred_test = np.dot(W.T, X_test.T) + np.expand_dims(B, axis=1)\nSSE_test = 1/X_test.shape[0] * np.sum(np.square(y_pred_test - y_test), axis=1)\n\nplt.figure(5)\nplt.semilogx(lam_vals, SSE_train, lam_vals, SSE_test)\nplt.legend([\"Training Error\", \"Testing Error\"])\nplt.xlabel('Lambda')\nplt.ylabel('SSE / n')\nplt.title('8c: Squared Error as a function of Lambda')\nplt.show()\n\n# Part d:\n\n(w30, _ ) = lasso_coordinate_descent(X_train, y_train, lam=30, delta=10e-5)\n\nvar_names = df_train.columns[1:] # skip the first varname corresponding to response variable ViolentCrimesPerPop\nnonzero_coeffs = {w30[i]:var_names[i] for i in range(len(w30)) if not w30[i] == 0}\nmax_coeff = max(list(nonzero_coeffs.keys()))\nmin_coeff = min(list(nonzero_coeffs.keys())) \nprint(nonzero_coeffs)\nprint(\"feature with largest coefficient: \", nonzero_coeffs[max_coeff], \" , value: \", max_coeff)\nprint(\"feature with smallest coefficient: \", nonzero_coeffs[min_coeff], \" , value: \", min_coeff)\n"} {"blob_id": "637e84e96255a9b5514621426a542b21d03909e1", "repo_name": "lxyshuai/leetcode", "path": "/287. Find the Duplicate Number.py", "length_bytes": 1588, "score": 4.0625, "int_score": 4, "content": "# coding=utf-8\n\"\"\"\nGiven an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.\n\nExample 1:\n\nInput: [1,3,4,2,2]\nOutput: 2\nExample 2:\n\nInput: [3,1,3,4,2]\nOutput: 3\nNote:\n\nYou must not modify the array (assume the array is read only).\nYou must use only constant, O(1) extra space.\nYour runtime complexity should be less than O(n2).\nThere is only one duplicate number in the array, but it could be repeated more than once.\n\"\"\"\n\n\nclass Solution(object):\n def findDuplicate(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n \"\"\"\n \u6839\u636e\u9e3d\u7b3c\u539f\u7406\uff0c\u7ed9\u5b9an + 1\u4e2a\u8303\u56f4[1, n]\u7684\u6574\u6570\uff0c\u5176\u4e2d\u4e00\u5b9a\u5b58\u5728\u6570\u5b57\u51fa\u73b0\u81f3\u5c11\u4e24\u6b21\u3002\n \u5229\u7528\u4e8c\u5206\u67e5\u627e\uff0c\u627e\u51fa\u91cd\u590d\u7684\u6570\u5b57k,\u53d6middle = left + (right - left) / 2\u4e3a\u679a\u4e3e\u3002\n \u904d\u5386\u6570\u7ec4\uff0c\u5982\u679c\u6570\u7ec4\u4e2d\u5c0f\u4e8e\u7b49\u4e8emiddle\u7684\u6570\u91cf\u5927\u4e8emiddle,\u5219\u53ef\u4ee5\u786e\u5b9a[1, middle]\u8303\u56f4\u5185\u4e00\u5b9a\u6709\u89e3,\u5426\u5219\u53ef\u4ee5\u786e\u5b9a\u89e3\u843d\u5728(n / 2, n]\u8303\u56f4\u5185\n \"\"\"\n left = 1\n right = len(nums) - 1\n while left <= right:\n middle = left + (right - left) / 2\n count = 0\n for number in nums:\n if number <= middle:\n count += 1\n if count > middle:\n right = middle - 1\n else:\n left = middle + 1\n return left\n\nif __name__ == '__main__':\n print Solution().findDuplicate([1,2,3,3])"} {"blob_id": "560dc58495a63bf01ea6b2e6f018446abea64990", "repo_name": "echowuzangye/cs61a_code", "path": "/mt2/q1/q1.py", "length_bytes": 5799, "score": 4.375, "int_score": 4, "content": "email = 'example_key'\n\n\"\"\"This question involves plucking the leaves off a tree one by one.\n\nDefinitions:\n\n1) A \"number tree\" is a Tree whose labels are _unique_ positive integers.\n No repeated labels appear in a number tree.\n\n2) A \"plucking order\" for a number tree t is a sequence of unique positive\n integers that are all labels of t.\n\n3) A plucking order is \"valid\" if both of these conditions are true:\n (a) the plucking order contains all labels of t, and\n (b) in the plucking order, the label for each node of t appears after\n the labels of all its descendant nodes. Thus, leaves appear first.\n\nNote: redwood, pine, and cyprus are all kinds of trees.\n\"\"\"\n\n\"\"\"A: (3 pts) Implement order, which takes a number tree called redwood. It returns\na valid plucking order as a list of numbers. If there is more than one valid\nplucking order for redwood, your order function can return any one of them.\n\nIMPORTANT: You do not need to return EVERY valid plucking order; just one.\n\nCheck the doctests with: python3 ok -q a\n\"\"\"\ndef order(redwood):\n \"\"\"Return a list containing a valid plucking order for the labels of t.\n\n >>> order(Tree(1, [Tree(2, [Tree(3, [Tree(4)])])])) # The only valid plucking order.\n [4, 3, 2, 1]\n >>> order(Tree(1, [Tree(2), Tree(3)])) in [[2, 3, 1], [3, 2, 1]] # There are 2 valid orders.\n True\n >>> o = order(Tree(1, [Tree(2, [Tree(3)]), Tree(4, [Tree(5)])])) # There are many valid orders,\n >>> o.index(5) < o.index(4) # but all have 5 before 4,\n True\n >>> o.index(3) < o.index(2) # and 3 before 2,\n True\n >>> o[4:] # and 1 at the end.\n [1]\n\n >>> order(Tree(7, [Tree(4, [Tree(6)]), Tree(5)])) in [[6, 5, 4, 7], [5, 6, 4, 7], [6, 4, 5, 7]]\n True\n \"\"\"\n plucking_order = []\n for b in redwood.branches:\n plucking_order.extend(order(b))\n return plucking_order + [redwood.label]\n\n\n\"\"\"B: (5 pts) Implement pluck, which takes a number tree called pine and returns\na function that is called repeatedly on the elements of a plucking order. If that\nplucking order is valid, the final call returns 'success!'. Otherwise, if one of\nthe repeated calls is on a number that is not part of a valid plucking order, the\nerror string 'Hey, not valid!' is returned.\n\nSince pine is a number tree and the values passed to plucker form a plucking\norder, you can assume that:\n- The labels of pine are unique,\n- All values k passed to the plucker function are unique for a given pine, and\n- All values k are labels of pine.\n\nCheck the doctests with: python3 ok -q b\n\"\"\"\ndef pluck(pine):\n \"\"\"Return a function that returns whether a plucking order is valid\n for a number tree t when called repeatedly on elements of a plucking order.\n\n Calling the function returned by pluck should not mutate pine.\n\n +---+\n | 1 |\n +---+\n / \\---- / +---+ +---+\n | 2 | | 6 |\n +---+ +---+\n | / | / +---+ +---+ +---+\n | 3 | | 7 | | 8 |\n +---+ +---+ +---+\n / \\ |\n / \\ |\n +---+ +---+ +---+\n | 4 | | 5 | | 9 |\n +---+ +---+ +---+\n\n >>> b0 = Tree(2, [Tree(3, [Tree(4), Tree(5)])])\n >>> b1 = Tree(6, [Tree(7), Tree(8, [Tree(9)])])\n >>> t = Tree(1, [b0, b1])\n >>> pluck(t)(9)(8)(7)(6)(5)(4)(3)(2)(1)\n 'success!'\n >>> pluck(t)(5)(9)(4)(7)(3)(8)(6)(2)(1)\n 'success!'\n >>> pluck(t)(2)\n 'Hey, not valid!'\n >>> pluck(t)(5)(9)(7)(6)\n 'Hey, not valid!'\n\n >>> pluck(b0)(5)(2)\n 'Hey, not valid!'\n >>> pluck(b0)(4)(5)(3)(2)\n 'success!'\n \"\"\"\n def plucker(k):\n def pluck_one_leaf(cyprus):\n \"\"\"Return a copy of cyprus without leaf k and check that k is a\n leaf label, not an interior node label.\n \"\"\"\n if not cyprus.is_leaf() and cyprus.label == k:\n return 'Hey, not valid!'\n plucked_branches = []\n for b in cyprus.branches:\n skip_this_leaf = b.is_leaf() and b.label == k\n if not skip_this_leaf:\n plucked_branch_or_error = pluck_one_leaf(b)\n if isinstance(plucked_branch_or_error, str):\n return plucked_branch_or_error\n else:\n plucked_branches.append(plucked_branch_or_error)\n return Tree(cyprus.label, plucked_branches)\n nonlocal pine\n if pine.is_leaf():\n assert k == pine.label, 'all k must appear in pine'\n return 'success!'\n pine = pluck_one_leaf(pine)\n if isinstance(pine, str):\n return pine\n return plucker\n return plucker\n\n##############################\n# NO FURTHER QUESTIONS BELOW #\n##############################\n\nclass Tree:\n \"\"\"A tree is a label and a list of branches.\"\"\"\n def __init__(self, label, branches=[]):\n self.label = label\n for branch in branches:\n assert isinstance(branch, Tree)\n self.branches = list(branches)\n\n def __repr__(self):\n if self.branches:\n branch_str = ', ' + repr(self.branches)\n else:\n branch_str = ''\n return 'Tree({0}{1})'.format(repr(self.label), branch_str)\n\n def __str__(self):\n return '\\n'.join(self.indented())\n\n def indented(self):\n lines = []\n for b in self.branches:\n for line in b.indented():\n lines.append(' ' + line)\n return [str(self.label)] + lines\n\n def is_leaf(self):\n return not self.branches\n"} {"blob_id": "8bacef639ebf69938ec3fb0d5f266cc018df0b35", "repo_name": "ali-hussain/project-euler", "path": "/problem18.py", "length_bytes": 2971, "score": 3.546875, "int_score": 4, "content": "#!/usr/bin/env python3\n'''\nBy starting at the top of the triangle below and moving to adjacent numbers on\nthe row below, the maximum total from top to bottom is 23.\n\n3\n7 4\n2 4 6\n8 5 9 3\n\nThat is, 3 + 7 + 4 + 9 = 23.\n\nFind the maximum total from top to bottom of the triangle below:\n\n75\n95 64\n17 47 82\n18 35 87 10\n20 04 82 47 65\n19 01 23 75 03 34\n88 02 77 73 07 63 67\n99 65 04 28 06 16 70 92\n41 41 26 56 83 40 80 70 33\n41 48 72 33 47 32 37 16 94 29\n53 71 44 65 25 43 91 52 97 51 14\n70 11 33 28 77 73 17 78 39 68 17 57\n91 71 52 38 17 14 91 43 58 50 27 29 48\n63 66 04 68 89 53 67 30 73 16 69 87 40 31\n04 62 98 27 23 09 70 98 73 93 38 53 60 04 23\n\nNOTE: As there are only 16384 routes, it is possible to solve this problem by\ntrying every route. However, Problem 67, is the same challenge with a triangle\ncontaining one-hundred rows; it cannot be solved by brute force, and requires a\nclever method! ;o)\n\n'''\n\nimport logging\nimport argparse\nfrom EulerLibrary import Utilities\n\ndef arguments(parser):\n parser.add_argument('--input_file','-i',type=str,default='resources/problem18.txt',\n help='Input file with pyramid')\n\nclass PyramidMaxPathFinder:\n def __init__(self,file_name):\n self._parse_input_file(file_name)\n self._find_max_path()\n def _parse_input_file(self,file_name):\n input_file = open(file_name,'r')\n row_strings = [x.replace('\\n','') for x in input_file.readlines()]\n self._pyramid = [[int(y) for y in x.split()] for x in row_strings]\n # print('Parsed pyramid:')\n # PyramidMaxPathFinder._print_pyramid(self._pyramid)\n def _find_max_path(self):\n self._max_subpath_pyramid = [[]]*len(self._pyramid)\n # Leaf node values themselves are the max path\n self._max_subpath_pyramid[-1]=self._pyramid[-1]\n # For all other rows the max path self + greater of the two reachable values\n for row in reversed(range(0,len(self._pyramid)-1)):\n max_row = []\n for column in range(0,len(self._pyramid[row])):\n max_subpath = self._pyramid[row][column]+max(\n self._max_subpath_pyramid[row+1][column],\n self._max_subpath_pyramid[row+1][column+1])\n max_row.append(max_subpath)\n self._max_subpath_pyramid[row]=max_row\n # print('Max subpaths calculated:')\n # PyramidMaxPathFinder._print_pyramid(self._max_subpath_pyramid)\n @staticmethod\n def _print_pyramid(pyramid):\n top_string = str(pyramid[0][0])\n for row in pyramid:\n for value in row:\n print('{0:{1}}'.format(value,len(top_string)),end=' ')\n print('')\n def get_max_path(self):\n return self._max_subpath_pyramid[0][0]\n\nif __name__ == '__main__':\n PARSED_ARGS = Utilities.initialize(arguments)\n finder = PyramidMaxPathFinder(PARSED_ARGS.input_file)\n print('Calculated max path {}'.format(finder.get_max_path()))\n"} {"blob_id": "78b65f5b6b72fd30e264ca0352c283f2d95fe932", "repo_name": "fjrleao/criptaritmetica-genetico", "path": "/ag.py", "length_bytes": 10861, "score": 3.609375, "int_score": 4, "content": "# -*- coding: utf-8 \n# TRABALHO DE INTELIGENCIA ARTIFICIAL\n# DOUGLAS FELIPE MUNARO E F\u00c1BIO JUNIOR\n\nfrom collections import OrderedDict\nimport argparse\nimport random\n\n#python3 ag.py -i SEND+MORE=MONEY -p 100 -g 100 -c 60 -m 2 -t 0 -s 2 -a 1\n\n#Fun\u00e7ao principal\ndef main():\n\tgeracoes = 0\n\tachou = 0\n\tpopulacao = []\n\tparseArg()\n\tretiraRepetidas()\n\tpopulacaoInicial = geraPopulacaoIni()\n\tavalia1 = avaliacao(populacaoInicial, metAvaliacao)\n\tfor i in range(0, len(avalia1)):\n\t\tif avalia1[i] == 0:\n\t\t\tachou = 1\n\t\t\tprint(\"ACHOU O RESULTADO\")\n\t\t\tprint('[1 ', populacaoIni[i],']')\n\t\t\texit(0)\n\n\tpopulacao = populacaoInicial\n\t\n\twhile geracoes < numGeracoes:\n\t\tpopulacao = crossover(populacao)\n\t\tpopulacao = mutacao(populacao)\n\t\tavalia1 = avaliacao(individuos, metAvaliacao)\n\t\texclui_piores(avalia1)\n\n\t\tpopulacao = individuos\n\t\tfor j in range(0, len(avalia1)):\n\t\t\tprint(str(avalia1[j]) + ' -- ' + str(individuos[j]))\n\t\t\tif avalia1[j] == 0:\n\t\t\t\tachou = 1\n\t\t\t\tprint(\"ACHOU O RESULTADO\")\n\t\t\t\tprint('[ '+ str(geracoes)+ ' ' + str(individuos[j]) + ' ]')\n\t\t\t\texit(0)\n\t\tgeracoes += 1\n\t\tprint(geracoes)\n\t\t# print(\"geracoes: \" +str(geracoes))\n\n\t\t\n\t\n#Fun\u00e7ao para manipula\u00e7ao dos argumentos\ndef parseArg():\n \n # construct the argument parser and parse the arguments\n ap = argparse.ArgumentParser(description=\"Criptoartimetica\")\n ap.add_argument(\"-i\", \"--input\", required=True, help=\"Express\u00e3o a ser avaliada\")\n ap.add_argument(\"-p\", \"--populacao\", required=True, help=\"Popula\u00e7\u00e3o Inicial\")\n ap.add_argument(\"-g\", \"--geracao\", required=True, help=\"N\u00famero de Gera\u00e7\u00f5es\")\n ap.add_argument(\"-c\", \"--crossover\", required=True, help=\"Taxa de Crossover\")\n ap.add_argument(\"-m\", \"--mutacao\", required=True, help=\"Taxa de Muta\u00e7\u00e3o\")\n ap.add_argument(\"-t\", \"--torneio\", required=True, help=\"N\u00famero de Torneio --> '0' se metodo de sele\u00e7\u00e3o n\u00e3o for torneio\")\n ap.add_argument(\"-s\", \"--selecao\", required=True, help=\"M\u00e9todo de Sele\u00e7\u00e3o\")\n ap.add_argument(\"-a\", \"--avaliacao\", required=True, help=\"M\u00e9todo de Avalia\u00e7\u00e3o\")\n args = ap.parse_args()\n\n #variaveis que irao receber o conteudo dos argumentos\n global exp #recebera o input inicialmente\n global populacaoQtd #quantidade da popula\u00e7ao\n global numGeracoes #numero de gera\u00e7oes \n global taxaCrossover #taxa de crossover \n global taxaMutacao #taxa de muta\u00e7ao\n global numTorneio #numero de torneio\n global metSelecao #metodo de sele\u00e7ao\n global metAvaliacao #metodo de avalia\u00e7ao\n exp = args.input\n populacaoQtd = int(args.populacao)\n numGeracoes = int(args.geracao)\n taxaCrossover = int(args.crossover)\n taxaMutacao = int(args.mutacao)\n numTorneio = int(args.torneio)\n metSelecao = int(args.selecao)\n metAvaliacao = int(args.avaliacao)\n\n\n#Fun\u00e7ao para retirar letras repetidas da expressao\ndef retiraRepetidas():\n\n\tglobal exp #expressao apenas com letras minusculas\n\tglobal expLimpa #expressao com letras minusculas e sem sinais de '+' e '='\n\tglobal manipulaExp #recebera o input depois de serem eliminados o sinal de '+' e '=' e eleminados todos os caracteres repetidos\n \n\texp = exp.lower()\n\texpLimpa = exp\n\texpLimpa = expLimpa.replace('+',\"\")\n\texpLimpa = expLimpa.replace('=',\"\")\n\tmanipulaExp = list(OrderedDict.fromkeys(expLimpa))\n\n\n#Fun\u00e7ao para gerar popula\u00e7ao inicial\ndef geraPopulacaoIni():\n\n\tglobal populacaoIni #lista que recebera a popula\u00e7ao inicial\n\tpopulacaoIni = []\n\tglobal individuos\n\tindividuos = []\n\tglobal manipulaExp\n\tdicionario = {}\n\tfor i in range(int(populacaoQtd)):\n\t\tresult = random.sample(range(0,9), len(manipulaExp))\n\t\tif str(result) in dicionario:\n\t\t\tprint(\"INDIVIDUO DUPLICADO\")\n\t\telse:\n\t\t\tdicionario[str(result)] = 1\t\t\t\n\t\t\tpopulacaoIni.append(result)\n\n\t\t\n\t\t\n\t\t#print(populacaoIni[i])\n\t\t#print(i)\n\t\t#print(\"\\n\")\n\t\n\tindividuos = populacaoIni\n\treturn populacaoIni\n\n#Funcao de avalia\u00e7ao\n#metAvaliacao = 1 --> Diferen\u00e7a entre a soma desejada e a soma real no valor total\n#metAvaliacao = 2 --> Soma das diferen\u00e7as entre a soma desejada e a soma real d\u00edgito a d\u00edgito\n#metAvaliacao = 3 --> Produto das diferen\u00e7as entre a soma desejada e a soma real d\u00edgito a d\u00edgito\ndef avaliacao(pop, avaliacao):\n\n\tauxExp = \"\" #auxExp sera usada para dividir os valores da expressao para poder ser feito a soma\n\taux1 = \"\" #aux1 sera utilizada para receber o valor antes do sinal de '+'\n\taux2 = \"\" #aux2 sera utilizada para receber o valor depois do sinal de '+'\n\tlistaAvaliacao = []\n\tlistaAvaliacao.clear()\n\n\tif avaliacao == 1:\n\n\t\tfor k in range(0, len(pop)):\n\t\t\tauxExp = \"\"\n\t\t\tlistaAux = pop[k]\n\t\t\tfor i in range(0, len(exp)):\n\t\t\t\tfor j in range(0, len(manipulaExp)):\n\t\t\t\t\tif exp[i] == manipulaExp[j]:\n\t\t\t\t\t\tauxExp = auxExp + str(listaAux[j])\n\n\t\t\t\tif exp[i] == '+':\n\t\t\t\t\taux1 = auxExp\n\t\t\t\t\tauxExp = \"\"\n\t\t\t\tif exp[i] == '=':\n\t\t\t\t\taux2 = auxExp\n\t\t\t\t\tauxExp = \"\"\n\t\t\t\t\tsomaDesejada = int(aux1) + int(aux2) #somaDesejada recebe a soma de aux1 + aux2\n\n\t\t\t\tif i == int(len(exp))-1:\n\t\t\t\t\tsomaReal = int(auxExp) #somaReal recebe auxExp pois sera o valor que ira sobrar depois da manipula\u00e7ao e \u00e9 justamente o valor da soma real\n\t\t\t\t\tdiferenca = abs(somaDesejada -somaReal)\n\t\t\t\t\tlistaAvaliacao.append(diferenca)\n\t\t\t\t\t\n\t\treturn listaAvaliacao\n\n\tif avaliacao == 2:\n\n\t\tfor k in range(0, len(pop)):\n\t\t\tauxExp = \"\"\n\t\t\tlistaAux = pop[k]\n\t\t\tfor i in range(0, len(exp)):\n\t\t\t\tfor j in range(0, len(manipulaExp)):\n\t\t\t\t\tif exp[i] == manipulaExp[j]:\n\t\t\t\t\t\tauxExp = auxExp + str(listaAux[j])\n\n\t\t\t\tif exp[i] == '+':\n\t\t\t\t\taux1 = auxExp\n\t\t\t\t\tauxExp = \"\"\n\t\t\t\tif exp[i] == '=':\n\t\t\t\t\taux2 = auxExp\n\t\t\t\t\tauxExp = \"\"\n\t\t\t\t\tsomaDesejada = int(aux1) + int(aux2) #somaDesejada recebe a soma de aux1 + aux2\n\n\t\t\t\tif i == int(len(exp))-1:\n\t\t\t\t\tsomaReal = int(auxExp) #somaReal recebe auxExp pois sera o valor que ira sobrar depois da manipula\u00e7ao e \u00e9 justamente o valor da soma real\n\t\t\t\t\tdiferenca = abs(somaDesejada -somaReal)\n\t\t\t\t\tdiferenca = somarDigitos(diferenca)\n\t\t\t\t\tlistaAvaliacao.append(diferenca)\n\t\t\t\t\t\n\t\treturn listaAvaliacao\n\n\tif avaliacao == 3:\n\n\t\tfor k in range(len(pop)):\n\t\t\tauxExp = \"\"\n\t\t\tlistaAux = pop[k]\n\t\t\tfor i in range(len(exp)):\n\t\t\t\tfor j in range(len(manipulaExp)):\n\t\t\t\t\tif exp[i] == manipulaExp[j]:\n\t\t\t\t\t\tauxExp = auxExp + str(listaAux[j])\n\n\t\t\t\tif exp[i] == '+':\n\t\t\t\t\taux1 = auxExp\n\t\t\t\t\tauxExp = \"\"\n\t\t\t\tif exp[i] == '=':\n\t\t\t\t\taux2 = auxExp\n\t\t\t\t\tauxExp = \"\"\n\t\t\t\t\tsomaDesejada = int(aux1) + int(aux2) #somaDesejada recebe a soma de aux1 + aux2\n\n\t\t\t\tif i == int(len(exp))-1:\n\t\t\t\t\tsomaReal = int(auxExp) #somaReal recebe auxExp pois sera o valor que ira sobrar depois da manipula\u00e7ao e \u00e9 justamente o valor da soma real\n\t\t\t\t\tdiferenca = abs(somaDesejada -somaReal)\n\t\t\t\t\tdiferenca = multDigitos(diferenca)\n\t\t\t\t\tlistaAvaliacao.append(diferenca)\n\t\t\t\t\t\n\t\treturn listaAvaliacao\n\t\t\t\t\t\t\n\ndef roleta(pop):\n\n\tresultados_invertidos = []\n\tresultados_invertidos = [-1] * len(pop)\n\tvetor_intervalos = []\n\tvetor_intervalos = [-1] * len(pop)\n\tvetor = []\n\tvetor = [-1] * len(pop)\n\tresultado = 0\n\ttotal_valores = 0\n\tvetor = avaliacao(pop, metAvaliacao)\n\t# print(vetor)\n\t\n\tfor k in range(0, len(pop)):\n\t\ttry:\n\t\t\taux_roleta = float( 1/ vetor[k] )\n\t\texcept:\n\t\t\taux_roleta = 0\n\t\t\tprint(\"ACHOU O RESULTADO: \" +str(individuos[k]))\n\t\t\texit(0)\n\t\tresultados_invertidos[k] = round(aux_roleta,2)\n\t\n\t# coloca os valores obtidos na avalia\u00e7\u00e3o dentro do vetor\n\tfor i in range(0, len(pop)):\t\t\n\t\ttotal_valores = total_valores + resultados_invertidos[i]\n\t\tvetor_intervalos[i] = total_valores\n\t\n\troleta = random.uniform(1,total_valores)\n\n\tfor i in range(0, len(pop)):\n\t\tif roleta >= vetor_intervalos[i] and roleta <= vetor_intervalos[i+1]: \n\t\t\tresultado = i\n\t\t\tbreak\n\n\tresultados_invertidos.clear()\n\tvetor_intervalos.clear()\n\tvetor.clear()\n\t\n\treturn individuos[resultado]\n\ndef torneio_de_3(pop, taxa_torneio):\n\tposicao = 0\n\tfinalistas = []\n\tfinalistas = [-1] * len(pop)\n\ttorneio = []\n\ttorneio = [-1] * len(pop)\n\tvetor = avaliacao(pop, metAvaliacao)\n\ttotal_valores = 0\n\tfor j in range(0, taxa_torneio):\n\t\tfor i in range(0, taxa_torneio):\n\t\t\tvalor = random.randint(1, len(vetor)-1)\n\t\t\ttorneio[i] = vetor[valor]\n\n\t\tmelhor = torneio[0]\n\t\tfor i in range(0, taxa_torneio):\n\t\t\tif(melhor > torneio[i] ):\n\t\t\t\tmelhor = torneio[i]\n\t\tfinalistas.append(melhor)\t\n\n\tresultado = finalistas[0]\n\tfor i in range(0, len(finalistas)):\n\t\t\tif(resultado > finalistas[i]):\n\t\t\t\tresultado = finalistas[i]\n\n\tfor k in range(0, len(vetor)):\n\t\tif ( vetor[k] == resultado):\n\t\t\tposicao = k\t\n\t\t\tbreak\n\n\treturn individuos[posicao]\t\t\n\n\ndef crossover(pop):\n\n\tpai1 = []\n\tpai1 = [-1] * len(pop)\n\tpai2 = []\n\tpai2 = [-1] * len(pop)\n\tfilho1 = []\n\tfilho2 = []\n\n\ttaxa = 0\n\ttaxa = int((( len(individuos) * taxaCrossover) / 100) / 2)\n\n\t# for para trocar de posi\u00e7\u00f5es\n\tfor k in range(0, taxa):\t\n\t\tpai1 = roleta(pop)\n\t\tpai2 = roleta(pop)\n\t\twhile pai1 == pai2:\n\t\t\tpai2 = roleta(pop)\n\n\t\tponto1 = random.randint(1, len(pai1)-2)\n\t\tponto2 = random.randint(1, len(pai1)-2) \n\t\tif ponto2 < ponto1:\n\t\t\taux = ponto1\t\t\t\n\t\t\tponto1 = ponto2\n\t\t\tponto2 = ponto1\n\t\n\t\twhile ( ponto2 - ponto1) < 2 or (ponto2 - ponto1) > 3:\n\t\t\tponto1 = random.randint(1, len(pai1)-2)\n\t\t\tponto2 = random.randint(1, len(pai1)-2)\n\t\t\n\t\t# print(\"Ponto1: \" +str(ponto1))\n\t\t# print(\"Ponto2: \" +str(ponto2))\n\n\t\tfilho1 = list(pai1)\n\t\tfilho2 = list(pai2)\n\t\t# print(\"PAI: \" +str(filho1))\n\t\t# print(\"PAI 2: \" +str(filho2))\n\t\t# print(filho1[ponto1:ponto2])\n\t\t# print(filho2[ponto1:ponto2])\n\t\tfilho1[ponto1:ponto2] = pai2[ponto1:ponto2]\n\t\tfilho2[ponto1:ponto2] = pai1[ponto1:ponto2]\n\t\t\n\t\t# for para fazer as mudan\u00e7as, para n\u00e3o existir valores repetidos\n\t\tfor k in range(0, len(filho1)):\n\t\t\tif(k < ponto1 or k >= ponto2):\n\t\t\t\tm = ponto1 \n\t\t\t\twhile(m < ponto2):\n\t\t\t\t\tif(filho1[k] == filho1[m]):\n\t\t\t\t\t\tfilho1[k] = filho2[m]\n\t\t\t\t\t\tm = ponto1\n\t\t\t\t\telse:\n\t\t\t\t\t\tm += 1\n\n\t\tfor r in range(0, len(filho2)):\n\t\t\tif(r < ponto1 or r >= ponto2):\n\t\t\t\to = ponto1\n\t\t\t\twhile(o < ponto2):\n\t\t\t\t\tif(filho2[r] == filho2[o]):\n\t\t\t\t\t\tfilho2[r] = filho1[o]\n\t\t\t\t\t\to = ponto1\n\t\t\t\t\telse:\n\t\t\t\t\t\to += 1\n\t\t# print(filho1)\n\t\t# print(filho2)\n\t\tindividuos.append(filho1)\n\t\tindividuos.append(filho2)\n\ndef mutacao(pop):\t\n\ttaxa = ( len(individuos) * taxaMutacao) / 100\n\tfor i in range (0, int(taxa)):\t\n\t\tinicio = len(individuos) - int((len(individuos) * taxaMutacao) / 100) / 2\n\t\t\n\t\tindice_filho = random.randint(int(inicio), len(individuos)-1)\n\t\t\n\t\tfilho = individuos[indice_filho]\n\t\tindice1 = random.randint(0, len(filho)-1)\n\t\tindice2 = random.randint(0, len(filho)-1)\n\t\n\t\taux = filho[indice1]\n\t\tfilho[indice1] = filho[indice2]\n\t\tfilho[indice2] = aux\n\t\t\n\t\tindividuos[indice_filho] = filho\n\ndef exclui_piores(avalia1):\n\tfor i in range(0, len(avalia1)-100):\n\t\tpior = max(avalia1)\n\t\tpos = avalia1.index(pior)\n\t\tdel avalia1[pos]\n\t\tdel individuos[pos]\n\t\n\n\ndef somarDigitos(n):\n s = 0\n while n:\n s += n % 10\n n //= 10 \n return s\n\ndef multDigitos(n):\n\ts = 1\n\twhile n:\n\t\taux = n % 10\n\t\tif aux == 0:\n\t\t\ts *= 1\n\t\t\tn //= 10\n\t\telse:\n\t\t\ts *= aux\n\t\t\tn //= 10\n\treturn s\n\n\n\nif __name__ == \"__main__\":\n\tmain()\n"} {"blob_id": "ea812806aa4961cee69f99abb94550cc909fbcd0", "repo_name": "onlinekof2001/python_data_analyzed", "path": "/Python_Prime_Cal.py", "length_bytes": 3753, "score": 4.125, "int_score": 4, "content": "'''\n4 ways to get the primes t\nprime is a series of integer numbers large than 1 and can only divisible by 1 and itself.\n'''\n# \u7a77\u4e3e\u6cd5, \u53d62\u5230n\u4e2a\u6570, \u80fd\u88ab2\u5230n - 1\u6574\u9664\u7684\u90fd\u88ab\u6392\u9664\u5728\u5916 range(start, stop[, step]), \u4e0d\u5305\u542bstop\n\nclass Calculator(object):\n def prime(self, n):\n m = 0\n for i in range(2, n):\n j = 2\n for j in range(2, i-1):\n if i % j == 0:\n break\n else:\n print(i, \"is prime\")\n m += 1\n return m\n\nobj = Calculator();\nobj.prime(20)\n\n# \u7a77\u4e3e\u6cd5, \u53d6\u9664\u6570\u7684\u4e00\u534a print(int(11/2)), \u56e0\u4e3a\u4efb\u4f55\u6570\u7531\u4e24\u4e2a\u56e0\u6570\u76f8\u4e58\u5f97\u6765\u7684, \u5982\uff1a15, 1*15, 3*5. \u53ef\u4ee5\u770b\u5230\u6709\u4e00\u534a\u7684\u56e0\u6570\u843d\u572815/2\u7684\u524d\u9762\n\nclass Calculator(object):\n def prime(self, n):\n m = 0\n for i in range(2, n):\n j = 2\n for j in range(2, int(i/2)+1):\n if i % j == 0:\n break\n else:\n print(i, \"is prime\")\n m += 1\n return m\n\n# \u518d\u6b21\u53d8\u5f62, \u4efb\u4f55\u6570\u7684\u56e0\u6570\u5fc5\u6709\u4e00\u4e2a\u5c0f\u4e8e\u221ax\u548c\u4e00\u4e2a\u5927\u4e8e\u221ax\u7684\u5b58\u5728, \u5982\uff1a\u221a81=9, 1*81, 3*27, 9*9\n\nclass Calculator(object):\n def prime(self, n):\n m = 0\n for i in range(2, n):\n j = 2\n for j in range(2, int(i**0.5)+1):\n if i % j == 0:\n break\n else:\n print(i, \"is prime\")\n m += 1\n return m\n\n#\u5bf9\u4e8e\u4efb\u610f\u4e00\u4e2a\u5927\u4e8e3\u7684\u5408\u6570\uff08\u9664\u4e861\u548c\u81ea\u8eab\u5916\uff0c\u8fd8\u80fd\u88ab\u5176\u4ed6\u6574\u6570\u6574\u9664\u7684\u6570\uff09, \u6211\u4eec\u90fd\u53ef\u4ee5\u5c06\u5176\u62c6\u5206\u6210\u81f3\u5c11\u5305\u542b\u4e00\u4e2a\u8d28\u6570\u7684\u56e0\u5b50\u76f8\u4e58, \u4f8b\u5982\uff1a20=2*10\uff082\u662f\u8d28\u6570\uff09; 45=5*9; \n#\u5229\u7528\u6b64\u70b9\uff0c\u6211\u4eec\u53ef\u4ee5\u91c7\u7528\u904d\u5386\u5c0f\u4e8e\u8fd9\u4e2a\u6570\u7684\u6240\u6709\u8d28\u6570\u6765\u786e\u8ba4\u8fd9\u4e2a\u6570\u662f\u4e0d\u662f\u8d28\u6570\u3002\n\nclass Calculator(object):\n def prime(self, n):\n if n <= 2:\n return 0\n else:\n prime_list = list()\n prime_list.append(2) # \u5148\u5c062\u52a0\u5165\u5230\u8981\u904d\u5386\u7684\u5217\u8868\u4e2d\n for x in range(3, n):\n y = False \n for y in prime_list:\n if x % y == 0: # \u5bf9\u5c0f\u4e8en\u7684x\u8fdb\u884c\u904d\u5386\uff0c\u5f53\u67d0\u4e2a\u6570\u6574\u9664\u4e3a0\u65f6\uff0c\u4e0d\u6267\u884c\u6dfb\u52a0\u5217\u8868\u64cd\u4f5c\n y = False\n break\n else:\n y = True\n if y is True:\n prime_list.append(x) # \u5bf9\u5c0f\u4e8ex\u7684\u8d28\u6570\u8fdb\u884c\u904d\u5386\u540e\uff0c\u6ca1\u6709\u80fd\u6574\u9664\u7684\u8d28\u6570\uff0c\u5219\u8fd9\u4e2a\u6570\u4e5f\u662f\u8d28\u6570\n return len(prime_list)\n\n'''\n\u57c3\u62c9\u6258\u65af\u7279\u5c3c\u7b5b\u6cd5\uff1b\u4f7f\u7528\u7684\u539f\u7406\u662f\u4ece2\u5f00\u59cb\uff0c\u5c06\u6bcf\u4e2a\u7d20\u6570\u7684\u5404\u4e2a\u500d\u6570\uff0c\u6807\u8bb0\u6210\u5408\u6570\u3002\u4e00\u4e2a\u7d20\u6570\u7684\u5404\u4e2a\u500d\u6570\uff0c\u662f\u4e00\u4e2a\u5dee\u4e3a\u6b64\u7d20\u6570\u672c\u8eab\u7684\u7b49\u5dee\u6570\u5217\u3002\u6b64\u4e3a\u8fd9\u4e2a\u7b5b\u6cd5\u548c\u8bd5\u9664\u6cd5\u4e0d\u540c\u7684\u5173\u952e\u4e4b\u5904\uff0c\u540e\u8005\u662f\u4ee5\u7d20\u6570\u6765\u6d4b\u8bd5\u6bcf\u4e2a\u5f85\u6d4b\u6570\u80fd\u5426\u88ab\u6574\u9664\u3002(\u6458\u81ea\u7ef4\u57fa\u767e\u79d1)\n\n\u5177\u4f53\u7684\u5b9e\u73b0\u65b9\u5f0f\uff1a\n\n\u00a0 \u00a0 \u00a0 \u00a0 \u5148\u7559\u4e0b\u7b2c\u4e00\u4e2a\u7d20\u65702\uff0c\u5c06\u6240\u67092\u7684\u500d\u6570\u7684\u5408\u6570\u5168\u90e8\u5254\u9664\uff1b\u4e0b\u4e00\u4e2a\u7d20\u65703\uff0c\u5c063\u7684\u500d\u6570\u7684\u6240\u6709\u5408\u6570\u5168\u90e8\u5254\u9664\uff1b\u63a5\u7740\u75285\u8fdb\u884c\u7b5b\u9009\u5254\u9664\uff1b\u5f53\u6240\u8981\u4f7f\u7528\u7684\u7d20\u6570\u7684\u5e73\u65b9\u5927\u4e8e\u8bbe\u5b9a\u503c\u65f6\uff0c\u505c\u6b62\u7b5b\u9009\uff0c\u5219\u5269\u4e0b\u7684\u6240\u6709\u6570\u5747\u4e3a\u7d20\u6570\u3002\n\n\u4f8b\u5982\uff1a\u6c42\u51fa\u5c0f\u4e8e120\u7684\u6240\u6709\u7d20\u6570\uff0c\u4f9d\u6b21\u4f7f\u75282,3,5,7\u8fdb\u884c\u7b5b\u9009\uff0c\u5f53\u523011\u65f6\uff0c11*11>120,\u505c\u6b62\u7b5b\u9009\uff0c\u5269\u4f59\u6570\u5373\u4e3a\u8d28\u6570\u3002\n'''\nclass Calculator(object):\n def prime(self, n):\n if n <= 2:\n return 0\n is_right = [True] * n\n is_right[1] = False\n for i in range(2, int(n ** 0.5) + 1):\n if is_right[i]:\n for j in range(i * i, n, i):\n is_right[j] = False\n m = 0\n for x in range(2, n):\n if is_right[x]:\n m += 1\n return m"} {"blob_id": "8f06148244370885e21319b816d262bca61dddf1", "repo_name": "odlomax/py_lib", "path": "/maths/points/separations.py", "length_bytes": 1171, "score": 3.8125, "int_score": 4, "content": "import numpy as np\nfrom scipy import spatial\n\ndef mean_separation(r):\n \n \"\"\"\n Function: calculates the mean separation between points in a reasonably memory-efficient way\n \n Arguments\n ---------\n r[:,:]: float\n array of point positions [n_points:n_dim]\n \n Result\n ------\n mu_sep: float\n mean separation between points\n \n \"\"\"\n \n mu_sep=0.\n \n for i in range(r.shape[0]-2,-1,-1):\n mu_sep+=np.sum(spatial.distance.cdist(r[i+1:,:],[r[i,:]]))\n \n mu_sep/=0.5*r.shape[0]*(r.shape[0]-1)\n \n return mu_sep\n\ndef mean_squared_separation(r):\n \n \"\"\"\n Function: calculates the mean squared separation between points in a reasonably memory-efficient way\n \n Arguments\n ---------\n r[:,:]: float\n array of point positions [n_points:n_dim]\n \n Result\n ------\n mu2_sep: float\n mean squared separation between points\n \n \"\"\"\n \n mu2_sep=0.\n \n for i in range(r.shape[0]-2,-1,-1):\n mu2_sep+=np.sum(spatial.distance.cdist(r[i+1:,:],[r[i,:]],\"sqeuclidean\"))\n \n mu2_sep/=0.5*r.shape[0]*(r.shape[0]-1)\n \n return mu2_sep"} {"blob_id": "35b235e1350140df4ff37402be381a1a3405bb61", "repo_name": "bjan94/Interview-Questions", "path": "/greedy/MeetingRooms2.py", "length_bytes": 1105, "score": 3.859375, "int_score": 4, "content": "\"\"\"\nGiven an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of conference rooms required.\n\nExample 1:\n\nInput: [[0, 30],[5, 10],[15, 20]]\nOutput: 2\nExample 2:\n\nInput: [[7,10],[2,4]]\nOutput: 1\n\"\"\"\nimport heapq\n\n\nclass Interval:\n def __init__(self, s=0, e=0):\n self.start = s\n self.end = e\n\n\ndef min_meeting_rooms(intervals):\n if intervals is None or len(intervals) == 0:\n return 0\n\n intervals.sort(key=lambda i: i.start)\n\n pq = []\n res = 0\n\n for interval in intervals:\n if not pq or interval.start < pq[0]:\n res += 1\n else:\n heapq.heappop(pq)\n heapq.heappush(pq, interval.end)\n\n return len(pq)\n\n\ndef main():\n i0 = Interval(0, 30)\n i1 = Interval(5, 10)\n i2 = Interval(15, 20)\n print(min_meeting_rooms([i2, i0, i1]))\n\n i4 = Interval(7, 10)\n i5 = Interval(2, 4)\n print(min_meeting_rooms([i4, i5]))\n\n i4 = Interval(5, 10)\n i5 = Interval(6, 10)\n print(min_meeting_rooms([i4, i5]))\n\n\nif __name__ == \"__main__\":\n main()\n"} {"blob_id": "18f6d1acc3059e5d38590c37dab799240991c98a", "repo_name": "gyang274/leetcode", "path": "/src/0100-0199/0101.symmetric.bt.py", "length_bytes": 981, "score": 3.65625, "int_score": 4, "content": "from config.treenode import TreeNode, listToTreeNode\n\n\nclass Solution:\n def isSymmetric(self, root: TreeNode) -> bool:\n if root is None or (root.left is None and root.right is None):\n return True\n # stack of root left nodes, stack of root right nodes\n sl, sr = [root.left, ], [root.right, ]\n while sl or sr:\n nl, nr = sl.pop(), sr.pop()\n if nl is not None and nr is not None:\n if nl.val == nr.val:\n sl.extend((nl.right, nl.left))\n sr.extend((nr.left, nr.right))\n else:\n return False\n if (nl is None and nr is not None) or (nl is not None and nr is None):\n return False\n return True\n\n\nif __name__ == '__main__': \n solver = Solution()\n cases = [\n [1,2,2,3,4,4,3],\n [1,2,2,None,3,None,3],\n ]\n cases = [\n (listToTreeNode(x)) for x in cases\n ]\n rslts = [\n solver.isSymmetric(x) for x in cases\n ]\n for cs, rs in zip(cases, rslts):\n print(f\"case:\\n{cs.display()}, solution: {rs}\")"} {"blob_id": "434fac27ecf3a1727f0869e3564d1e77972b1860", "repo_name": "raul-bermejo/Project-Euler", "path": "/src/Problem25.py", "length_bytes": 1634, "score": 4.25, "int_score": 4, "content": "# -*- coding: utf-8 -*-\n\"\"\"\n@author: rbv\n\nProblem 22:\nThe Fibonacci sequence is defined by the recurrence relation:\n\nFn = Fn\u22121 + Fn\u22122, where F1 = 1 and F2 = 1.\nHence the first 12 terms will be:\n\nF1 = 1\nF2 = 1\nF3 = 2\nF4 = 3\nF5 = 5\nF6 = 8\nF7 = 13\nF8 = 21\nF9 = 34\nF10 = 55\nF11 = 89\nF12 = 144\nThe 12th term, F12, is the first term to contain three digits.\n\nWhat is the index of the first term in the Fibonacci sequence to contain 1000 digits?\n\"\"\"\nimport time\n\n\n# In this problem, we cannot use textbook recursion as it is far too slow for\n# large fibonacci numbers. We can use the matehmatical exponentiation, which gives\n# the following formula: F(2k) = F(k)*[2*F(k+1)-F(k)] where k is int.\ndef fast_fibo(n):\n \"Returns F(n), F(n+1) n by using mathematical exponentiation\"\n if n == 0:\n return (0,1)\n else:\n a, b = fast_fibo(n//2) # where (a,b) = (F(n//2), F(n//2 + 1))\n c = a*(2*b - a)\n d = b**2 + a**2\n if n%2 == 0:\n return (c, d)\n else:\n return (d, c+d)\n\nstart = time.time()\n\nval = True\ni = 1\nwhile val:\n f_i, _ = fast_fibo(i) # calculate the i_th fibonacci number\n # Calculate the num of digits by turning\n # into string and getting length, then have\n # statement for the length\n n_digits = len(str(f_i)) \n if n_digits >= 1000:\n val = False\n break\n # Increment index\n i += 1\n\nprint(f\"The index of the first term in the Fibonacci sequence to contain 1000 digits is {i}\")\nend = time.time()\nprint(f\"The program took {end-start:.4e} seconds to run.\")\n"} {"blob_id": "dd13199d16985eb09114b021f9a875001feb0aaa", "repo_name": "bnajafi/Scientific_Python_Assignments_POLIMI_EETBS", "path": "/Assignment 1_Deadline 26 Sept 2017/Assignment1_step2_Moretti.py", "length_bytes": 2458, "score": 3.796875, "int_score": 4, "content": "# -*- coding: utf-8 -*-\n\"\"\"\n\nEETBS 2017/2018 - Assignment 1, step 2 - Heat transfer rate through a composite wall\n\nGiorgio Moretti (10433550)\n\n\"\"\"\n\n# HEAT TRANSFER RATE THROUGH ONE UNIT OF THE WALL (length= 1 m)\n\nprint \"\\n NOW YOU WILL ENTER THE DATA FOR THE CALCULATION\"\n\nA_unit = float(raw_input(\"Enter the area of one unit of the wall in m^2 \"))\nT_in = float(raw_input(\"Enter the inner temperature in \u00b0C \"))\nT_out = float(raw_input(\"Enter the outer temperature in \u00b0C \"))\nh_in = float(raw_input(\"Enter the inner convective heat transfer coefficient in W/m^2\u00b0C \"))\nh_out = float(raw_input(\"Enter the outer convective heat transfer coefficient in W/m^2\u00b0C \"))\n\nR_in = 1/(h_in * A_unit) # inner convective resistance [\u00b0C/W]\nR_out = 1/(h_out * A_unit) # outer convective resistance [\u00b0C/W]\n\nprint \"\\n THE WALL IS MADE BY PLASTER, BRICK AND RIGID FOAM\"\n\nkb = float(raw_input(\"Enter the conductivity of the brick in W/m\u00b0C \"))\nkp = float(raw_input(\"Enter the conductivity of the plaster in W/m\u00b0C \")) \nkf = float(raw_input(\"Enter the conductivity of the foam in W/m\u00b0C \")) \n\nAf = float(raw_input(\"Enter the area of the foam in m^2 \"))\nLf = float(raw_input(\"Enter the thickness of the foam in m \"))\nRf = Lf/(kf * Af) # foam conductive resistance [\u00b0C/W]\n\nAp = float(raw_input(\"Enter the area of the side plaster in m^2 \"))\nLp = float(raw_input(\"Enter the thickness of the side plaster in m^2 \"))\nRp = Lp/(kp * Ap) # side plaster conductive resistance [\u00b0C/W]\n\nApc = float(raw_input(\"Enter the area of the center plaster in m^2 \"))\nLpc = float(raw_input(\"Enter the thickness of the center plaster in m^2 \"))\nRpc = Lpc/(kp * Apc) # center plaster resistance [\u00b0C/W]\n\nAb = float(raw_input(\"Enter the area of the brick in m^2 \"))\nLb = float(raw_input(\"Enter the thickness of the brick in m^2 \"))\nRb = Lb/(kb * Ab) # brick resistance [\u00b0C/W]\n\n# resistances in parallel\nR_parallel = 1/Rpc + 1/Rb + 1/Rpc\n\n# total resistance\nR_tot = R_in + Rf + Rp + R_parallel + Rp + R_out\n\n# unit heat transfer rate [W]\nQr_unit = (T_in - T_out)/R_tot\n\n# HEAT TRANSFER RATE OF THE WHOLE WALL [W]\nA_wall = float(raw_input(\"Enter the area of the wall in m^2 \"))\nQr_wall = Qr_unit * (A_wall/A_unit)\n\nprint \"\\n The total resistance of the unit is: R_tot = \" + str(R_tot) + \" \u00b0C/W\"\nprint \"\\n The unit heat transfer rate is: Qr_unit = \" + str(Qr_unit) + \" W\"\nprint \"\\n The heat transfer rate of the wall is: Qr_wall = \" + str(Qr_wall) + \" W\""} {"blob_id": "910c28a16665a578b4d8033241554eea17fac058", "repo_name": "LawrenceELee/GraphAlgorithmsAndDataStructures-python", "path": "/sorts.py", "length_bytes": 9068, "score": 3.921875, "int_score": 4, "content": "'''\nImplementation of common sorting algs in python.\n\nSelection sort: \"selects\" min, puts it in correct place.\n avg/worst runtime: O(n^2), aux mem: O(1), stable?\n\nInsertion sort: avg/worst runtime: O(n^2), aux mem: O(1),\n stable: yes, in-place: yes.\n\nMerge sort: avg/worst runtime: O(n lg n), aux mem: O(n),\n stable: yes, in-place: no.\n\nQuick sort: avg runtime: O(n lg n) under the assumption that elements are\n randomized/shuffled and that they are mostly unique/few duplicates,\n if not then you will get worst runtime: O(n^2), aux mem: O(lg n),\n stable: no, in-place: yes (even though it has rec call stacks).\n\nQuick 3-way sort: variant of quicksort (quick3) that is great for data with\n many duplicates.\n\nHeap sort: avg/worst runtime: O(n lg n), aux mem: O(1). stable?\n\nTimsort: python\u2019s native sorting algorithm, is a naturally adaptive version\n of merge sort. best runtime: O(n), worst O(n lg n).\n\n'''\n\nfrom random import randrange as randrange\n\ndef selectionsort_v1(data):\n '''\n This version is more imperative (translation of Java to Python).\n '''\n N = len(data)\n\n i = 0\n while i < N:\n minimum = i\n\n j = i+1\n while j < N:\n if data[j] < data[minimum]:\n minimum = j #found new minimum.\n j += 1\n\n data[i], data[minimum] = data[minimum], data[i] #python idiom for swap.\n i += 1\n\ndef test_selectionsort_v1():\n print(\"Testing selectionsort v1...\")\n my_list = [randrange(100) for i in range(50)]\n print(my_list)\n print(\"sorted?\", is_sorted(my_list))\n selectionsort_v1(my_list)\n print(my_list)\n print(\"sorted?\", is_sorted(my_list))\n print()\n\ndef selectionsort_v2(data):\n '''\n This version of selection sort uses Python idioms and style:\n * use min() to find minimum instead of iterating over array.\n * use enumerate() to return a pair (idx, element) instead of 2 nested\n for-loops.\n * use comma to swap values instead of swap() function.\n '''\n for idx, element in enumerate(data):\n # find min in remaining array using element/value as the key.\n # x.__getitem__(y) <==> x[y]\n mn = min(range(idx, len(data)), key=data.__getitem__) #find min\n\n data[idx], data[mn] = data[mn], element #swap data[idx] and data[mn].\n return data #is this optional? since sort is in-place, no need to return.\n '''\n what does enumerate do?\n it numbers elmnts from 0 to N-1, in effect assigning idices to elements.\n >>> data = ['a', 'b', 'c', 'd', 'e', 'f']\n >>> for i in enumerate(data):\n print(i)\n\n (0, 'a')\n (1, 'b')\n (2, 'c')\n (3, 'd')\n (4, 'e')\n (5, 'f')\n '''\n\ndef test_selectionsort_v2():\n print(\"Testing selectionsort v2...\")\n my_list = [randrange(100) for i in range(50)]\n print(my_list)\n print(\"sorted?\", is_sorted(my_list))\n selectionsort_v2(my_list)\n print(my_list)\n print(\"sorted?\", is_sorted(my_list))\n print()\n\n\n\n\n\ndef insertionsort(data):\n '''\n avg/worst case runtime: O(n^2), aux mem: O(1), in-place, stable.\n '''\n N = len(data)\n i = 0\n while i < N:\n j = i\n while j > 0 and data[j] < data[j-1]:\n data[j], data[j-1] = data[j-1], data[j] #swap j with j-1\n j -= 1\n\n i += 1\n\ndef test_insertionsort():\n print(\"Testing insertionsort...\")\n my_list = [randrange(100) for i in range(50)]\n print(my_list)\n print(\"sorted?\", is_sorted(my_list))\n insertionsort(my_list)\n print(my_list)\n print(\"sorted?\", is_sorted(my_list))\n print()\n\n\n\n\n\ndef gnomesort(data):\n '''\n Gnomesort is a variant of insertion sort.\n '''\n i = 0\n while i < len(data):\n if i == 0 or data[i-1] <= data[i]:\n i += 1\n else:\n data[i], data[i-1] = data[i-1], data[i] #swap data[i] with data[i-1]\n i -= 1\n\ndef test_gnomesort():\n print(\"Testing gnomesort...\")\n my_list = [randrange(100) for i in range(50)]\n print(my_list)\n print(\"sorted?\", is_sorted(my_list))\n gnomesort(my_list)\n print(my_list)\n print(\"sorted?\", is_sorted(my_list))\n print()\n\n\n\n\n\ndef mergesort(data): #data is a more general than list object.\n '''\n Typical mergesort with a recursive dividing portion, then a merging portion.\n '''\n \n #mid = len(data)//2 #integer division, truncate after decimal pt.\n #under the hood, it might covert // into >>\n mid = len(data) >> 1 #fast way to divide by 2. just bitshift left.\n #do we have to worry about the sign bit since >> carries sign bit?\n\n left, right = data[:mid], data[mid:] #split at midpoint into 2 subarrays.\n\n #if subarray size is greater than 1 (more than 1 element), then...\n if len(left) > 1:\n left = mergesort(left) #recurse on left subarray.\n\n if len(right) > 1:\n right = mergesort(right) #recurse on right subarray.\n\n #merge portion of mergesort\n aux = [] #auxilary space\n while left and right: #while left and right sublists not empty...\n #easier to keep track of last elmnt than pointers for curr left/right.\n if left[-1] >= right[-1]:\n aux.append(left.pop()) #take last element of left subarray.\n else:\n aux.append(right.pop()) #take last element of right subarray.\n\n aux.reverse() #currently sorted descending, so need to reverse.\n return (left or right) + aux #concat aux with whatever is not empty, [].\n\ndef test_mergesort():\n print(\"Testing mergesort...\")\n my_list = [randrange(100) for i in range(50)]\n print(my_list)\n print(\"sorted?\", is_sorted(my_list))\n my_list = mergesort(my_list) #not in-place?\n print(my_list)\n print(\"sorted?\", is_sorted(my_list))\n print()\n\n\n\n\n\ndef quicksort_v1(data):\n shuffle(data) #make sure all data is randomized so that pivot is near mid.\n _quicksort(data, 0, len(data)-1)\ndef _quicksort(data, lo, hi):\n '''\n This version uses the same array and just swaps elements as needed.\n '''\n if lo < hi: #if not base case, where size is greater than or equal to 1.\n pivot, i, j = data[lo], lo, hi #i is ptr for left subarry, j for right.\n while i <= j:\n while data[i] < pivot: #find elmnt less than pivot\n i += 1\n while data[j] > pivot: #find elmnt less than pivot\n j -= 1\n\n if i <= j:\n data[i], data[j] = data[j], data[i] #swap\n i += 1\n j -= 1\n\n _quicksort(data, lo, j)\n _quicksort(data, i, hi)\n\ndef quicksort_v2(data):\n '''\n This doesn't do it in-place, it creates a new list everytime when it\n concatenates less, pivot, more.\n '''\n if len(data) <= 1: return data #base case\n less, pivot, more = partition(data)\n #sort lo up to pivot then concat with pivot then sort pivot+1 up to hi.\n return quicksort(less) + [pivot] + quicksort(more)\ndef partition(data):\n '''\n Partition will divide data into 2 lists: less (all elmts less than or equal\n to pivot), more (all elemts more than pivot), and 1 pivot elmnt.\n\n This doesn't do it in-place, it creates a new list everytime.\n '''\n #use first elmt as pivot, split into pivot and rest of data.\n pivot, data = data[0], data[1:]\n less = [i for i in data if i <= pivot] #create new list filtered from old.\n more = [i for i in data if i > pivot] #create new list filtered from old.\n return less, pivot, more #return lo list, pivot, hi list.\n\ndef test_quicksort():\n print(\"Testing quicksort...\")\n my_list = [randrange(100) for i in range(50)]\n print(my_list)\n print(\"sorted?\", is_sorted(my_list))\n quicksort_v1(my_list) #in-place sort, no new array is returned.\n print(my_list)\n print(\"sorted?\", is_sorted(my_list))\n print()\n\n\n\n\ndef shuffle(data):\n '''\n Helper function to randomize/shuffle elements in list.\n This is important for quicksort because this helps to make the pivot element\n somewhere near the middle of list and probablistic guarentee of\n O(n lg n) avg runtime.\n '''\n N = len(data)\n for idx, elmt in enumerate(data):\n randIdx = idx + randrange(N - idx)\n data[idx], data[randIdx] = data[randIdx], elmt\ndef test_shuffle():\n print(\"Testing shuffle()...\")\n my_list = [i for i in range(100)]\n shuffle(my_list)\n return is_sorted(my_list)\n \n\n\n\ndef is_sorted(data):\n '''\n Helper function to check that sort algs are working correctly.\n '''\n N = len(data) - 1\n i = 0\n while i < N:\n if data[i] > data[i+1]: return False #if out of order, return false\n i += 1\n \n return True #if no errors, then it is sorted.\n\ndef main():\n test_selectionsort_v1()\n test_selectionsort_v2()\n test_insertionsort()\n test_gnomesort()\n test_mergesort()\n test_quicksort()\n\n\nif __name__ == \"__main__\":\n main()\n"} {"blob_id": "95b1aaf12d07da9c8ca5e6adbce1a530abdab73f", "repo_name": "HarshaR99/Algorithm", "path": "/Flyod.py", "length_bytes": 636, "score": 3.734375, "int_score": 4, "content": "def floydWarshall(graph): \r\n\tdist = map(lambda i : map(lambda j : j , i) , graph) \r\n\tfor k in range(V): \r\n\t\t for i in range(V): \r\n\t\t\tfor j in range(V): \r\n\t\t\t\t dist[i][j] = min(dist[i][j] , \r\n dist[i][k]+ dist[k][j] \r\n ) \r\n\tprint \"Following matrix shows the shortest distances\\ \r\n \tbetween every pair of vertices\" \r\n \tfor i in range(V): \r\n \tfor j in range(V): \r\n \tif(dist[i][j] == INF): \r\n \tprint \"%7s\" %(\"INF\"), \r\n \telse: \r\n \tprint \"%7d\\t\" %(dist[i][j]), \r\n \tif j == V-1: \r\n print \"\" "} {"blob_id": "029be8472b06e6f10580e97f9d0abba67044fa61", "repo_name": "whglamrock/leetcode_series", "path": "/leetcode368 Largest Divisible Subset.py", "length_bytes": 2766, "score": 3.625, "int_score": 4, "content": "\n# in the following solution, 'compatible' means: after adding the new curNum to the previous subsets,\n# they are still inter-divisible. If can't read the reference, rewrite every i & j for loop for our\n# test case to understand.\n\nfrom copy import copy\n\n# P.S.: How could the copied list remain when the original list changes? Use the 'copy' operator!\nclass Solution(object):\n def largestDivisibleSubset(self, nums):\n\n nums.sort()\n n = len(nums)\n if n == 0: return []\n dp = [0] * n\n dp[0] = [nums[0]]\n\n for i in xrange(1, n): # after the ith loop, dp[:i+1] are valid (i.e., = final dp[:i+1])\n curNum = nums[i]\n maxSet = []\n for j in xrange(i): # every dp[j] is valid because dp[:i] are valid\n if curNum % nums[j] == 0: # curNum is divisible by nums[j], then it must be divisible by\n # every number in dp[j] that is less than nums[j]\n localSet = copy(dp[j])\n if len(localSet) > len(maxSet):\n maxSet = localSet\n # The j for loop looks for longest subset with dp[:i] that's compatible with nums[i].\n # For two biggest dp[x], dp[y] within dp[:i] that are both compatible with nums[i],\n # the maxSet for nums[i] can only be either dp[x]+[nums[i]] or dp[y]+[nums[i]]!\n # Reasoning:\n # 1) Let's assume len(dp[y]) > len(dp[x]).\n # 2) If dp[x], dp[y] are incompatible and have common elements, all uncommon\n # elements in dp[x] are causing the incompatibility. So if the maxSet for nums[i]\n # = dp[y]+[nums[i]], all uncommon elements in dp[x] can not be added to this maxSet.\n # 3) If dp[x], dp[y] are incompatible and don't have common elements, the situation is even\n # easier to think through\n # 4) If dp[x], dp[y] are compatible, then y must > x and all elements of dp[x] are included\n # in dp[y]. Thus the maxSet for nums[i] -- dp[i] = dp[y]+[nums[i]]\n # All above proves that once we found the longest compatible subset dp[y] within dp[:i],\n # the dp[i] = dp[y]+[nums[i]] and there is no need to check other common elements in various\n # dp[j]s.\n\n maxSet.append(nums[i]) # after finding the previously longest subset, adding nums[i] itself.\n dp[i] = maxSet # update the dp[i] for it to be used in next i for loop.\n\n res = []\n for localSet in dp: # in final dp, dp[i] is the largest subset ends with nums[i]\n if len(localSet) > len(res):\n res = localSet\n return res\n\n\n\nSol = Solution()\nnums = [1,2,3,4,6,24]\nprint Sol.largestDivisibleSubset(nums)"} {"blob_id": "1fabac46f70f50929a0b2426a7d1d037b7f59f84", "repo_name": "yi-guo/coding-interview", "path": "/leetcode/python/032-longestValidParentheses.py", "length_bytes": 1140, "score": 3.90625, "int_score": 4, "content": "#!/usr/bin/python\n\n# Given a string containing just the characters '(' and ')', find the length of the longest valid\n# (well-formed) parentheses substring.\n\n# For \"(()\", the longest valid parentheses substring is \"()\", which has length = 2.\n\n# Another example is \")()())\", where the longest valid parentheses substring is \"()()\", which has length = 4.\n\n# Dynamic programming - d[i] indicates the length of the longest parentheses starting at s[i].\n# If s[i] == ')', then d[i] = 0.\n# If s[i] == '(', then j = i + 1 + d[i + 1]\n# if s[j] == ')', then d[i] = d[i + 1] + 2 + d[j + 1]\n# otherwise, d[i] == 0\n# Maintain such d from right to left and return max(d), thus O(n)\ndef longestValidParentheses(s):\n if not s or len(s) < 2:\n return 0\n d = [0 for i in range(len(s))]\n for i in range(len(s) - 2, -1, -1):\n if s[i] == '(':\n j = i + 1 + d[i + 1]\n if j < len(s) and s[j] == ')':\n d[i] = d[i + 1] + 2\n if j < len(s) - 1:\n d[i] = d[i] + d[j + 1]\n return max(d)\n\ndef main():\n s = '(()'\n print longestValidParentheses(s)\n\nmain()\n"} {"blob_id": "94f277dbb9288698af5697259b129c8c3c46e169", "repo_name": "cireneuguilhermeteixeira/IC-2019.2-activities", "path": "/quebra_cabeca_deslizante/slide_puzzle_solver.py", "length_bytes": 15112, "score": 3.9375, "int_score": 4, "content": "#!/usr/bin/env python\n\"\"\"Implementa um solucionador para um slide puzzle NxN\n\nEste c\u00f3digo implementa classes e modelos para solucionar inst\u00e2ncias de um problema slide puzzle de ordem NxN.\nA estrat\u00e9gia para resolu\u00e7\u00e3o \u00e9 a de busca em largura em \u00e1rvore de decis\u00f5es utilizando heur\u00edsticas tipo A*. Por padr\u00e3o,\no problema a ser resolvido ser\u00e1 uma matriz de 3 linhas e 3 colunas (3x3), mas o programa \u00e9 capaz de resolver inst\u00e2ncias\nmaiores, para isso, execute-o passando como argumento o valor a ser usado como ordem da matriz.\n\"\"\"\n\nfrom __future__ import annotations\nfrom functools import reduce\nfrom typing import List, Set\nfrom decimal import Decimal\nimport operator\nimport random\nimport heapq\nimport copy\nimport sys\n\n__author__ = \"Tiago Siqueira Dionizio\"\n__email__ = \"tiagosdionizio@gmail.com\"\n\n\nclass StateMatrix:\n def __init__(self, rows: int, columns: int, elements: List[List]):\n self.rows = rows\n self.columns = columns\n self.elements = elements\n\n def __str__(self):\n msg: str = \"\"\n hyphens_qt: int = (9 * self.columns - 1)\n msg += \"\\n+{}+\\n\".format(hyphens_qt * \"-\")\n for i in range(self.rows):\n for j in range(self.columns):\n msg += \"| {x:^4} \".format(x=str(self.elements[i][j])\n if self.elements[i][j] != self.rows * self.columns\n else \" \") # o bloco vazio \u00e9 o de maior valor na sequ\u00eancia do puzzle\n msg += \"|\\n\"\n if i != self.rows - 1:\n msg += \"|{}|\\n\".format(hyphens_qt * \"-\")\n msg += \"+{}+\\n\".format(hyphens_qt * \"-\")\n return msg\n\n def is_solved(self) -> bool:\n for i in range(self.rows):\n for j in range(self.columns):\n if self.elements[i][j] != self.rows * i + j + 1:\n return False\n return True\n\n # retorna uma tupla (linha, coluna) que informa a posi\u00e7\u00e3o do elemento buscado na matriz\n def get_element_position(self, element: int) -> tuple:\n cords: List[tuple] = [(ind, self.elements[ind].index(element)) for ind in range(len(self.elements))\n if element in self.elements[ind]]\n return cords[0]\n\n def get_blank_space_position(self) -> tuple:\n # o bloco vazio \u00e9 o valor mais alto na sequ\u00eancia de n\u00fameros do puzzle que varia de acordo com o tamanho deste\n blank_value: int = self.rows * self.columns\n cords: tuple = self.get_element_position(blank_value)\n return cords\n\n def calculate_manhattan_distance(self, element: int) -> int:\n if element not in [item for sublist in self.elements for item in sublist]:\n return Decimal('Infinity') # se o elemento n\u00e3o existe na matriz sua dist\u00e2ncia \u00e9 infinita\n\n row_expected: int = (element - 1) // self.columns\n column_expected: int = (element - 1) % self.rows\n\n element_position: tuple = self.get_element_position(element)\n\n row_distance: int = abs(row_expected - element_position[0])\n column_distance: int = abs(column_expected - element_position[1])\n\n manhattan_distance: int = row_distance + column_distance\n return manhattan_distance\n\n def get_inversions_number(self) -> int:\n inversions: int = 0\n elements_list: List = [item for sublist in self.elements for item in sublist]\n blank_value: int = self.rows * self.columns\n for i in range((self.rows * self.columns) - 1):\n for j in range(i + 1, (self.rows * self.columns)):\n # se o valor da c\u00e9lula n\u00e3o for vazio e ela for maior do que uma c\u00e9lula subsequente n\u00e3o vazia,\n # ent\u00e3o temos uma invers\u00e3o\n if elements_list[i] != blank_value and elements_list[j] != blank_value \\\n and elements_list[i] > elements_list[j]:\n inversions += 1\n return inversions\n\n def is_solvable(self) -> (bool, str):\n \"\"\"\n Para um problema NxN ser solucion\u00e1vel, as seguintes condi\u00e7\u00f5es devem ser respeitadas:\n 1. Se N \u00e9 impar, o n\u00famero de invers\u00f5es no estado inicial deve ser par\n 2. Se N \u00e9 par, o problema ser\u00e1 solucion\u00e1vel se:\n 2.1. A c\u00e9lula vazia est\u00e1 em uma linha de \u00edndice par, contando de baixo para cima e o n\u00famero\n de invers\u00f5es \u00e9 \u00edmpar.\n 2.2. A c\u00e9lula vazia est\u00e1 em uma linha de \u00edndice \u00edmpar, contando de baixo para cima e o n\u00famero\n de invers\u00f5es \u00e9 par.\n Se estas condi\u00e7\u00f5es n\u00e3o forem atendidas, o problema N\u00c3O apresentar\u00e1 solu\u00e7\u00e3o!\n \"\"\"\n n: int = self.rows\n inversions: int = self.get_inversions_number()\n msg: str = \"\"\n if n % 2 == 1: # n \u00e9 \u00edmpar\n solvable: bool = inversions % 2 == 0\n if not solvable:\n msg = \"Problema de ordem \u00edmpar({}), mas com quantidade \u00edmpar de invers\u00f5es({} invers\u00f5es).\\n\\n\" \\\n .format(n, inversions)\n else: # n \u00e9 par\n blank_position_row: int = self.rows - self.get_blank_space_position()[0]\n if blank_position_row % 2 == 0: # a c\u00e9lula vazia est\u00e1 em uma linha par(de baixo para cima)\n solvable: bool = inversions % 2 == 1\n if not solvable:\n msg = \"Problema de ordem par({}), c\u00e9lula vazia em linha par, de baixo para cima, ({}), mas \" \\\n \"com quantidade par de invers\u00f5es({}).\\n\".format(n, blank_position_row, inversions)\n else: # a c\u00e9lula vazia est\u00e1 em uma linha \u00edmpar(de baixo para cima)\n solvable: bool = inversions % 2 == 0\n if not solvable:\n msg = \"Problema de ordem par({}), c\u00e9lula vazia em linha \u00edmpar, de baixo para cima, ({}), \" \\\n \"mas com quantidade \u00edmpar de invers\u00f5es({}).\\n\".format(n, blank_position_row, inversions)\n return solvable, msg\n\n\nclass TreeNode:\n def __init__(self, matrix: StateMatrix, tree_layer: int, children: List[TreeNode] = None, parent: TreeNode = None,\n ditance_from_solution: int = -1):\n self.matrix = matrix\n if children is None:\n self.children = []\n else:\n self.children = children\n self.parent = parent\n self.tree_layer = tree_layer\n if ditance_from_solution == -1:\n self.distance_from_solution = self.get_distance_from_solution()\n else:\n self.distance_from_solution = ditance_from_solution\n\n # heur\u00edstica para estimar qu\u00e3o distante da solu\u00e7\u00e3o o n\u00f3 est\u00e1, quanto menor o valor, melhor\n def get_distance_from_solution(self) -> int:\n blank_value: int = self.matrix.rows * self.matrix.columns\n\n distance: int = self.tree_layer\n distance += reduce(operator.add, map(self.matrix.calculate_manhattan_distance,\n [item for sublist in self.matrix.elements for item in sublist\n if item != blank_value]))\n\n return distance\n\n def generate_possible_states(self):\n permutations: List[dict] = []\n up: dict = {\"row\": -1, \"column\": 0}\n left: dict = {\"row\": 0, \"column\": -1}\n down: dict = {\"row\": 1, \"column\": 0}\n right: dict = {\"row\": 0, \"column\": 1}\n permutations.extend([up, down, left, right])\n\n for permutation in permutations:\n blank_position: tuple = self.matrix.get_blank_space_position()\n\n blank_row: int = blank_position[0]\n blank_column: int = blank_position[1]\n\n swap_row: int = permutation[\"row\"] + blank_row\n swap_column: int = permutation[\"column\"] + blank_column\n # o estado poss\u00edvel s\u00f3 ser\u00e1 criado se a c\u00e9lula a ser trocada estiver dentro dos limites da matriz\n if 0 <= swap_row < self.matrix.rows and 0 <= swap_column < self.matrix.columns:\n # como a c\u00f3pia de lista no python \u00e9, por padr\u00e3o, shallow, precisamos fazer uma deep copy, pois\n # vamos alterar a matriz de estados, mas queremos manter a matriz original inalterada\n copy_matrix: List[List] = copy.deepcopy(self.matrix.elements)\n child_state: StateMatrix = StateMatrix(self.matrix.rows, self.matrix.columns, copy_matrix)\n\n blank_value: int = self.matrix.rows * self.matrix.columns\n swap_value: int = child_state.elements[swap_row][swap_column]\n\n child_state.elements[swap_row][swap_column] = blank_value\n child_state.elements[blank_row][blank_column] = swap_value\n\n child_distance = self.distance_from_solution - self.matrix.calculate_manhattan_distance(swap_value)\n child_distance += child_state.calculate_manhattan_distance(swap_value) + 1\n\n node_child: TreeNode = TreeNode(child_state, self.tree_layer + 1, parent=self,\n ditance_from_solution=child_distance)\n if self.parent is not None:\n if node_child.matrix.elements != self.parent.matrix.elements:\n self.children.append(node_child)\n else:\n self.children.append(node_child)\n\n def __lt__(self, other: TreeNode): # m\u00e9todo usado para compara\u00e7\u00e3o no heap\n return self.distance_from_solution < other.distance_from_solution\n\n\nclass StateTree:\n def __init__(self, root: TreeNode):\n self.root = root\n\n # m\u00e9todo para encontrar o caminho de um n\u00f3 at\u00e9 a ra\u00edz da \u00e1rvore\n def find_path_to_root(self, node: TreeNode) -> List[TreeNode]:\n path: List[TreeNode] = []\n current_node: TreeNode = node\n while current_node != self.root:\n path.append(current_node)\n current_node = current_node.parent\n path.append(current_node)\n path.reverse() # a lista est\u00e1 de tr\u00e1s para frente, ent\u00e3o precisamos usar o reverse\n return path\n\n\nclass SlidePuzzleSolver:\n def __init__(self, decision_tree: StateTree):\n self.decision_tree: StateTree = decision_tree\n self.puzzle_rows: int = decision_tree.root.matrix.rows\n self.puzzle_columns: int = decision_tree.root.matrix.columns\n\n def solve(self):\n self.show_header_message()\n nodes_added: Set[TreeNode] = set()\n execution_queue: List[TreeNode] = [self.decision_tree.root]\n solution_found: bool = False\n current_node: TreeNode = self.decision_tree.root\n final_node: TreeNode = self.decision_tree.root\n heapq.heapify(execution_queue)\n if current_node.matrix.is_solved():\n solution_found = True\n final_node = current_node\n\n while not solution_found:\n current_node = heapq.heappop(execution_queue)\n print(\"\\nEstado escolhido:\\n{}\\nDistancia: {}\".format(current_node.matrix,\n current_node.distance_from_solution))\n nodes_added.add(current_node)\n current_node.generate_possible_states()\n for child in current_node.children:\n if child.matrix.is_solved():\n solution_found = True\n final_node = child\n else:\n if child.matrix.elements not in [node.matrix.elements for node in nodes_added]:\n heapq.heappush(execution_queue, child)\n\n solution_path: List[TreeNode] = self.decision_tree.find_path_to_root(final_node)\n self.show_solution_steps(solution_path)\n\n def show_header_message(self):\n print(\"\\n\\nResolvendo inst\u00e2ncia do problema quebra cabe\u00e7a deslizante.\\nN\u00famero de linhas: {}\"\n \"\\nN\u00famero de colunas: {}\\n\\nEstado inicial: {}\\n\\n\".format(self.puzzle_rows, self.puzzle_columns,\n self.decision_tree.root.matrix))\n\n @staticmethod\n def show_solution_steps(solution_path: List[TreeNode]):\n print(\"Solu\u00e7\u00e3o encontrada\\n\\n\")\n for index in range(len(solution_path) - 1):\n if index == 0:\n print(\"\\nEstado atual(Inicial)\")\n else:\n print(\"\\nEstado atual:\")\n print(solution_path[index].matrix)\n blank_position_actual_step = solution_path[index].matrix.get_blank_space_position()\n blank_position_next_step = solution_path[index + 1].matrix.get_blank_space_position()\n if blank_position_actual_step[0] != blank_position_next_step[0]: # moviento na vertical\n if blank_position_actual_step[0] - blank_position_next_step[0] > 0: # branco foi para cima\n step: str = \"->Mova o bloco vazio para CIMA.\"\n else: # branco foi para baixo\n step: str = \"->Mova o bloco vazio para BAIXO.\"\n else: # movimento na horizontal\n if blank_position_actual_step[1] - blank_position_next_step[1] > 0: # branco foi para a esquerda\n step: str = \"->Mova o bloco vazio para a ESQUERDA.\"\n else: # branco foi para a direita\n step: str = \"->Mova o bloco vazio para a DIREITA.\"\n print(step, \"\\n\")\n\n print(\"\\nEstado final(Problema resolvido):\\n\", solution_path[len(solution_path) - 1].matrix)\n print(\"\\nForam executados {} passos para encontrar a solu\u00e7\u00e3o.\\n\\n\".format(len(solution_path) - 1))\n\n\ndef generate_random_matrix(order: int) -> StateMatrix:\n solvable_matrix: bool = False\n while not solvable_matrix:\n elements: List = [x + 1 for x in range(order ** 2)]\n random.shuffle(elements)\n matrix: List[List] = [elements[index:index + order] for index in range(0, len(elements), order)]\n state_matrix: StateMatrix = StateMatrix(order, order, matrix)\n solvable_matrix = state_matrix.is_solvable()[0]\n if solvable_matrix:\n return state_matrix\n\n\ndef main():\n matrix_oder: int = 3\n try:\n arg: int = int(sys.argv[1])\n if arg > 1:\n matrix_oder = arg\n print(\"\\nUtilizando valor argumento {} como ordem da matriz do puzzle.\".format(matrix_oder))\n else:\n print(\"\\nUtilizando valor padr\u00e3o {} como ordem da matriz do puzzle, pois o valor passado como \"\n \"argumento ({}) \u00e9 menor que o m\u00ednimo aceit\u00e1vel(2).\".format(matrix_oder, int(sys.argv[1])))\n except (ValueError, IndexError):\n print(\"\\nUtilizando valor padr\u00e3o {} como ordem da matriz do puzzle.\".format(matrix_oder))\n pass\n\n initial_matrix_state: StateMatrix = generate_random_matrix(matrix_oder)\n solvable, msg = initial_matrix_state.is_solvable()\n if solvable:\n root: TreeNode = TreeNode(initial_matrix_state, 0)\n tree: StateTree = StateTree(root)\n\n slide_puzzle_solver: SlidePuzzleSolver = SlidePuzzleSolver(tree)\n slide_puzzle_solver.solve()\n else:\n print(\"\\nInst\u00e2ncia gerada n\u00e3o tem solu\u00e7\u00e3o!\\n\", initial_matrix_state, \"\\n{}\".format(msg))\n\n\nif __name__ == '__main__':\n main()\n"} {"blob_id": "728df81df64104aa0c0871ecacb962a9a128cfa2", "repo_name": "Rakan-AlZagha/8-puzzle-search", "path": "/search_ai.py", "length_bytes": 12735, "score": 3.671875, "int_score": 4, "content": "#\n# Author: Rakan AlZagha\n# Date: 3/15/2021\n#\n# Assignment: Project #1\n# Comments: BFS Linear Search is rather slow for more complicated problems (as expected), however, it fully works.\n#\n\n\nfrom queue import Queue\nfrom time import time\nfrom queue import PriorityQueue\nimport random\nimport sys\nimport numpy as np\n\n#\n# Class: Eight_Puzzle\n# Purpose: create an instance of the 8-Puzzle\n# and provide necessary elements to solve it\n# (heuristic, path, eval, state, goal)\n#\n\nclass Eight_Puzzle:\n state_count=0\n goal_state=[0,0,0,0,0,0,0,0,0]\n astar_eval=None\n heuristic_function = None\n heuristic_needed = False\n heuristic_type = None\n def __init__(self, state, root_origin, move, path_cost, goal_state, heuristic_type = None, heuristic_needed=False):\n self.root_origin=root_origin\n self.state=state\n self.move=move\n self.goal_state=goal_state\n if (self.root_origin == True):\n self.path_cost = root_origin.path_cost + path_cost\n else:\n self.path_cost = path_cost\n if (heuristic_needed == True):\n self.heuristic_needed=True\n self.heuristic_type=heuristic_type\n if(self.heuristic_type == 1):\n self.first_heuristic()\n self.astar_eval=self.heuristic_function+self.path_cost\n elif(self.heuristic_type == 2):\n self.second_heuristic()\n self.astar_eval=self.heuristic_function+self.path_cost\n else:\n heuristic_needed = False\n Eight_Puzzle.state_count = Eight_Puzzle.state_count + 1\n\n #\n # Function: first_heuristic\n # Purpose: calculate the number of misplaced tiles\n # and then report heuristic back to class\n # Parameters: self\n #\n\n def first_heuristic(self):\n self.heuristic_function=0\n for curr_node in range(1,9):\n if (self.is_goal_node(self,curr_node) == False):\n self.heuristic_function=self.heuristic_function+1\n #\n # Function: second_heuristic\n # Purpose: calculate the Manhattan distance of tiles\n # and then report heuristic back to class\n # Parameters: self\n #\n\n def second_heuristic(self):\n self.heuristic_function=0\n for curr_node in range(1,9):\n distance=abs(self.state.index(curr_node) - self.goal_state.index(curr_node))\n row=int(distance/3)\n column=int(distance%3)\n self.heuristic_function=self.heuristic_function+row+column\n\n #\n # Function: is_goal_node (static)\n # Purpose: checks if the current node is in the goal nodes place\n # Parameters: self, curr_node\n #\n\n @staticmethod\n def is_goal_node(self, curr_node):\n if (self.goal_state[curr_node] == self.state[curr_node]):\n return True\n else:\n return False\n \n #\n # Function: is_goal\n # Purpose: checks to see if current state is goal state\n # Parameters: self\n #\n\n def is_goal(self):\n if self.state == self.goal_state:\n return True\n else:\n return False\n\n #\n # Function: is_legal\n # Purpose: check if a move is legal/limit actions\n # Parameters: row,column\n #\n\n @staticmethod\n def is_legal(row,column):\n possible_actions = ['UP', 'DOWN', 'LEFT', 'RIGHT']\n if row == 0: \n possible_actions.remove('UP')\n if row == 2: \n possible_actions.remove('DOWN')\n if column == 0:\n possible_actions.remove('LEFT')\n if column == 2:\n possible_actions.remove('RIGHT')\n return possible_actions\n\n #\n # Function: explore_children\n # Purpose: expand current child node and generate children\n # Parameters: self\n #\n\n def explore_children(self):\n children=[]\n curr_pos = self.state.index(0)\n row = int(curr_pos / 3)\n column = int(curr_pos % 3)\n legal_actions=self.is_legal(row,column)\n for move in legal_actions:\n new_state = self.state.copy()\n if move == 'UP':\n temp_state = new_state[curr_pos]\n new_state[curr_pos] = new_state[curr_pos-3]\n new_state[curr_pos-3] = temp_state\n if move == 'DOWN':\n temp_state = new_state[curr_pos]\n new_state[curr_pos] = new_state[curr_pos+3]\n new_state[curr_pos+3] = temp_state\n if move == 'LEFT':\n temp_state = new_state[curr_pos]\n new_state[curr_pos] = new_state[curr_pos-1]\n new_state[curr_pos-1] = temp_state\n if move == 'RIGHT':\n temp_state = new_state[curr_pos]\n new_state[curr_pos] = new_state[curr_pos+1]\n new_state[curr_pos+1] = temp_state\n children.append(Eight_Puzzle(new_state, self, move, 1, self.goal_state, self.heuristic_type, self.heuristic_needed))\n return children\n\n #\n # Function: solution_path\n # Purpose: keep track of path/moves taken\n # Parameters: self\n #\n\n def solution_path(self):\n final_solution = []\n final_solution.append(self.move)\n final_path = self\n while final_path.root_origin != None:\n final_path = final_path.root_origin\n final_solution.append(final_path.move)\n final_solution = final_solution[:-1]\n final_solution.reverse()\n return final_solution\n#\n# Function: input_configuration\n# Purpose: Take in initial state as random or custom\n# Parameters: initial_state_decision\n#\n\ndef input_configuration(initial_state_decision):\n if(initial_state_decision == 1):\n initial_state = custom_config()\n print()\n print(\"Initial State:\")\n print_puzzle(initial_state)\n print()\n elif(initial_state_decision == 2):\n initial_state = random_config()\n print(\"Initial State:\")\n print_puzzle(initial_state)\n return initial_state\n\n#\n# Function: random_config\n# Purpose: generate a random configuration\n# Parameters: N/A\n#\n\ndef random_config():\n print(\"You chose random configuration\\n.\\n.\\n.\\n\")\n initial_state = [0, 1, 2, 3, 4, 5, 6, 7, 8]\n random.shuffle(initial_state)\n return initial_state\n\n#\n# Function: custom_config\n# Purpose: take in a custom tile configuration\n# Parameters: N/A\n#\n\ndef custom_config():\n print(\"You chose custom configuration\\n.\\n.\\n.\\n\")\n print(\"Enter 9 values from '0:8', seperate each with a space: \")\n digit_input = input()\n initial_state = digit_input.split(' ')\n char_to_int(initial_state)\n return initial_state\n\n#\n# Function: char_to_int\n# Purpose: convert char array into int array\n# Parameters: array\n#\n\ndef char_to_int(array):\n for i in range(0, len(array)):\n array[i] = int(array[i])\n return array\n\n#\n# Function: print_puzzle\n# Purpose: print the whole matrix (if needed)\n# Parameters: array\n#\n\ndef print_puzzle(array):\n two_dimension = np.reshape(array, (-1,3))\n for i in two_dimension:\n for j in i:\n print(j, end=\" \")\n print()\n\n#\n# Function: parity_check\n# Purpose: identify the parity needed for goal state calculation\n# Parameters: array\n#\n\ndef parity_check(array):\n parity_array = array[:]\n count = 0\n for i in range(0, len(parity_array) - 1):\n if(parity_array[i] == 0):\n del parity_array[i]\n for i in range(0, len(parity_array)):\n value = parity_array[i]\n for j in range(i+1, len(parity_array)):\n if(parity_array[j] < value):\n count = count + 1\n if(count % 2 == 0):\n parity = 0\n elif(count % 2 != 0):\n parity = 1\n return parity\n\n#\n# Function: goal_state_func\n# Purpose: identify correct goal based on parity\n# Parameters: self\n#\n\ndef goal_state_func(parity):\n if (parity == 0):\n goal_state = [1, 2, 3, 4, 5, 6, 7, 8, 0]\n elif (parity == 1):\n goal_state = [1, 2, 3, 8, 0, 4, 7, 6, 5]\n print(\"\\nGoal State:\")\n print_puzzle(goal_state)\n return goal_state\n\n#\n# Function: breadth_first_search\n# Purpose: search algorithm implementation for BFS\n# returns the solution to the puzzle\n# Parameters: initial_state, goal_state\n# Comments: struggles for more complex problems,\n# works, but takes a long time\n# Solutions: attempted to use binary search over linear search for reached states, \n# results were not as promising as I thought they would be\n#\n\ndef breadth_first_search(initial_state, goal_state):\n initial_root_node = Eight_Puzzle(initial_state, None, None, 0, goal_state,None, False)\n if initial_root_node.is_goal():\n return initial_root_node.solution_path()\n frontier = Queue()\n frontier.put(initial_root_node)\n reached=[]\n while (frontier.empty() != True):\n child_node=frontier.get()\n reached.append(child_node.state)\n expand_children=child_node.explore_children()\n for child in expand_children:\n if child.state not in reached:\n if child.is_goal():\n return child.solution_path()\n frontier.put(child)\n#\n# Function: a_star_misplaced (heuristic one)\n# Purpose: search algorithm for astar\n# returns the path to the solution\n# Parameters: initial_state, goal_state\n#\n\ndef a_star_misplaced(initial_state, goal_state):\n count=0\n reached=[]\n initial_root_node=Eight_Puzzle(initial_state,None,None,0,goal_state,1,True)\n frontier = PriorityQueue()\n frontier.put((initial_root_node.astar_eval,count,initial_root_node))\n while (frontier.empty() != True):\n child_node=frontier.get()\n child_node=child_node[2]\n reached.append(child_node.state)\n if child_node.is_goal():\n return child_node.solution_path()\n expand_children=child_node.explore_children()\n for child in expand_children:\n if child.state not in reached:\n count = count + 1\n frontier.put((child.astar_eval,count,child))\n\n#\n# Function: a_star_manhattan (heuristic two)\n# Purpose: search algorithm for astar\n# returns the path to the solution\n# Parameters: initial_state, goal_state\n#\n\ndef a_star_manhattan(initial_state, goal_state):\n count=0\n reached=[]\n initial_root_node=Eight_Puzzle(initial_state,None,None,0,goal_state,2,True)\n frontier = PriorityQueue()\n frontier.put((initial_root_node.astar_eval,count,initial_root_node))\n while (frontier.empty() != True):\n child_node=frontier.get()\n child_node=child_node[2]\n reached.append(child_node.state)\n if child_node.is_goal():\n return child_node.solution_path()\n expand_children=child_node.explore_children()\n for child in expand_children:\n if child.state not in reached:\n count = count + 1\n frontier.put((child.astar_eval,count,child))\n\n#\n# Function: main\n# Purpose: compile the 3 search algorithms and display results\n# Parameters: N/A\n#\n\ndef main():\n print(\"------------------------------------\")\n print(\"Welcome to the Eight_Puzzle Game!\")\n print(\"------------------------------------\")\n print()\n print(\"Please input decision (1 or 2) of initial state:\\n\\t1. Custom Configuration\\n\\t2. Random Configuration\")\n initial_state_decision = int(input(\"--> \"))\n initial_state = input_configuration(initial_state_decision)\n parity = parity_check(initial_state)\n goal_state = goal_state_func(parity)\n\n Eight_Puzzle.state_count=0\n initial_time=time()\n bfs=breadth_first_search(initial_state, goal_state)\n final_time=time()-initial_time\n print()\n print('Breadth First Search:', bfs)\n print('Total Number of Moves Required:', len(bfs))\n print('Total Number of Search Tree Nodes Explored:', Eight_Puzzle.state_count)\n print('Time until Completion:', final_time)\n print()\n\n Eight_Puzzle.state_count = 0\n initial_time = time()\n astar_misplaced = a_star_misplaced(initial_state, goal_state)\n final_time = time() - initial_time\n print()\n print('A* Misplaced Heuristic:',astar_misplaced)\n print('Total Number of Moves Required:', len(astar_misplaced))\n print('Total Number of Search Tree Nodes Explored:', Eight_Puzzle.state_count)\n print('Time until Completion:', final_time)\n print()\n\n\n Eight_Puzzle.state_count = 0\n initial_time = time()\n astar_manhattan = a_star_manhattan(initial_state, goal_state)\n final_time = time() - initial_time\n print()\n print('A* Manhattan Heuristic:',astar_manhattan)\n print('Total Number of Moves Required:', len(astar_manhattan))\n print('Total Number of Search Tree Nodes Explored:', Eight_Puzzle.state_count)\n print('Time until Completion:', final_time)\n print()\n\nif __name__ == \"__main__\":\n main()\n"} {"blob_id": "0d3bb1fe4de47366a4e7d0dcea204080bf4cf9ce", "repo_name": "sunnyyeti/Leetcode-solutions", "path": "/773 Sliding Puzzle.py", "length_bytes": 2545, "score": 3.96875, "int_score": 4, "content": "# On an 2 x 3 board, there are five tiles labeled from 1 to 5, and an empty square represented by 0. A move consists of choosing 0 and a 4-directionally adjacent number and swapping it.\n\n# The state of the board is solved if and only if the board is [[1,2,3],[4,5,0]].\n\n# Given the puzzle board board, return the least number of moves required so that the state of the board is solved. If it is impossible for the state of the board to be solved, return -1.\n\n \n\n# Example 1:\n\n\n# Input: board = [[1,2,3],[4,0,5]]\n# Output: 1\n# Explanation: Swap the 0 and the 5 in one move.\n# Example 2:\n\n\n# Input: board = [[1,2,3],[5,4,0]]\n# Output: -1\n# Explanation: No number of moves will make the board solved.\n# Example 3:\n\n\n# Input: board = [[4,1,2],[5,0,3]]\n# Output: 5\n# Explanation: 5 is the smallest number of moves that solves the board.\n# An example path:\n# After move 0: [[4,1,2],[5,0,3]]\n# After move 1: [[4,1,2],[0,5,3]]\n# After move 2: [[0,1,2],[4,5,3]]\n# After move 3: [[1,0,2],[4,5,3]]\n# After move 4: [[1,2,0],[4,5,3]]\n# After move 5: [[1,2,3],[4,5,0]]\n# Example 4:\n\n\n# Input: board = [[3,2,4],[1,5,0]]\n# Output: 14\n \n\n# Constraints:\n\n# board.length == 2\n# board[i].length == 3\n# 0 <= board[i][j] <= 5\n# Each value board[i][j] is unique.\nfrom collections import deque\nclass Solution:\n def slidingPuzzle(self, board: List[List[int]]) -> int:\n target_state = ((1,2,3),(4,5,0))\n state = lambda board: tuple(map(tuple,board))\n queue = deque([(state(board),0)])\n seen = {state(board)}\n def next_states(board_state):\n zero_r,zero_c = next((r,c) for r in range(2) for c in range(3) if board_state[r][c]==0)\n next_board = list(map(list,board_state))\n next_states = []\n for dr,dc in [(1,0),(-1,0),(0,1),(0,-1)]:\n nr,nc = zero_r+dr,zero_c+dc\n if 0<=nr<2 and 0<=nc<3:\n next_board[zero_r][zero_c],next_board[nr][nc] = next_board[nr][nc],next_board[zero_r][zero_c]\n next_states.append(state(next_board))\n next_board[zero_r][zero_c],next_board[nr][nc] = next_board[nr][nc],next_board[zero_r][zero_c]\n return next_states\n \n while queue:\n cur_state,moves = queue.popleft()\n if cur_state == target_state:\n return moves\n for next_state in next_states(cur_state):\n if next_state not in seen:\n queue.append((next_state,moves+1))\n seen.add(next_state)\n return -1"} {"blob_id": "13aa13e8cf39bc287179de7e49129bdabd7eb236", "repo_name": "jessica1127/python_leetcode", "path": "/leetcode/leetcode49_group-anagrams.py", "length_bytes": 2240, "score": 4.25, "int_score": 4, "content": "'''Given an array of strings, group anagrams together.\n\nExample:\n\nInput: [\"eat\", \"tea\", \"tan\", \"ate\", \"nat\", \"bat\"],\nOutput:\n[\n [\"ate\",\"eat\",\"tea\"],\n [\"nat\",\"tan\"],\n [\"bat\"]\n]\nNote:\n\nAll inputs will be in lowercase.\nThe order of your output does not matter.\n'''\nimport itertools\n\nclass Solution(object):\n def groupAnagrams(self, strs):\n \"\"\"\n :type strs: List[str]\n :rtype: List[List[str]]\n \"\"\"\n \n d = {}\n for w in strs:\n key = tuple(sorted(w))\n d[key] = d.get(key, []) + [w] #a = ['aa'] b=['bb'], a+b = ['aa', 'bb']\n print d.values()\n return d.values()\n#\u4e0b\u97624\u4e2a\u65b9\u6cd5\u6ca1\u6709\u5b8c\u5168\u61c2\uff0c\u4e0b\u9762\u8981\u7406\u89e3\uff1a\n def groupAnagrams2(self, strs):\n '''\n :type strs: List[str]\n :rtype: List[List[str]]\n '''\n \"\"\"\n collections.Counter creates a counter object. A counter object is like a specific kind of dictionary where it is build for counting (objects that hashes to same value)\n tuple(sorted(s)) is used here so that anagrams will be hashed to the same value. tuple is used because sorted returns a list which cannot be hashed but tuples can be hashed\n filter: selects some elements of the list based on given function (first argument - a lambda function is given here)\n lambda function defined here returns True if number of anagrams of that elements is greater than 1\n \"\"\"\n count = collections.Counter([tuple(sorted(s)) for s in strs])\n return filter(lambda x: count[tuple(sorted(x))]>1, strs)\n\n def groupAnagrams3(self, strs):\n return [sorted(g) for _, g in itertools.groupby(sorted(strs, key=sorted), sorted)]\n \n def groupAnagrams4(self, strs):\n groups = itertools.groupby(sorted(strs, key=sorted), sorted)\n return [sorted(members) for _, members in groups]\n\n def groupAnagrams5(self, strs):\n groups = collections.defaultdict(list)\n for s in strs:\n groups[tuple(sorted(s))].append(s)\n return map(sorted, groups.values())\n \n \n\nif __name__ == '__main__':\n strs = [\"eat\", \"tea\", \"tan\", \"ate\", \"nat\", \"bat\"]\n s = Solution()\n s.groupAnagrams(strs)\n \n \n"} {"blob_id": "250d69405d94fe71722b2c6c98de02f586a75703", "repo_name": "tcbegley/Algorithms", "path": "/Misc/knights.py", "length_bytes": 4209, "score": 4.3125, "int_score": 4, "content": "from collections import defaultdict\n\n\nclass Graph:\n \"\"\"\n Graph class. Add edges using add_edge or add_undirected_edge methods.\n Vertex labels can be any immutable type.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Graph is stored as a dictionary where vertex labels are the keys and\n the values are a list of labels of adjacent vertices.\n \"\"\"\n self.graph = defaultdict(list)\n\n def add_edge(self, v, w):\n \"\"\"\n Add a directed edge connecting vertex v to vertex w.\n \"\"\"\n self.graph[v].append(w)\n\n def add_undirected_edge(self, v, w):\n \"\"\"\n Add undirected edge connecting vertices v and w.\n \"\"\"\n self.add_edge(v, w)\n self.add_edge(w, v)\n\n def bfs(self, start, target):\n \"\"\"\n Conducts breadth first search for vertex target starting from vertex\n start. Returns length of shortest path, or -1 if target is unreachable\n from start, and optimal route. This function is just a wrapper that\n processes the returned dictionary.\n \"\"\"\n depth, path_dict = self._bfs(start, target)\n best_path = []\n if path_dict:\n k = target\n best_path.append(k)\n while k != start:\n k = path_dict[k]\n best_path.append(k)\n return depth, best_path[::-1]\n\n def _bfs(self, start, target):\n \"\"\"Implements the actual breadth first search.\"\"\"\n visited = defaultdict(lambda: False)\n\n queue = [start]\n visited[start] = True\n\n depth = {}\n reached_from = {}\n depth[start] = 0\n\n while queue:\n s = queue.pop(0)\n d = depth[s]\n if s == target:\n return d, reached_from\n for i in self.graph[s]:\n if not visited[i]:\n visited[i] = True\n queue.append(i)\n depth[i] = d + 1\n reached_from[i] = s\n return -1, None\n\n\nclass Knight:\n \"\"\"\n This class can be used to find the shortest path for a knight between two\n squares on a chessboard. It creates a graph where each vertex corresponds\n to a square on the chessboard and is connected to all other squares\n reachable in one move by the knight. The shortest path is then found by\n a breadth-first search on this graph.\n\n Graph vertices are indexed by 0, 1, ..., 63. self.vertex_map can be used to\n go between these numeric vertex labels and traditional chessboard labels,\n A1, C2 etc.\n \"\"\"\n\n def __init__(self):\n self.board, self.vertex_map = generate_board()\n\n def shortest_path(self, start, stop):\n \"\"\"Find shorest path between start and stop\"\"\"\n start_i = self.vertex_map.index(start)\n stop_i = self.vertex_map.index(stop)\n _, best_path = self.board.bfs(start_i, stop_i)\n return [self.vertex_map[i] for i in best_path]\n\n\ndef generate_board():\n \"\"\"Generate graph of possible knight moves and lookup dictionary\"\"\"\n vertex_map = [b + a for b in \"ABCDEFGH\" for a in \"12345678\"]\n board = Graph()\n for i in range(8):\n for j in range(8):\n loc = 8 * i + j\n if i >= 2 and j > 0:\n # down 2, left 1\n board.add_edge(loc, loc - 17)\n if i >= 2 and j < 7:\n # down 2, right 1\n board.add_edge(loc, loc - 15)\n if i >= 1 and j > 1:\n # down 1, left 2\n board.add_edge(loc, loc - 10)\n if i >= 1 and j < 6:\n # down 1, right 2\n board.add_edge(loc, loc - 6)\n if i < 7 and j > 1:\n # up 1, left 2\n board.add_edge(loc, loc + 6)\n if i < 7 and j < 6:\n # up 1, right 2\n board.add_edge(loc, loc + 10)\n if i < 6 and j > 0:\n # up 2, left 1\n board.add_edge(loc, loc + 15)\n if i < 6 and j < 7:\n # up 2, right 1\n board.add_edge(loc, loc + 17)\n return board, vertex_map\n\n\nif __name__ == \"__main__\":\n k = Knight()\n print(k.shortest_path(\"A1\", \"D4\"))\n"} {"blob_id": "79fe016317254a0d7fab8da831809bd6f323f347", "repo_name": "maomao905/algo", "path": "/find-minimum-in-rotated-sorted-array.py", "length_bytes": 1074, "score": 3.625, "int_score": 4, "content": "\"\"\"\nbinary search\ncompare start <--> pivot/pivot <--> end\nif start < pivot: ok, otherwise, there is a pivot inside, so binary search within that range\nif pivot < pivot: ok, otherwise, there is a pivot inside\n\ntime: O(logN)\nspace: O(1)\n\"\"\"\nfrom typing import List\nclass Solution:\n def findMin(self, nums: List[int]) -> int:\n left, right = 0, len(nums)-1\n \n if nums[left] < nums[right]:\n return nums[0]\n \n while left < right:\n # print(left,right)\n mid = (left+right)//2\n # mid\u3088\u308a\u3082\u53f3\u5074\u306b\u304b\u306a\u3089\u305apivot\u304c\u3042\u308b\n if nums[right] < nums[mid]:\n left = mid + 1\n else:\n # x // 2\u306f\u5207\u308a\u6368\u3066\u306a\u306e\u3067\u3001right = mid\u306b\u3059\u308b\u3068\u3001\u52dd\u624b\u306bright\u304c\u4e00\u3064\u5de6\u306b\u305a\u308c\u3066\u304f\u308c\u308b\u30a4\u30e1\u30fc\u30b8\n right = mid\n \n return nums[left]\n\ns = Solution()\nprint(s.findMin([3,4,5,1,2]))\nprint(s.findMin([3,4,5,6,1,2]))\nprint(s.findMin([4,5,6,7,0,1,2]))\nprint(s.findMin([1]))\nprint(s.findMin([1,2]))\nprint(s.findMin([1,2,3]))\n"} {"blob_id": "95b11d213a5a771d6e6a99e24194e58a0ad54f24", "repo_name": "Vspick/python_interview", "path": "/leetcode/symmetric-tree.py", "length_bytes": 1233, "score": 3.953125, "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\nclass Solution(object):\n def isSymmetric(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: bool\n \"\"\"\n queue = [root]\n while queue:\n layer_val = []\n new_queue = []\n for node in queue:\n if node is not None:\n new_queue.append(node.left)\n new_queue.append(node.right)\n val = node.val if node is not None else None\n layer_val.append(val)\n if layer_val != layer_val[::-1]:\n return False\n queue = new_queue\n return True\n\n# \u9012\u5f52\u89e3\u6cd5\nclass Solution(object):\n def isSymmetric(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: bool\n \"\"\"\n def t_equal_rec(l,r):\n if not l and not r: return True\n if not l or not r: return False\n return l.val==r.val and t_equal_rec(l.left, r.right) and t_equal_rec(l.right, r.left)\n if not root: return True\n return t_equal_rec(root.left, root.right)"} {"blob_id": "cac2a1ab9d94504c6267860ce7baf3712dcd2776", "repo_name": "bhusalashish/DSA-1", "path": "/Data/DP/0 - 1 Variations/Count of Subset Sum Recursive.py", "length_bytes": 1268, "score": 3.734375, "int_score": 4, "content": "'''\n#### Name: 0 - 1 Variations\nLink: [link]()\n\n#### Sub_question_name: Count of Subset Sum Recursive \nLink: [link]()\n\nInstead of true or false we use 0 or 1\n\n'''\nfrom pprint import pprint\n\n\ndef count_subset(arr, req_sum):\n # print(req_sum, arr)\n if req_sum == 0:\n return 1\n\n if len(arr) == 0:\n return 0\n\n item = arr[-1]\n arr = arr[:-1]\n\n if item > req_sum:\n return count_subset(arr, req_sum)\n else:\n return count_subset(arr, req_sum) + count_subset(arr, req_sum-item)\n\n\n# arr = [2, 3, 5]\narr = [1, 1, 2, 3]\nn = len(arr)\nreq_sum = 4\n\nprint(count_subset(arr, req_sum))\n\n# Memoization Solution\n\n\ndef count_subset(arr, req_sum, T):\n n = len(arr)\n if T[n][req_sum] != -1:\n return T[n][req_sum]\n\n if req_sum == 0:\n return 1\n\n if len(arr) == 0:\n return 0\n\n item = arr[-1]\n arr = arr[:-1]\n\n if item > req_sum:\n T[n][req_sum] = count_subset(arr, req_sum, T)\n return T[n][req_sum]\n else:\n T[n][req_sum] = count_subset(\n arr, req_sum, T) + count_subset(arr, req_sum-item, T)\n return T[n][req_sum]\n\n\n# arr = [2, 3, 5]\narr = [1, 1, 2, 3]\nreq_sum = 4\nT = [[-1 for j in range(req_sum+1)] for i in range(n+1)]\n\nprint(count_subset(arr, req_sum, T))\n\n"} {"blob_id": "17bd943cdcd33f187fb78f65d255310b63840f15", "repo_name": "shhuan/algorithms", "path": "/leetcode/hard/N_Queens.py", "length_bytes": 2198, "score": 3.890625, "int_score": 4, "content": "# -*- coding: utf-8 -*-\n\n\"\"\"\ncreated by huash06 at 2015-04-29 13:56\n\nThe n-queens puzzle is the problem of placing n queens on an n\u00d7n chessboard such that no two queens attack each other.\n\n\n\nGiven an integer n, return all distinct solutions to the n-queens puzzle.\n\nEach solution contains a distinct board configuration of the n-queens' placement,\nwhere 'Q' and '.' both indicate a queen and an empty space respectively.\n\nFor example,\nThere exist two distinct solutions to the 4-queens puzzle:\n\n[\n [\".Q..\", // Solution 1\n \"...Q\",\n \"Q...\",\n \"..Q.\"],\n\n [\"..Q.\", // Solution 2\n \"Q...\",\n \"...Q\",\n \".Q..\"]\n]\n\n\"\"\"\n__author__ = 'huash06'\n\nimport sys\nimport os\nimport datetime\nimport functools\nimport itertools\nimport collections\nimport copy\nclass Solution:\n # @return a list of lists of string\n def solveNQueens(self, n):\n if n <= 0:\n return []\n board = [['.'] * n for _ in range(n)]\n return self.dfs(n, 0, board, [False]*n)\n\n def dfs(self, num, row, board, usedCols):\n if row >= num:\n # \u8fd9\u91cc\u53ef\u4ee5\u4e0d\u7528deepcopy\uff0c \u5feb\u5f88\u591a\n aboard = copy.copy(board)\n return [[''.join(arow) for arow in aboard]]\n\n ret = []\n for col, used in enumerate(usedCols):\n if not used and self.canPlace(board, num, row, col):\n usedCols[col] = True\n board[row][col] = 'Q'\n oneBoard = self.dfs(num, row+1, board, usedCols)\n ret.extend(oneBoard)\n board[row][col] = '.'\n usedCols[col] = False\n return ret\n def canPlace(self, board, num, row, col):\n # \u53ea\u9700\u8981\u770b\u4e0a\u9762\u7684\u659c\u7ebf\u4f4d\u7f6e\u662f\u5426\u653e\u7f6e\uff0c (1, -1), (1, 1)\u4e0d\u7528\u68c0\u67e5\n delta = [(-1, -1), (-1, 1)]\n for d in delta:\n r = row + d[0]\n c = col + d[1]\n while 0 <= r < num and 0 <= c < num:\n if board[r][c] == 'Q':\n return False\n r += d[0]\n c += d[1]\n return True\n\n\n\ns = Solution()\n\n\nprint(s.solveNQueens(4))\n\nstartTime = datetime.datetime.now()\nprint(s.solveNQueens(9))\nprint('Time Cose: {}'.format(datetime.datetime.now() - startTime))\n"} {"blob_id": "b8fd7bb642447b2c790d507c23a07573232ba7f8", "repo_name": "TianhengZhao/LeetCode", "path": "/[34]\u5728\u6392\u5e8f\u6570\u7ec4\u4e2d\u67e5\u627e\u5143\u7d20\u7684\u7b2c\u4e00\u4e2a\u548c\u6700\u540e\u4e00\u4e2a\u4f4d\u7f6e.py", "length_bytes": 3197, "score": 3.59375, "int_score": 4, "content": "# \u7ed9\u5b9a\u4e00\u4e2a\u6309\u7167\u5347\u5e8f\u6392\u5217\u7684\u6574\u6570\u6570\u7ec4 nums\uff0c\u548c\u4e00\u4e2a\u76ee\u6807\u503c target\u3002\u627e\u51fa\u7ed9\u5b9a\u76ee\u6807\u503c\u5728\u6570\u7ec4\u4e2d\u7684\u5f00\u59cb\u4f4d\u7f6e\u548c\u7ed3\u675f\u4f4d\u7f6e\u3002 \n# \n# \u4f60\u7684\u7b97\u6cd5\u65f6\u95f4\u590d\u6742\u5ea6\u5fc5\u987b\u662f O(log n) \u7ea7\u522b\u3002 \n# \n# \u5982\u679c\u6570\u7ec4\u4e2d\u4e0d\u5b58\u5728\u76ee\u6807\u503c\uff0c\u8fd4\u56de [-1, -1]\u3002 \n# \n# \u793a\u4f8b 1: \n# \n# \u8f93\u5165: nums = [5,7,7,8,8,10], target = 8\n# \u8f93\u51fa: [3,4] \n# \n# \u793a\u4f8b 2: \n# \n# \u8f93\u5165: nums = [5,7,7,8,8,10], target = 6\n# \u8f93\u51fa: [-1,-1] \n# Related Topics \u6570\u7ec4 \u4e8c\u5206\u67e5\u627e\n\n\n# leetcode submit region begin(Prohibit modification and deletion)\nfrom typing import List\n\n\nclass Solution:\n def searchRange_ans(self, nums: List[int], target: int) -> List[int]:\n \"\"\"\n \u7528\u4e8c\u5206\u67e5\u627e\u5206\u522b\u627e\u5230\u9996\u5c3e\u4f4d\u7f6e\n \"\"\"\n if not nums:\n return [-1, -1]\n first_pos = self.findFirstPos(nums, target)\n if first_pos == -1:\n return [-1, -1]\n last_pos = self.findLastPos(nums, target)\n return [first_pos, last_pos]\n\n def findFirstPos(self, nums, target):\n \"\"\"\u627e\u5230\u6700\u5de6\u4fa7\u7684target\"\"\"\n left, right = 0, len(nums) - 1\n # \u4e0d\u80fd\u53d6\u7b49 \u4f1a\u6b7b\u5faa\u73af\n while left < right:\n mid = left + (right - left) // 2\n # \u76ee\u6807 > mid\u4f4d\u7f6e\u503c\uff0c\u6240\u6709\u76ee\u6807\u503c\u5728[mid+1, right]\u5185\n if target > nums[mid]:\n left = mid + 1\n # \u76ee\u6807 <= mid\u4f4d\u7f6e\u503c\uff0c\u6700\u5de6\u7684\u76ee\u6807\u5728[left, mid]\u4e2d\n else:\n right = mid\n # \u6700\u540e\u4e00\u6b21while\u65f6\uff0c\u4e00\u5b9a\u53ea\u6709\u4e24\u4e2a\u6570\u4e86\uff0cmid\u53d6\u5730\u677f\uff0cleft = mid = right-1\n # \u82e5target > nums[mid], left = mid + 1 = right\n # \u82e5target <= nums[mid], right = mid = left\n if nums[left] == target:\n return left\n return -1\n\n def findLastPos(self, nums, target):\n \"\"\" \u627e\u6700\u53f3\u4fa7target \"\"\"\n left, right = 0, len(nums) - 1\n while left < right:\n # \u53d6\u5929\u68da\uff01\n mid = left + (right - left) // 2 + 1\n # \u76ee\u6807 < mid\u4f4d\u7f6e\u503c\uff0c\u6240\u6709\u76ee\u6807\u503c\u5728[left, mid-1]\u5185\n if target < nums[mid] :\n right = mid - 1\n # \u76ee\u6807 >= mid\u4f4d\u7f6e\u503c\uff0c\u6700\u53f3\u7684\u76ee\u6807\u5728[mid\uff0c right]\u4e2d\n else:\n left = mid\n return left\n\n\n def searchRange(self, nums: List[int], target: int) -> List[int]:\n \"\"\"\n \u5728target\u51e0\u4e4e\u4e0e\u6570\u7ec4\u7b49\u957f\u65f6\uff0c\u65f6\u95f4\u590d\u6742\u5ea6\u9000\u5316\u5230O(N)\n \"\"\"\n length = len(nums)\n if not length:\n return [-1, -1]\n left, right = 0, length - 1\n while left <= right:\n mid = left + (right - left) // 2\n if nums[mid] == target:\n start = end = mid\n # \u627e\u5230\u4e4b\u540e\uff0c\u4ece\u8be5\u70b9\u4f9d\u6b21\u5411\u5de6\u53f3\u627e\u76f8\u7b49\u7684\u503c\n while start - 1 >= 0 and nums[start] == nums[start - 1]:\n start -= 1\n while end + 1 < length and nums[end] == nums[end + 1]:\n end += 1\n return [start, end]\n elif nums[mid] > target:\n right = mid - 1\n else:\n left = mid + 1\n return [-1, -1]\n# leetcode submit region end(Prohibit modification and deletion)\n"} {"blob_id": "25eb31986557393c5c87020b0c238b09e3ccad2f", "repo_name": "Gabrielatb/Interview-Prep", "path": "/hackbright/word_break.py", "length_bytes": 2480, "score": 3.71875, "int_score": 4, "content": "\n# Build a function that is given a phrase and a vocab set. \n# It should return a set of the possible legal phrases that can be made\n# from that vocabulary.\n\n# >>> vocab = {'i', 'a', 'ten', 'oodles', 'ford', 'inner', 'to',\n# ... 'night', 'ate', 'noodles', 'for', 'dinner', 'tonight'}\n\n# >>> sentences = parse('iatenoodlesfordinnertonight', vocab)\n\n# >>> for s in sorted(sentences):\n# ... print s\n# i a ten oodles for dinner to night\n# i a ten oodles for dinner tonight\n# i a ten oodles ford inner to night\n# i a ten oodles ford inner tonight\n# i ate noodles for dinner to night\n# i ate noodles for dinner tonight\n# i ate noodles ford inner to night\n# i ate noodles ford inner tonight\ndef wordBreak(s, wordDict, memo={}):\n \"\"\"\n :type s: str\n :type wordDict: List[str]\n :rtype: List[str]\n \"\"\"\n\n if s in memo:\n return memo[s]\n \n if not s:\n return []\n \n rest_sentence = []\n for word in wordDict:\n if word == s:\n rest_sentence.append(word)\n elif s.startswith(word):\n rest = s[len(word):]\n for item in wordBreak(rest, wordDict, memo):\n sentence = word + ' ' + item\n rest_sentence.append(sentence)\n memo[s] = rest_sentence\n return rest_sentence\n\n\n\n\n# vocab = ['i', 'a', 'ten', 'oodles', 'ford', 'inner', 'to',\n# 'night', 'ate', 'noodles', 'for', 'dinner', 'tonight']\n\n# sentence = 'iatenoodlesfordinnertonight'\nsentence = 'a'\nvocab = ['a']\n\nprint wordBreak(sentence, vocab)\n\n\n\n# def word_break(phrase, vocab):\n# \"\"\"Break a string into words.\n\n# Input:\n# - string of words without space breaks\n# - vocabulary (set of allowed words)\n\n# Output:\n# set of all possible ways to break this down, given a vocab\n# \"\"\"\n\n# # 'set of all possible legal phrases' ---> recursion\n\n# poss_breaks = set()\n\n# for word in vocab:\n# #base case no parsing required\n# if phrase == word:\n# poss_breaks.add(word)\n\n# elif phrase.startswith(word):\n# #word matches beginning of string\n\n# #rest of the string\n# rest = phrase[len(word):]\n\n# #recurse to find the various possibilities of end of sentence\n\n \n# for parsed in word_break(rest, vocab):\n# print parsed\n# # word_and_rest = [word + ' ' + parsed]\n\n# # return_lst.append(word_and_rest)\n\n# # return return_lst\n\n\n\n\n\n\n\n\n"} {"blob_id": "254e089c775e0643192a952f580607aeac0aaf4f", "repo_name": "zh-wang/leetcode", "path": "/solutions/0124_Binary_Tree_Maximum_Path_Sum/dfs.py", "length_bytes": 574, "score": 3.515625, "int_score": 4, "content": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def maxPathSum(self, root: TreeNode) -> int:\n self.ret = -1<<32\n self.dfs(root)\n return self.ret\n\n def dfs(self, root):\n if not root:\n return 0\n l = self.dfs(root.left)\n r = self.dfs(root.right)\n cur_sum = root.val + max(0, l) + max(0, r)\n self.ret = max(self.ret, cur_sum)\n return max(0, root.val + max(0, l, r))\n"} {"blob_id": "c44835bd5043e3a3656475a390e90f47773d5c92", "repo_name": "jungle8884/Algorithm_Code", "path": "/kmeans.py", "length_bytes": 5262, "score": 3.6875, "int_score": 4, "content": "\"\"\"\nk = 2, n = 8\n\u6570\u636e:\n1\t1\n2\t1\n1\t2\n2\t2\n4\t3\n5\t3\n4\t4\n5\t4\n\u7b2c\u4e00\u6b21\u7ed8\u56fe\u65f6:\n \u53d8\u5316\u4e4b\u524d\u8c03\u7528showCluster(data, k, centroids, clusterAssment), \n\u7531\u4e8emarkIndex = int(clusterAssment[i, 0]) \u7b49\u4e8e0, \u6240\u4ee5\u5168\u662f\u7ea2\u8272;\n\u53d8\u5316\u4e4b\u540e\u518d\u8c03\u7528showCluster(data, k, centroids, clusterAssment),\nclusterAssment[i, :] = minIndex, minDist ** 2 \u66f4\u65b0, \u6240\u4ee5\u4e00\u7c07\u4e3a\u7ea2\u5708, \u53e6\u4e00\u7c07\u4e3a\u84dd\u8272\u6b63\u65b9\u5f62;\n\u5176\u4e2d, \u8d28\u5fc3\u7528\u9ed1\u8272*\u8868\u793a.\n\u4ee5\u6b64\u7c7b\u63a8, \u83b7\u5f97\u6700\u540e\u56fe\u50cf\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n# \u52a0\u8f7d\u6570\u636e\ndef loadData(filename):\n data = np.loadtxt(filename, delimiter='\\t', encoding=\"UTF-8-sig\")\n return data\n\n\n# \u8ba1\u7b97\u6b27\u5f0f\u8ddd\u79bb\ndef euclideanDistances(X, Y):\n # X \u4ee3\u8868\u5750\u6807(x1, x2) Y \u4ee3\u8868\u5750\u6807(y1, y2)\n return np.sqrt(np.sum((X - Y) ** 2))\n\n\n# \u6784\u5efak\u4e2a\u968f\u673a\u8d28\u5fc3 k=2\ndef randCent(data, k):\n m, n = data.shape # (8, 2) \u6570\u7ec4\u7684\u5f62\u5f0f\uff0c\u5bf9\u4e8e\u77e9\u9635\uff0cm \u884c n \u5217, \u5217\u6570\u8868\u793a\u7ef4\u6570\n centroids = np.zeros((k, n), dtype=np.int) # (k=2, n=2) k \u884c n \u5217, \u5217\u6570\u4e0e\u6837\u672c\u7684\u5217\u6570\u4e00\u81f4\n for i in range(k):\n index = int(np.random.uniform(0, m)) # \u968f\u673a\u751f\u6210\u5e8f\u53f7 0~7 uniform---[low, high)\n centroids[i, :] = data[index, :] # [index, :]\u8868\u793a\u7b2cindex\u884c\u6240\u6709\u5143\u7d20\n return centroids\n\n\ndef kMeans(data, k):\n m = np.shape(data)[0] # shape=(8,2) \u8868\u793a8\u884c2\u5217, [0]\u6b64\u5904\u83b7\u53d6\u884c\u6570\n clusterChange = True # \u82e5\u7c07\u53d1\u751f\u4e86\u6539\u53d8\u4e3aTrue\n # \u7b2c\u4e00\u5217\u5b58\u6837\u672c\u5c5e\u4e8e\u54ea\u4e00\u7c07\n # \u7b2c\u4e8c\u5217\u5b58\u6837\u672c\u7684\u5230\u7c07\u7684\u4e2d\u5fc3\u70b9\u7684\u8bef\u5dee\n # mat \u4ee3\u8868 matrix \u77e9\u9635 [m \u884c 2 \u5217], \u884c\u53f70~7\u4ee3\u8868\u6837\u672c\u5e8f\u53f7\n clusterAssment = np.mat(np.zeros((m, 2)))\n\n # \u7b2c1\u6b65 \u521d\u59cb\u5316centroids\u8d28\u5fc3\n centroids = randCent(data, k) # \u968f\u673a\u751f\u6210k=2\u4e2a\u8d28\u5fc3\n while clusterChange: # \u82e5\u8d28\u5fc3\u53d1\u751f\u4e86\u6539\u53d8\u5c31\u7ee7\u7eed\u6267\u884c\n clusterChange = False\n # \u663e\u793a\u8d28\u5fc3\u53d8\u5316\u4e4b\u524d---\u770b\u8fc7\u7a0b\u7528\n # showCluster(data, k, centroids, clusterAssment)\n # \u904d\u5386\u6240\u6709\u6837\u672c data[0~7, :] m==8\n # \u7b2c1\u8f6e\u7684\u8d28\u5fc3\u662f\u5728\u6837\u672c\u4e2d\u7684, \u5e76\u6ca1\u6709\u6392\u9664, \u56e0\u6b64\u4f1a\u6709\u4e24\u6b21\u6837\u672c\u81ea\u8eab\u7684\u8ba1\u7b97, \u4f46\u5e76\u4e0d\u5f71\u54cd\u7ed3\u679c\n for i in range(m):\n # \u6bcf\u4e00\u884c\u90fd\u8981\u627e\u6700\u5c0f\u8ddd\u79bb\n minDist = 100000.0\n minIndex = -1\n\n # \u904d\u5386\u6240\u6709\u7684\u8d28\u5fc3 centroids[0~1, :] k==2\n # \u7b2c2\u6b65 \u627e\u51fa\u6700\u8fd1\u7684\u8d28\u5fc3, \u7d22\u5f15j\u4fdd\u5b58\u5230minIndex\n for j in range(k):\n # \u8ba1\u7b97\u8be5\u6837\u672c\u5230\u8d28\u5fc3\u7684\u6b27\u5f0f\u8ddd\u79bb\n distance = euclideanDistances(centroids[j, :], data[i, :])\n if distance < minDist:\n minDist = distance\n minIndex = j\n\n # \u7b2c3\u6b65: \u66f4\u65b0\u6bcf\u4e00\u4e2a\u6837\u672c\u6240\u5c5e\u7684\u7c07 i=minIndex\n if clusterAssment[i, 0] != minIndex: # \u7b2c\u4e00\u5217\u5143\u7d20\u503c\u4e0d\u7b49\u4e8e\u6700\u5c0f\u8d28\u5fc3\u7d22\u5f15\u503c\n clusterChange = True\n clusterAssment[i, :] = minIndex, minDist ** 2 # \u4e3a\u7b2ci\u884c\u6240\u6709\u5143\u7d20\u8d4b\u503c\n\n # \u7b2c4\u6b65: \u66f4\u65b0\u8d28\u5fc3, \u6bcf\u4e00\u8f6e\u66f4\u65b0\u4e00\u6b21\n for j in range(k):\n ''' nonzero(a) \u8fd4\u56de\u6570\u7ec4a\u4e2d\u975e\u96f6\u5143\u7d20\u7684\u7d22\u5f15\u503c\u6240\u7ec4\u6210\u7684\u6570\u7ec4\u3002\n np.mean() \u4e8c\u7ef4\u77e9\u9635\uff0caxis=0\u8fd4\u56de\u7eb5\u8f74\u7684\u5e73\u5747\u503c\uff0caxis=1\u8fd4\u56de\u6a2a\u8f74\u7684\u5e73\u5747\u503c\n clusterAssment[:, 0] \u8868\u793a\u7b2c\u4e00\u5217\u6570\u503c---\u6240\u5c5e\u7684\u7c07(.A\u8868\u793a\u8f6c\u6362\u4e3a array)\n clusterAssment[:, 0].A == j \u8868\u793a\u5c5e\u4e8e\u7b2cj\u7c07\n np.nonzero(clusterAssment[:, 0].A == j)[0] \u53d6\u975e\u96f6\u6570\u7ec4---\u7531\u7b2cj\u7c07\u7684\u7d22\u5f15\u503c\u6784\u6210\n np.mean(pointInCluster, axis=0) \u5bf9\u7b2cj\u7c07\u7684\u503c\u6c42\u5e73\u5747\u503c'''\n pointInCluster = data[np.nonzero(clusterAssment[:, 0].A == j)[0]] # \u83b7\u53d6\u7c07\u4e2d\u6240\u6709\u70b9\n centroids[j, :] = np.mean(pointInCluster, axis=0) # \u5bf9\u7c07\u6c42\u5e73\u5747\u503c\u6c42\u65b0\u7684\u8d28\u5fc3\n # \u8d28\u5fc3\u53d8\u5316\u4e4b\u540e---\u770b\u8fc7\u7a0b\u7528\n # showCluster(data, k, centroids, clusterAssment)\n # \u5b8c\u6210\u540e\u8fd4\u56de\u8d28\u5fc3, \u7c07[\u6240\u5c5e\u8d28\u5fc3, \u8bef\u5dee]\n return centroids, clusterAssment\n\n\n# \u6570\u636e\u53ef\u89c6\u5316\ndef showCluster(data, k, centroids, clusterAssment):\n m, n = data.shape # (8, 2) \u6570\u7ec4\u7684\u5f62\u5f0f\uff0c\u5bf9\u4e8e\u77e9\u9635\uff0cm \u884c n \u5217, \u5217\u6570\u8868\u793a\u7ef4\u6570\n if n != 2:\n print(\"\u6570\u636e\u4e0d\u662f\u4e8c\u7ef4\u7684\")\n return 1\n\n # \u7ea2\u5706\u5708 \u84dd\u8272\u6b63\u65b9\u5f62 \u9ed1\u8272\u6b63\u4e09\u89d2-\u8d28\u5fc3\u989c\u8272\n mark = ['or', 'sb', '*k', '*k']\n if k > len(mark):\n print(\"k\u503c\u592a\u5927\u4e86\")\n return 1\n\n # \u7ed8\u5236\u5750\u6807\u8f74, \u6807\u9898\n plt.title('k-means')\n plt.xlabel('X-Axis')\n plt.ylabel('Y-Axis')\n\n # \u7ed8\u5236\u6240\u6709\u7684\u6837\u672c\n for i in range(m):\n markIndex = int(clusterAssment[i, 0])\n plt.plot(data[i, 0], data[i, 1], mark[markIndex]) # (x, y, \u989c\u8272---[0~1])\n\n # \u7ed8\u5236\u8d28\u5fc3\n for i in range(k):\n plt.plot(centroids[i, 0], centroids[i, 1], mark[i+2]) # \u8d28\u5fc3\u989c\u8272\u4e3a: mark[2~3]\n\n plt.show()\n\n\n''' if __name__ == \"__main__\":\n__name__ \u662f\u5f53\u524d\u6a21\u5757\u540d\uff0c\u5f53\u6a21\u5757\u88ab\u76f4\u63a5\u8fd0\u884c\u65f6\u6a21\u5757\u540d\u4e3a __main__ \n\u8fd9\u53e5\u8bdd\u7684\u610f\u601d\u5c31\u662f\uff0c\u5f53\u6a21\u5757\u88ab\u76f4\u63a5\u8fd0\u884c\u65f6\uff0c\u4ee5\u4e0b\u4ee3\u7801\u5757\u5c06\u88ab\u8fd0\u884c\uff0c\n\u5f53\u6a21\u5757\u662f\u88ab\u5bfc\u5165\u65f6\uff0c\u4ee3\u7801\u5757\u4e0d\u88ab\u8fd0\u884c\u3002'''\nif __name__ == \"__main__\":\n data = loadData('test.txt')\n k = 2\n centroids, clusterAssment = kMeans(data, k)\n showCluster(data, k, centroids, clusterAssment) # \u6700\u7ec8\u56fe\u50cf\n\n"} {"blob_id": "c7745273e2f4642ea5195100bc50aab5361cbd8f", "repo_name": "furkanyildiz/GTU_COURSES", "path": "/CSE 321- Introduction To Algorithm Design/hw3/CSE321_HW3_141044031/labify_141044031.py", "length_bytes": 1444, "score": 4.03125, "int_score": 4, "content": "import bfs\n\n#the function repairs a lab and it's roads which is connectted to it.\ndef calculate_cost(graph,starting_point,visited,road_cost,lab_cost):\n\n if visited == len(graph)*[True]:\n return 0\n\n parent = bfs.breadthFirstSearch(graph, starting_point)\n road_count = -1\n for i in range(len(parent)):\n if parent[i] != -1:\n visited[i] = True\n road_count = road_count +1\n\n if parent[i] == -1 and visited[i] == False:\n starting_point = i + 1\n break\n\n return road_cost*road_count + lab_cost + calculate_cost(graph,starting_point,visited,road_cost,lab_cost)\n\n\n\ndef findMinimumCostToLabifyGTU(lab_cost,road_cost,graph):\n #connected olmayan graphlar icin tuttugum array, bu array ile islem yapilmayan vertexleri belirleyecegiz\n visited = len(graph) * [False]\n\n #bir lab\u0131n ve o laba bagli yollarin tamir edilmesiyle olusan cost\n cost_option_1 = calculate_cost(graph,1,visited,road_cost,lab_cost)\n\n #tum lablarin tamiri ile olusan cost\n cost_option_2 = len(graph) * lab_cost\n\n return cost_option_1 if cost_option_1 final_shift[1]:\r\n final_shift[0] = shift[0]\r\n final_shift[1] = shift[1] - final_shift[1]\r\n elif shift[1] < final_shift[1]:\r\n final_shift[1] -= shift[1]\r\n else:\r\n final_shift = [0, 0]\r\n\r\n dq.rotate((2 * final_shift[0] - 1) * final_shift[1])\r\n return \"\".join(dq)\r\n\r\n\r\nprint(stringShift(\"abcdefg\", [[1, 1], [1, 1], [0, 2], [1, 3]]))\r\n"} {"blob_id": "10dca784e8a85b8ed2d9f3a761ecd2752f17132b", "repo_name": "greatabel/puzzle_I_cracked", "path": "/3ProjectEuler/i1_25/i23Non-abundant sums.py", "length_bytes": 1786, "score": 4.09375, "int_score": 4, "content": "\n# A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n.\n\n# As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.\n\n# Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.\nimport time\n\ndef divisorGenerator(n):\n # print(\"divisorGenerator \",n)\n for i in range(1,int(n/2)+1):\n if n%i == 0: \n # print(i)\n yield i\n\ndef is_abundant(number):\n thesum = sum(list(divisorGenerator(number)))\n if thesum > number:\n return True\n else:\n return False\n\ndef find_abundant_below_num(num):\n myset = set()\n for number in range(1,num):\n if is_abundant(number):\n myset.add(number)\n print(\"find_abundant_below_num:\",len(myset))\n return myset\n\ndef generate_number_whoIs2abundantSum(abundants,limit):\n the2sumSet = set()\n for x in abundants:\n for y in abundants:\n if x + y < limit:\n the2sumSet.add(x+y)\n print(len(the2sumSet))\n thesum = 0\n for i in range(1,limit):\n thesum += i\n print('thesum=',thesum,thesum - sum(the2sumSet))\n\n\n\n\nif __name__ == \"__main__\":\n tic = time.clock()\n myset = find_abundant_below_num(28124)\n toc = time.clock()\n print(toc - tic)\n generate_number_whoIs2abundantSum(myset,28124)"} {"blob_id": "a73f34df9f07a9f5f0f9072a1bbd16a3c80f568e", "repo_name": "mrseidel/CEMC2016-LargeData", "path": "/Examples/CO2 - Example/pCO2Visual/application.windows64/pCO2setup.py", "length_bytes": 11527, "score": 3.625, "int_score": 4, "content": "'''\r\nProgrammers Name: Pavel Lovtsov\r\nDate Last Updated: January 20th, 2014\r\nCourse: ICS - 4UO \r\nDecription: Organizes data needed for visualization \r\nLimitation: Takes some time to finish\r\n\r\n'''\r\n\r\n#Initializing key variables and importing necessary libraries.\r\nimport linecache\r\nfilename1 = []\r\n\r\nimport random\r\n\r\nimport sys\r\nsys.setrecursionlimit(60000000)\r\n\r\ni = 3\r\n\r\n'''\r\nWorks cited:\r\nQuicksort: c2.com/cgi/wiki?QuickSortInPython\r\nUsed the quicksort code. Modified it to work with my objects.\r\n\r\nLinecache: http://python.about.com/od/simplerscripts/qt/Getlinebynumber.htm\r\nUsed to read file line by line.\r\n'''\r\n\r\nclass Information():\r\n def __init__(self,name,info,divisor,sortlat):\r\n self.name = name\r\n self.info = info\r\n self.divisor = divisor\r\n self.sortlat = sortlat \r\n\r\nclass Location(Information):\r\n def __init__(self,lat,lon,name,info,divisor,sortlat):\r\n self.lat = lat\r\n self.lon = lon\r\n Information.__init__(self,name,info,divisor,sortlat)\r\n \r\ndef latsort(list1):\r\n ''' \r\n (list) -> (list)\r\n \r\n This method takes a list of Location objects and sorts it by latitude. \r\n \r\n '''\r\n if len(list1) < 2: \r\n return list1\r\n else:\r\n pivot = random.choice(list1)\r\n small = [i for i in list1 if float(i.lat)< float(pivot.lat)]\r\n medium = [i for i in list1 if float(i.lat)==float(pivot.lat)]\r\n large = [i for i in list1 if float(i.lat)> float(pivot.lat)]\r\n return latsort(small) + medium + latsort(large)\r\n \r\n \r\n\r\n\r\n\r\ndef lonsorthelp(list1):\r\n ''' \r\n (list) -> (list)\r\n \r\n This method takes a list of Location objects and sorts it by longitude. \r\n \r\n ''' \r\n if len(list1) < 2: \r\n return list1\r\n else:\r\n pivot = random.choice(list1)\r\n small = [i for i in list1 if float(i.lon)< float(pivot.lon)]\r\n medium = [i for i in list1 if float(i.lon)==float(pivot.lon)]\r\n large = [i for i in list1 if float(i.lon)> float(pivot.lon)]\r\n return lonsorthelp(small) + medium + lonsorthelp(large)\r\n\r\n\r\n\r\n \r\ndef lonsort(list1,lastplace,current,final):\r\n ''' \r\n (list, integer, integer, list) -> (list)\r\n \r\n This method takes a list of Location objects, two integers(should be 0), \r\n and an empty list and returns the list of Location objects sorted by \r\n longitude while maintaining the order of latitude. \r\n \r\n ''' \r\n list1.append(Location(1000,1000,0,0,0,0))\r\n for i in range(0,((len(list1))-1)):\r\n if list1[i].sortlat == list1[i+1].sortlat:\r\n current +=1\r\n else:\r\n partial = []\r\n for x in range(lastplace,((current)+1)):\r\n partial.append(list1[x])\r\n final.append(partial)\r\n lastplace = current + 1\r\n current += 1 \r\n for i in range(0,(len(final))):\r\n final[i] = lonsorthelp(final[i])\r\n lastone = []\r\n for i in range(0,(len(final))):\r\n for x in range (0, (len(final[i]))):\r\n lastone.append(final[i][x])\r\n final = []\r\n return lastone \r\n\r\n\r\ndef avg(filename1, locationarray):\r\n ''' \r\n \r\n (list, list)\r\n \r\n This method takes the list of raw data and an empty list. It creates Location objects, \r\n sorts them, combines data that have similar latitude and longitude, averages it, and \r\n outputs the objects' data to a text file. \r\n \r\n ''' \r\n \r\n #The 'avgconv' list is a list of average values for the data. It was calculated using a seperate program.\r\n avgconv = [0,0,372.10447779649525,14.660290051500347,14.40008071967913,34.085836704855666,358.8570867413065,36.361194911183425,362.61888945523253,1005.8678425248053,1005.6044413049046]\r\n #Splits up the data by the ',' character and creates a list.\r\n for d in range(0,(len(filename1))):\r\n filename1[d] = filename1[d].split(\",\")\r\n filename1[d][-1] = filename1[d][-1].replace('\\n',\"\")\r\n #Creates Location objects. The objects need a latitude,longitude, a name, their information, a divisor and\r\n #a number called a 'sortlat', which is needed by the sorting functions.\r\n print (\"Creating Objects\") \r\n for q in range(0,(len(filename1))):\r\n filewriting = \"LAT[\" + (str(round(float(filename1[q][2])))) + \"]LON[\" + (str(round(float(filename1[q][3])))) + \"]\"\r\n locationarray.append(Location((filename1[q][2]),(filename1[q][3]),filewriting,filename1[q][4:],1,(str(round(float(filename1[q][2]))))))\r\n #I recently found out the values that weren't measured were denoted using \r\n #'-999.9'. Since we don't know what the value is, a safe guess is that it was an average value. So the part replaces\r\n #all the '-999.9' with average values calculated earlier.\r\n print (\"Replacing null values with average values.\")\r\n for i in range(0,(len(locationarray))):\r\n for x in range(2,(len(locationarray[i].info))):\r\n if float(locationarray[i].info[x]) == -999.9:\r\n locationarray[i].info[x] = avgconv[x]\r\n print (\"Replaced.\")\r\n #Sorts the objects by both latitude and longitude\r\n print (\"Sorting.\")\r\n locationarray = (latsort(locationarray)) \r\n locationarray = (lonsort(locationarray,0,0,[]))\r\n #Objects that have the same name are combined into one object which holds the all the totals.\r\n print (\"Sorted. Collecting 'like' terms.\")\r\n h = 1\r\n while h != ((len(locationarray))):\r\n if locationarray[h-1].name == locationarray[h].name:\r\n for y in range(2,(len(locationarray[h].info))):\r\n locationarray[h-1].info[y] = (float(locationarray[h-1].info[y]))+(float(locationarray[h].info[y]))\r\n if float(locationarray[h-1].info[1]) < float(locationarray[h].info[1]):\r\n locationarray[h-1].info[0] = locationarray[h].info[0]\r\n locationarray[h-1].info[1] = locationarray[h].info[1]\r\n \r\n locationarray[h-1].divisor += 1\r\n locationarray.remove(locationarray[h]) \r\n h = 1\r\n \r\n else:\r\n h+=1\r\n \r\n #Averages out all the data. \r\n print (\"Done. Now averaging.\")\r\n for i in range(0,(len(locationarray))):\r\n for x in range(2,(len(locationarray[i].info))):\r\n locationarray[i].info[x] = (\"%.2f\" %(float(float(locationarray[i].info[x]))/(locationarray[i].divisor)))\r\n for i in range(0,(len(locationarray))):\r\n '''\r\n Firstly, it trys to read a pre-existing file that has the same latitude and longitude as the object. If it finds one, the data is combined and re-averaged. If not, a new file is created holding all the averages.\r\n '''\r\n try:\r\n with open(locationarray[i].name + '.txt', 'r') as in_file:\r\n holder = in_file.readlines()\r\n for x in range(2,((len(holder))-1)):\r\n holder[x] = (float((holder[x].split(\": \")[1]).replace('\\n',\"\")))\r\n holder[-1] = int(holder[-1])\r\n for x in range(2,(len(locationarray[i].info))):\r\n holder[x] = (\"%.2f\" %((((holder[x]) * (holder[-1])) + ((float(locationarray[i].info[x])) * (locationarray[i].divisor))) / (int(holder[-1]) + locationarray[i].divisor)))\r\n holder[-1] = (int(holder[-1]) + locationarray[i].divisor)\r\n print (\"Overwriting file \" + locationarray[i].name)\r\n with open(locationarray[i].name + '.txt', 'w') as out_file:\r\n out_file.write(\"Date last updated: \" + str(locationarray[i].info[0]) + \"\\n\")\r\n out_file.write(\"Date last updated (Julian Date in decimal notation): \" + str(locationarray[i].info[1]) + \"\\n\")\r\n out_file.write(\"Mole fraction concentration of CO2(ppm) in dried air: \" + (str(holder[2])) + \"\\n\")\r\n out_file.write(\"Temperature at which pCO2 was measured in C: \" + (str(holder[3]))+ \"\\n\")\r\n out_file.write(\"Sea Surface Temperature in C: \" + (str(holder[4]))+ \"\\n\")\r\n out_file.write(\"Sea Surface Salinity: \" + (str(holder[5]))+ \"\\n\")\r\n out_file.write(\"Partial Pressure of CO2 in seawater (in units of microatmospheres) at the temperature in the SST line: \" + (str(holder[6]))+ \"\\n\")\r\n out_file.write(\"Partial Pressure of CO2 in seawater (in units of Pascals) at the temperature in the TEMP line: \" + (str(holder[7]))+ \"\\n\")\r\n out_file.write(\"Partial Pressure of CO2 in seawater (in units of microatmospheres) at the temperature in the TEMP_PCO2 line: \" + (str(holder[8]))+ \"\\n\")\r\n out_file.write(\"Pressure in the equilibration vessel in units of millibars: \" + str((holder[9]))+ \"\\n\")\r\n out_file.write(\"Barometric pressure in the outside air from the ship's observation system in units of millibars: \" + (str(holder[10]))+ \"\\n\")\r\n out_file.write(str(holder[11])) \r\n except IOError: \r\n print (\"Creating new file \" + locationarray[i].name)\r\n with open(locationarray[i].name + '.txt', 'w') as out_file:\r\n out_file.write(\"Date last updated: \" + str(locationarray[i].info[0]) + \"\\n\")\r\n out_file.write(\"Date last updated (Julian Date in decimal notation): \" + str(locationarray[i].info[1]) + \"\\n\") \r\n out_file.write(\"Mole fraction concentration of CO2(ppm) in dried air: \" + (locationarray[i].info[2]) + \"\\n\")\r\n out_file.write(\"Temperature at which pCO2 was measured in C: \" + (locationarray[i].info[3])+ \"\\n\")\r\n out_file.write(\"Sea Surface Temperature in C: \" + (locationarray[i].info[4])+ \"\\n\")\r\n out_file.write(\"Sea Surface Salinity: \" + (locationarray[i].info[5])+ \"\\n\")\r\n out_file.write(\"Partial Pressure of CO2 in seawater (in units of microatmospheres) at the temperature in the SST line: \" + (locationarray[i].info[6])+ \"\\n\")\r\n out_file.write(\"Partial Pressure of CO2 in seawater (in units of Pascals) at the temperature in the TEMP line: \" + (locationarray[i].info[7])+ \"\\n\")\r\n out_file.write(\"Partial Pressure of CO2 in seawater (in units of microatmospheres) at the temperature in the TEMP_PCO2 line: \" + (locationarray[i].info[8])+ \"\\n\")\r\n out_file.write(\"Pressure in the equilibration vessel in units of millibars: \" + (locationarray[i].info[9])+ \"\\n\")\r\n out_file.write(\"Barometric pressure in the outside air from the ship's observation system in units of millibars: \" + (locationarray[i].info[10])+ \"\\n\")\r\n out_file.write(str(locationarray[i].divisor))\r\n\r\n \r\n print (\"Done. Next chunk...\")\r\n \r\n \r\n#Gets the number of lines in the file. \r\nprint (\"Getting number of lines.\")\r\nwith open('LDEO_Database_V2012.csv','r') as x:\r\n file = x.readlines()\r\nlenfile = len(file)\r\nfile = None\r\n\r\nprint (str(lenfile) + \" lines.\")\r\nprint (\"Processing Data.\")\r\n#Chunks the data together according to the first 4 characters (denoted as 'FILENAME' in the main file)\r\n#and feeds the chinks of data into the 'avg' function.\r\nwhile i < lenfile:\r\n i+= 1\r\n while (linecache.getline('LDEO_Database_V2012.csv',i))[:4] == (linecache.getline('LDEO_Database_V2012.csv',i+1))[:4]:\r\n filename1.append(linecache.getline('LDEO_Database_V2012.csv',i))\r\n i+=1\r\n filename1.append(linecache.getline('LDEO_Database_V2012.csv',i))\r\n print (\"Up to line \" + (str(i)) + \".\")\r\n avg(filename1,[])\r\n\r\n filename1 = []\r\n \r\n\r\n\r\n "} {"blob_id": "2a464645ba1591ea41dbbce8c4deda810a52c095", "repo_name": "sksavant/algo-problems", "path": "/topcoder/srm-144-div1/300.py", "length_bytes": 4094, "score": 4.375, "int_score": 4, "content": "#!/usr/bin/python\n'''\nProblem Statement\nLet's say you have a binary string such as the following:\n011100011\nOne way to encrypt this string is to add to each digit the sum of its adjacent digits. For example, the above string would become:\n123210122\nIn particular, if P is the original string, and Q is the encrypted string, then Q[i] = P[i-1] + P[i] + P[i+1] for all digit positions i. Characters off the left and right edges of the string are treated as zeroes.\nAn encrypted string given to you in this format can be decoded as follows (using 123210122 as an example):\nAssume P[0] = 0.\nBecause Q[0] = P[0] + P[1] = 0 + P[1] = 1, we know that P[1] = 1.\nBecause Q[1] = P[0] + P[1] + P[2] = 0 + 1 + P[2] = 2, we know that P[2] = 1.\nBecause Q[2] = P[1] + P[2] + P[3] = 1 + 1 + P[3] = 3, we know that P[3] = 1.\nRepeating these steps gives us P[4] = 0, P[5] = 0, P[6] = 0, P[7] = 1, and P[8] = 1.\nWe check our work by noting that Q[8] = P[7] + P[8] = 1 + 1 = 2. Since this equation works out, we are finished, and we have recovered one possible original string.\nNow we repeat the process, assuming the opposite about P[0]:\nAssume P[0] = 1.\nBecause Q[0] = P[0] + P[1] = 1 + P[1] = 1, we know that P[1] = 0.\nBecause Q[1] = P[0] + P[1] + P[2] = 1 + 0 + P[2] = 2, we know that P[2] = 1.\nNow note that Q[2] = P[1] + P[2] + P[3] = 0 + 1 + P[3] = 3, which leads us to the conclusion that P[3] = 2. However, this violates the fact that each character in the original string must be '0' or '1'. Therefore, there exists no such original string P where the first digit is '1'.\nNote that this algorithm produces at most two decodings for any given encrypted string. There can never be more than one possible way to decode a string once the first binary digit is set.\nGiven a string message, containing the encrypted string, return a tuple (string) with exactly two elements. The first element should contain the decrypted string assuming the first character is '0'; the second element should assume the first character is '1'. If one of the tests fails, return the string \"NONE\" in its place. For the above example, you should return {\"011100011\", \"NONE\"}.\nDefinition\n\nClass:\nBinaryCode\nMethod:\ndecode\nParameters:\nstring\nReturns:\ntuple (string)\nMethod signature:\ndef decode(self, message):\n\n\nConstraints\n-\nmessage will contain between 1 and 50 characters, inclusive.\n-\nEach character in message will be either '0', '1', '2', or '3'.\nExamples\n0)\n\n\"123210122\"\nReturns: { \"011100011\", \"NONE\" }\nThe example from above.\n1)\n\n\"11\"\nReturns: { \"01\", \"10\" }\nWe know that one of the digits must be '1', and the other must be '0'. We return both cases.\n2)\n\n\"22111\"\nReturns: { \"NONE\", \"11001\" }\nSince the first digit of the encrypted string is '2', the first two digits of the original string must be '1'. Our test fails when we try to assume that P[0] = 0.\n3)\n\n\"123210120\"\nReturns: { \"NONE\", \"NONE\" }\nThis is the same as the first example, but the rightmost digit has been changed to something inconsistent with the rest of the original string. No solutions are possible.\n4)\n\n\"3\"\nReturns: { \"NONE\", \"NONE\" }\n\n5)\n\n\"12221112222221112221111111112221111\"\nReturns: \n{ \"01101001101101001101001001001101001\",\n \"10110010110110010110010010010110010\" }\n\nThis problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2003, TopCoder, Inc. All rights reserved.\n'''\n\ndef getOriginal(q, start):\n p = []\n p.append(start)\n p.append(q[0]-start)\n for i in range(2,len(q)):\n x = q[i-1]-p[i-2]-p[i-1]\n if (x==0 or x==1):\n p.append(x)\n else:\n return []\n return p\n\ndef toString(l):\n s = \"\"\n if l == []:\n return \"NONE\"\n for x in l:\n s = s + str(x)\n return s\n\nclass BinaryCode:\n def decode(self, s):\n q = []\n for x in s:\n q.append(int(x))\n# Assuming 1st 0\n return (toString(getOriginal(q,0)),toString(getOriginal(q,1)))\n\nb = BinaryCode()\nprint b.decode(\"123210122\")\n"} {"blob_id": "88d7b33379b9dfee70691cfae2f55c554e30a352", "repo_name": "flamit/DataStructures", "path": "/Tree/maxSum.py", "length_bytes": 3569, "score": 4.3125, "int_score": 4, "content": "'''\nFind the maximum path sum between two leaves of a binary tree\n\nThe maximum sum path may or may not go through root. For eample in the following binary tree, the maximum sum is 27(3+6+9+0-1+10). Expected time complexity is O(n).\n\nA simple solution is to traverse the tree and do following for every traversed node X.\n 1) Find maximum sum from leaf to root in left subtree of X (we can use this post for this and next steps)\n 2) Find maximum sum from leaf to root in right subtree of X.\n 3) Add the above two calculated values and X->data and compare the sum with the maximum value obtained so far and update the maximum value.\n 4) Return the maximum value.\n\nThe time complexity of above solution is O(n2)\n\nWe can find the maximum sum using single traversal of binary tree. The idea is to maintain two values in recursive calls\n 1) Maximum root to leaf path sum for the subtree rooted under current node.\n 2) The maximum path sum between leaves (desired output).\n\nFor every visited node X, we find the maximum root to leaf sum in left and right subtrees of X. We add the two values with X->data, and compare the sum with maximum path sum found so far.\n\nFollowing is the implementation of the above O(n) solution.\n'''\n\n# Python program to find maximumpath sum between two leaves\n# of a binary tree\n \n \n# A binary tree node\nclass Node:\n # Constructor to create a new node\n def __init__(self, data):\n self.data = data\n self.left = None\n self.right = None\n \n# Utility function to find maximum sum between any\n# two leaves. This function calculates two values:\n# 1) Maximum path sum between two leaves which are stored\n# in res\n# 2) The maximum root to leaf path sum which is returned\n# If one side of root is empty, then it returns INT_MIN\n \ndef maxPathSumUtil(root, res):\n \n # Base Case\n if root is None:\n return 0\n \n if root.left is None and root.right is None:\n return root.data\n \n # Find maximumsum in left and righ subtree. Also\n # find maximum root to leaf sums in left and righ \n # subtrees ans store them in ls and rs\n ls = maxPathSumUtil(root.left, res)\n rs = maxPathSumUtil(root.right, res)\n \n # If both left and right children exist\n if root.left is not None and root.right is not None:\n \n # update result if needed\n res[0] = max(res[0], ls + rs + root.data)\n \n # Return maximum possible value for root being \n # on one side\n return max(ls, rs) + root.data\n \n # If any of the two children is empty, return\n # root sum for root being on one side\n if root.left is None:\n return rs + root.data\n else:\n return ls + root.data\n \n# The main function which returns sum of the maximum \n# sum path betwee ntwo leaves. THis function mainly \n# uses maxPathSumUtil()\ndef maxPathSum(root):\n INT_MIN = -2**32\n res = [INT_MIN]\n maxPathSumUtil(root, res)\n return res[0]\n \n \n# Driver program to test above function\nroot = Node(-15)\nroot.left = Node(5)\nroot.right = Node(6)\nroot.left.left = Node(-8)\nroot.left.right = Node(1)\nroot.left.left.left = Node(2)\nroot.left.left.right = Node(6)\nroot.right.left = Node(3)\nroot.right.right = Node(9)\nroot.right.right.right= Node(0)\nroot.right.right.right.left = Node(4)\nroot.right.right.right.right = Node(-1)\nroot.right.right.right.right.left = Node(10)\n \nprint \"Max pathSum of the given binary tree is\", maxPathSum(root)\n''' \n# This code is contributed by Nikhil Kumar Singh(nickzuck_007)\n \nRun on IDE\n\n Output: Max pathSum of the given binary tree is 27.\n\n\n'''\n"} {"blob_id": "6bda0599bba93f2cf7973681af6103d9459f7afc", "repo_name": "andreafiori/python-coding-dojo", "path": "/src/online/leetcode/single_number_ii.py", "length_bytes": 1562, "score": 3.734375, "int_score": 4, "content": "\"\"\"\nSingle Number II\n\nURL: https://leetcode.com/problems/single-number-ii/\n\nGiven a non-empty array of integers, every element appears three times except for one, which appears exactly once.\nFind that single one.\n\nNote: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?\n\nExample 1:\n Input: [2,2,3,2]\n Output: 3\n\nExample 2:\n Input: [0,1,0,1,0,1,99]\n Output: 99\n\n\"\"\"\nclass SingleNumberII(object):\n # def singleNumber(self, nums):\n # \"\"\"\n # :type nums: List[int]\n # :rtype: int\n # \"\"\"\n # import ctypes\n # # note that if res is not c 32\n # # there will be errors\n # count = [0] * 32\n # res = ctypes.c_int32(0)\n # for i in range(32):\n # for num in nums:\n # if (ctypes.c_int32(num).value >> i) & 1:\n # count[i] += 1\n # res.value |= ((count[i] % 3) << i)\n # return res.value\n\n def solution(self, nums):\n \"\"\"\n Solution 2\n :param nums: int\n :return: int\n \"\"\"\n # bitmask\n # ones as a bitmask to represent the ith bit had appeared once.\n # twos as a bitmask to represent the ith bit had appeared twice.\n # threes as a bitmask to represent the ith bit had appeared three times.\n ones, twos, threes = 0, 0, 0\n for num in nums:\n twos |= ones & num\n ones ^= num\n threes = ones & twos\n ones &= ~threes\n twos &= ~threes\n return ones"} {"blob_id": "563afc98e79b3396bfcce4fb9a451b09487d6f2c", "repo_name": "bass-2000/python-sandbox", "path": "/lesson_11/02_prime_numbers.py", "length_bytes": 7016, "score": 3.953125, "int_score": 4, "content": "# -*- coding: utf-8 -*-\n\n\n# \u0415\u0441\u0442\u044c \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u0433\u0435\u043d\u0435\u0440\u0430\u0446\u0438\u0438 \u0441\u043f\u0438\u0441\u043a\u0430 \u043f\u0440\u043e\u0441\u0442\u044b\u0445 \u0447\u0438\u0441\u0435\u043b\n\n\ndef get_prime_numbers(n):\n prime_numbers = []\n for number in range(2, n + 1):\n \"\"\"\u0415\u0441\u043b\u0438 \u0447\u0438\u0441\u043b\u043e \u043d\u0435 \u0434\u0435\u043b\u0438\u0442\u0441\u044f \u043d\u0430 \u043f\u0440\u0435\u0434\u0448\u0435\u0441\u0442\u0432\u0435\u043d\u043d\u0438\u043a\u043e\u0432 \u0441 \u043e\u0441\u0442\u0430\u0442\u043a\u043e\u043c \u043d\u043e\u043b\u044c - \u043f\u0440\u043e\u0441\u0442\u043e\u0435 \u0447\u0438\u0441\u043b\u043e, \u0435\u0433\u043e \u0434\u043e\u0431\u0430\u0432\u043b\u044f\u044e\u0442 \u0432 prime numb\n \u0435\u0441\u043b\u0438 \u043d\u0435\u0442 \u043e\u043d\u043e \u043f\u043e\u0440\u043f\u0443\u0441\u043a\u0430\u0435\u0442, \u0431\u0435\u0440\u0435\u0442\u0441\u044f \u0441\u043b\u0435\u0434.\"\"\"\n for prime in prime_numbers:\n if number % prime == 0:\n break\n else:\n prime_numbers.append(number)\n return prime_numbers\n\n\n# \u0427\u0430\u0441\u0442\u044c 1\n# \u041d\u0430 \u043e\u0441\u043d\u043e\u0432\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u0430 get_prime_numbers \u0441\u043e\u0437\u0434\u0430\u0442\u044c \u043a\u043b\u0430\u0441\u0441 \u0438\u0442\u0435\u0440\u0438\u0440\u0443\u0435\u043c\u044b\u0445 \u043e\u0431\u044c\u0435\u043a\u0442\u043e\u0432,\n# \u043a\u043e\u0442\u043e\u0440\u044b\u0439 \u0432\u044b\u0434\u0430\u0435\u0442 \u043f\u043e\u0441\u043b\u0435\u0434\u043e\u0432\u0430\u0442\u0435\u043b\u044c\u043d\u043e\u0441\u0442\u044c \u043f\u0440\u043e\u0441\u0442\u044b\u0445 \u0447\u0438\u0441\u0435\u043b \u0434\u043e n\n#\n# \u0420\u0430\u0441\u043f\u0435\u0447\u0430\u0442\u0430\u0442\u044c \u0432\u0441\u0435 \u043f\u0440\u043e\u0441\u0442\u044b\u0435 \u0447\u0438\u0441\u043b\u0430 \u0434\u043e 10000 \u0432 \u0441\u0442\u043e\u043b\u0431\u0438\u043a\n\n\nclass PrimeNumbers:\n\n def __init__(self, number): # n=10, \u043f\u0440\u0435\u0434\u0435\u043b\n self.current_number = 1 # \u0442\u0435\u043a\u0443\u0449\u0435\u0435 \u0447\u0438\u0441\u043b\u043e\n self.prime_numbers = [] # \u0441\u043f\u0438\u0441\u043e\u043a \u043f\u0440\u043e\u0441\u0442\u044b\u0445 \u0447\u0438\u0441\u0435\u043b\n self.max_number = number # \u043c\u0430\u043a\u0441\u0438\u043c\u0430\u043b\u044c\u043d\u043e\u0435 \u0447\u0438\u0441\u043b\u043e\n\n def __iter__(self):\n return self\n\n def get_prime(self):\n for prime in self.prime_numbers:\n if self.current_number % prime == 0:\n return False\n else:\n return True\n\n def __next__(self):\n self.current_number += 1\n if self.current_number <= self.max_number:\n while not self.get_prime():\n if self.current_number < self.max_number:\n self.current_number += 1\n else:\n raise StopIteration()\n else:\n self.prime_numbers.append(self.current_number)\n return self.current_number\n\n\n# prime_number_iterator = PrimeNumbers(number=10000)\n# for number in prime_number_iterator:\n# print(number)\n# \u0427\u0430\u0441\u0442\u044c 2\n# \u0422\u0435\u043f\u0435\u0440\u044c \u043d\u0443\u0436\u043d\u043e \u0441\u043e\u0437\u0434\u0430\u0442\u044c \u0433\u0435\u043d\u0435\u0440\u0430\u0442\u043e\u0440, \u043a\u043e\u0442\u043e\u0440\u044b\u0439 \u0432\u044b\u0434\u0430\u0435\u0442 \u043f\u043e\u0441\u043b\u0435\u0434\u043e\u0432\u0430\u0442\u0435\u043b\u044c\u043d\u043e\u0441\u0442\u044c \u043f\u0440\u043e\u0441\u0442\u044b\u0445 \u0447\u0438\u0441\u0435\u043b \u0434\u043e n\n# \u0420\u0430\u0441\u043f\u0435\u0447\u0430\u0442\u0430\u0442\u044c \u0432\u0441\u0435 \u043f\u0440\u043e\u0441\u0442\u044b\u0435 \u0447\u0438\u0441\u043b\u0430 \u0434\u043e 10000 \u0432 \u0441\u0442\u043e\u043b\u0431\u0438\u043a\n\n\ndef true_happy_number(number):\n number = list(map(int, (str(number))))\n middle_number = len(number) // 2\n left_part = sum(number[:middle_number])\n right_part = sum(number[-middle_number:])\n return left_part == right_part and len(number) > 1\n\n\ndef true_reverse_number(number):\n number = str(number)\n reverse_number = ''.join(reversed(number))\n return number == reverse_number and len(number) > 1\n\n\ndef true_repdigit_number(number):\n number_check = set(str(number))\n return len(number_check) == 1 and len(str(number)) > 1\n\n\ndef get_prime(current_number, numbers):\n for prime in numbers:\n if current_number % prime == 0:\n return False\n else:\n return True\n\n\ndef prime_numbers_generator(n):\n prime_numbers = []\n for number in range(2, n + 1):\n if get_prime(current_number=number, numbers=prime_numbers):\n prime_numbers.append(number)\n if true_repdigit_number(number):\n yield f'repdigit number {number}'\n elif true_reverse_number(number):\n yield f'reverse number {number}'\n elif true_happy_number(number):\n yield f'happy number {number}'\n else:\n yield f'just prime number {number}'\n\n\n# for number in prime_numbers_generator(n=10):\n# print(number)\n\n\n# \u0427\u0430\u0441\u0442\u044c 3\n# \u041d\u0430\u043f\u0438\u0441\u0430\u0442\u044c \u043d\u0435\u0441\u043a\u043e\u043b\u044c\u043a\u043e \u0444\u0443\u043d\u043a\u0446\u0438\u0439-\u0444\u0438\u043b\u044c\u0442\u0440\u043e\u0432, \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u0432\u044b\u0434\u0430\u0435\u0442 True, \u0435\u0441\u043b\u0438 \u0447\u0438\u0441\u043b\u043e:\n# 1) \"\u0441\u0447\u0430\u0441\u0442\u043b\u0438\u0432\u043e\u0435\" \u0432 \u043e\u0431\u044b\u0434\u0435\u043d\u043d\u043e\u043c \u043f\u043e\u043d\u0438\u043c\u0430\u043d\u0438\u0438\u0438 - \u0441\u0443\u043c\u043c\u0430 \u043f\u0435\u0440\u0432\u044b\u0445 \u0446\u0438\u0444\u0440 \u0440\u0430\u0432\u043d\u0430 \u0441\u0443\u043c\u043c\u0435 \u043f\u043e\u0441\u043b\u0435\u0434\u043d\u0438\u0445\n# \u0415\u0441\u043b\u0438 \u0447\u0438\u0441\u043b\u043e \u0438\u043c\u0435\u0435\u0442 \u043d\u0435\u0447\u0435\u0442\u043d\u043e\u0435 \u0447\u0438\u0441\u043b\u043e \u0446\u0438\u0444\u0440 (\u043d\u0430\u043f\u0440\u0438\u043c\u0435\u0440 727 \u0438\u043b\u0438 92083),\n# \u0442\u043e \u0434\u043b\u044f \u0432\u044b\u0447\u0438\u0441\u043b\u0435\u043d\u0438\u044f \"\u0441\u0447\u0430\u0441\u0442\u043b\u0438\u0432\u043e\u0441\u0442\u0438\" \u0431\u0440\u0430\u0442\u044c \u0440\u0430\u0432\u043d\u043e\u0435 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0446\u0438\u0444\u0440 \u0441 \u043d\u0430\u0447\u0430\u043b\u0430 \u0438 \u043a\u043e\u043d\u0446\u0430:\n# 727 -> 7(2)7 -> 7 == 7 -> True\n# 92083 -> 92(0)83 -> 9+2 == 8+3 -> True\n# 2) \"\u043f\u0430\u043b\u0438\u043d\u0434\u0440\u043e\u043c\u043d\u043e\u0435\" - \u043e\u0434\u0438\u043d\u0430\u043a\u043e\u0432\u043e \u0447\u0438\u0442\u0430\u044e\u0449\u0435\u0435\u0441\u044f \u0432 \u043e\u0431\u043e\u0438\u0445 \u043d\u0430\u043f\u0440\u0430\u0432\u043b\u0435\u043d\u0438\u044f\u0445. \u041d\u0430\u043f\u0440\u0438\u043c\u0435\u0440 723327 \u0438 101\n# 3) \u043f\u0440\u0438\u0434\u0443\u043c\u0430\u0442\u044c \u0441\u0432\u043e\u044e (https://clck.ru/GB5Fc \u0432 \u043f\u043e\u043c\u043e\u0449\u044c)\n#\n# \u041f\u043e\u0434\u0443\u043c\u0430\u0442\u044c, \u043a\u0430\u043a \u043c\u043e\u0436\u043d\u043e \u043f\u0440\u0438\u043c\u0435\u043d\u0438\u0442\u044c \u0444\u0443\u043d\u043a\u0446\u0438\u0438-\u0444\u0438\u043b\u044c\u0442\u0440\u044b \u043a \u043f\u043e\u043b\u0443\u0447\u0435\u043d\u043d\u043e\u0439 \u043f\u043e\u0441\u043b\u0435\u0434\u043e\u0432\u0430\u0442\u0435\u043b\u044c\u043d\u043e\u0441\u0442\u0438 \u043f\u0440\u043e\u0441\u0442\u044b\u0445 \u0447\u0438\u0441\u0435\u043b\n# \u0434\u043b\u044f \u043f\u043e\u043b\u0443\u0447\u0435\u043d\u0438\u044f, \u043a \u043f\u0440\u0438\u043c\u0435\u0440\u0443: \u043f\u0440\u043e\u0441\u0442\u044b\u0445 \u0441\u0447\u0430\u0441\u0442\u043b\u0438\u0432\u044b\u0445 \u0447\u0438\u0441\u0435\u043b, \u043f\u0440\u043e\u0441\u0442\u044b\u0445 \u043f\u0430\u043b\u0438\u043d\u0434\u0440\u043e\u043c\u043d\u044b\u0445 \u0447\u0438\u0441\u0435\u043b,\n# \u043f\u0440\u043e\u0441\u0442\u044b\u0445 \u0441\u0447\u0430\u0441\u0442\u043b\u0438\u0432\u044b\u0445 \u043f\u0430\u043b\u0438\u043d\u0434\u0440\u043e\u043c\u043d\u044b\u0445 \u0447\u0438\u0441\u0435\u043b \u0438 \u0442\u0430\u043a \u0434\u0430\u043b\u0435\u0435. \u041f\u0440\u0438\u0434\u0443\u043c\u0430\u0442\u044c \u043d\u0435 \u043c\u0435\u043d\u0435\u0435 2\u0445 \u0441\u043f\u043e\u0441\u043e\u0431\u043e\u0432.\n#\n# \u041f\u043e\u0434\u0441\u043a\u0430\u0437\u043a\u0430: \u0432\u043e\u0437\u043c\u043e\u0436\u043d\u043e, \u043d\u0443\u0436\u043d\u043e \u0431\u0443\u0434\u0435\u0442 \u0434\u043e\u0431\u0430\u0432\u0438\u0442\u044c \u043f\u0430\u0440\u0430\u043c\u0435\u0442\u0440 \u0432 \u0438\u0442\u0435\u0440\u0430\u0442\u043e\u0440/\u0433\u0435\u043d\u0435\u0440\u0430\u0442\u043e\u0440.\n\ndef true_happy_number(func):\n def decorator_1(max_number):\n for number in func(max_number):\n check_number = list(map(int, (str(number))))\n middle_number = len(check_number) // 2\n left_part = sum(check_number[:middle_number])\n right_part = sum(check_number[-middle_number:])\n if left_part == right_part and len(check_number) > 1:\n yield f'{number} \u043f\u0440\u043e\u0441\u0442\u043e\u0435 \u0447\u0438\u0441\u043b\u043e \u0441\u0447\u0430\u0441\u0442\u044c\u044f!'\n else:\n continue\n\n return decorator_1\n\n\ndef true_reverse_number(func):\n def decorator_2(max_number):\n for number in func(max_number):\n number = str(number)\n reverse_number = ''.join(reversed(number))\n if number == reverse_number and len(number) > 1:\n yield f'{number} \u043f\u0440\u043e\u0441\u0442\u043e\u0435 \u043f\u0430\u043b\u0438\u043d\u0434\u0440\u043e\u043c\u043d\u043e\u0435 \u0447\u0438\u0441\u043b\u043e!'\n else:\n continue\n\n return decorator_2\n\n\ndef true_repdigit_number(func):\n def decorator_3(max_number):\n for number in func(max_number):\n number_check = set(str(number))\n if len(number_check) == 1 and len(str(number)) > 1:\n yield f'{number} \u044d\u0442\u043e \u043f\u0440\u043e\u0441\u0442\u043e\u0435 \u0447\u0438\u0441\u043b\u043e \u0441\u043e\u0441\u0442\u043e\u0438\u0442 \u0438\u0437 \u043f\u043e\u0432\u0442\u043e\u0440\u044f\u044e\u0449\u0438\u0445\u0441\u044f \u0446\u0438\u0444\u0440!'\n else:\n continue\n\n return decorator_3\n\n\ndef get_prime(current_number, numbers):\n for prime in numbers:\n if current_number % prime == 0:\n return False\n else:\n return True\n\n\n@true_happy_number\n# @true_reverse_number\n# @true_repdigit_number\ndef prime_numbers_generator(max_number):\n prime_numbers = []\n for number in range(2, max_number + 1):\n if get_prime(current_number=number, numbers=prime_numbers):\n prime_numbers.append(number)\n yield number\n\n\nfor number in prime_numbers_generator(max_number=5555):\n print(number)\n"} {"blob_id": "5b9e45571f4c362de51b42fd9d2e71eab148f990", "repo_name": "victor0198utm/LFPC", "path": "/LAB 1/Lab 1 - generating_words.py", "length_bytes": 1534, "score": 4.0, "int_score": 4, "content": "# This programs generates all possible words with length less than 20 characters\n# and compare them with the searched words\n\n# grammar declaration\nd = dict()\nd[\"S\"] = \"aD\"\nd[\"D\"] = \"dE,bJ,aE\"\nd[\"J\"] = \"cS\"\nd[\"E\"] = \"e,aE\"\n\n# words to search for\nsearch = [\"adaaae\", \"abcade\", \"abcadae\", \"abcabcadaae\", \"aaaaae\"]\n\ndef generate(letter, interm_str):\n # make an array with possible replacements for nonterminal characters\n try:\n options = d[letter].split(\",\")\n except:\n options = d[letter]\n\n # loop through replacement options\n for i in range(len(options)):\n # limit the words at 20 charaters\n if len(interm_str)>20:\n return\n \n temp_str = \"\"\n for idx_letter in range(len(interm_str)):\n # keep the terminal characters and replace the nonterminal ones \n if letter == interm_str[idx_letter]:\n temp_str += options[i]\n else:\n temp_str += interm_str[idx_letter]\n\n # search for new nonterminal characters\n upper_letter = \"\"\n for up_letter in temp_str:\n if up_letter == up_letter.upper():\n upper_letter = up_letter\n \n if len(upper_letter) != 0:\n generate(upper_letter, temp_str)\n # there aren't any nontermial characters\n else:\n if temp_str in search:\n print(temp_str)\n\n\nprint(\"Founded words:\") \n# the start string is \"S\" and the character to be replaced is \"S\"\ngenerate(\"S\", \"S\")"} {"blob_id": "c214f2f27579e5e7140bc71296c2273ae81e1fd4", "repo_name": "mauriciodotso/quantcoin", "path": "/quantcoin/transaction.py", "length_bytes": 5244, "score": 3.609375, "int_score": 4, "content": "import binascii\nimport hashlib\nimport json\n\nfrom ecdsa import SECP256k1, SigningKey, VerifyingKey\n\n\nclass Transaction(object):\n \"\"\"\n A Transaction represents the trade of the coins in the network.\n Only one sender is allowed by transaction, but as many as needed receivers\n are allowed. A transaction is only valid if the amount sent cant be\n verified to be owned by the sender. This process is made by the miners when\n building new blocks and the rest of the network when accepting a new block.\n\n An special kind of transaction has no sender. This transaction represents\n the coin creation. This transaction can only be made by a miner when\n creating a new block. The amount of coins allowed in this kind of\n transaction is limited by the nodes in the network when accepting a new\n block.\n \"\"\"\n\n def __init__(self, from_wallet, to_wallets, signature=None, public_key=None):\n \"\"\"\n\n :param from_wallet: the address of the sender of the money\n :param to_wallets: the tuples with addresses of the receivers and amounts\n received. There is a special to_wallet tuple with a None wallet\n address, this case is the commission to the miner. The commission\n is optional and must be put as the first on to_wallet list.\n :param signature: The transaction's proof of that it's from the 'from_wallet'.\n :param public_key: The transaction's public key encoded.\n \"\"\"\n self._from_wallet = from_wallet\n if not isinstance(to_wallets, list):\n to_wallets = [to_wallets]\n self._to_wallets = to_wallets\n self._signature = signature\n self._public_key = public_key\n\n def json(self):\n \"\"\"\n Converts the object to a json\n \"\"\"\n dictionary = {\n 'body': {\n 'from': self.from_wallet(),\n 'to': self.to_wallets(),\n },\n 'signature': self.signature(),\n 'public_key': self.public_key()\n }\n\n return dictionary\n\n def from_wallet(self):\n \"\"\"\n Retrieves the sender of the transaction\n \"\"\"\n return self._from_wallet\n\n def to_wallets(self):\n \"\"\"\n Retrieves the receivers of the transaction\n \"\"\"\n return self._to_wallets\n\n def commission(self):\n \"\"\"\n :return: The commission value offered by this transaction.\n \"\"\"\n if self._to_wallets[0][0] is None:\n return self._to_wallets[0][1]\n else:\n return 0.0\n\n def is_creation_transaction(self):\n \"\"\"\n True if this transaction corresponds to a money creation transaction.\n This kind of transaction has no sender, thus the money is created. The\n receivers of this transaction usually would be the ones responsible\n for the block calculation.\n \"\"\"\n return self.from_wallet() is None\n\n def amount_spent(self):\n \"\"\"\n The amount spent on this transaction.\n \"\"\"\n total_amount = 0.0\n for _, amount in self.to_wallets():\n total_amount += amount\n\n return total_amount\n\n def prepare_for_signature(self):\n \"\"\"\n Obtains only the data of the transaction that should be signed.\n \"\"\"\n data = {\n 'from': self.from_wallet(),\n 'to': self.to_wallets(),\n }\n\n return json.dumps(data)\n\n def sign(self, private_key_encoded, public_key_encoded):\n \"\"\"\n Does the transaction signature\n :param private_key_encoded: The private key encoded in Base64\n :param public_key_encoded: The public key encoded in Base64\n \"\"\"\n to_sign = self.prepare_for_signature()\n priv_key = SigningKey.from_string(binascii.a2b_base64(private_key_encoded),\n curve=SECP256k1)\n signature = priv_key.sign(to_sign, hashfunc=hashlib.sha256)\n self.signed(binascii.b2a_base64(signature), public_key_encoded)\n\n def signed(self, signature, public_key):\n \"\"\"\n Stores the signature into the transaction. After this the transaction\n is ready for inclusion in the blockchain.\n \"\"\"\n self._signature = signature\n self._public_key = public_key\n\n def verify(self):\n \"\"\"\n Verifies the transaction proof of authenticity\n :return: True if the transaction is authentic\n \"\"\"\n if self._public_key is not None:\n to_verify = self.prepare_for_signature()\n pub_key = VerifyingKey.from_string(binascii.a2b_base64(self._public_key),\n curve=SECP256k1)\n return pub_key.verify(signature=binascii.a2b_base64(self.signature()),\n data=to_verify,\n hashfunc=hashlib.sha256)\n else:\n return False\n\n def signature(self):\n \"\"\"\n Obtains the signature of this transaction\n \"\"\"\n return self._signature\n\n def public_key(self):\n \"\"\"\n Obtains the public key of the transaction\n \"\"\"\n return self._public_key\n"} {"blob_id": "8c7bab559000d0acb6cf8f5c6a9f7e437174c880", "repo_name": "mosmeh/calculator-game-solver", "path": "/calc.py", "length_bytes": 2459, "score": 3.546875, "int_score": 4, "content": "from itertools import product\n\nclass Operation:\n def __init__(self):\n pass\n\n def apply(self, n):\n raise NotImplementedError()\n\n def __str__(self):\n raise NotImplementedError()\n\nclass Append(Operation):\n def __init__(self, n):\n self.n = n\n \n def apply(self, n):\n return n * 10 + (1 if n >= 0 else -1) * self.n\n\n def __str__(self):\n return str(self.n)\n\nclass Add(Operation):\n def __init__(self, n):\n self.n = n\n \n def apply(self, n):\n return n + self.n\n\n def __str__(self):\n return '{}{}'.format('+' if self.n > 0 else '', self.n)\n\nclass Multiply(Operation):\n def __init__(self, n):\n self.n = n\n \n def apply(self, n):\n return self.n * n\n \n def __str__(self):\n return 'x{}'.format(self.n)\n\nclass Divide(Operation):\n def __init__(self, n):\n self.n = n\n\n def apply(self, n):\n return n / self.n\n \n def __str__(self):\n return '/{}'.format(self.n)\n\nclass Replace(Operation):\n def __init__(self, before, after):\n self.before = str(before)\n self.after = str(after)\n \n def apply(self, n):\n return float(str(n).replace(self.before, self.after))\n \n def __str__(self):\n return '{}=>{}'.format(self.before, self.after)\n\nclass Power(Operation):\n def __init__(self, power):\n self.power = power\n\n def apply(self, n):\n return n ** self.power \n \n def __str__(self):\n return 'x^{}'.format(self.power)\n\nclass Reverse(Operation):\n @staticmethod\n def apply(n):\n return (1 if n > 0 else -1) * int(reversed(str(abs(n))))\n \n @staticmethod\n def __str__():\n return 'Reverse'\n\nclass Negate(Operation):\n @staticmethod\n def apply(n):\n return -n\n \n @staticmethod\n def __str__():\n return '+/-'\n\nclass Sum(Operation):\n @staticmethod\n def apply(n):\n s = 0\n while n > 0:\n s += n % 10\n n = int(n / 10)\n return s\n \n @staticmethod\n def __str__():\n return 'SUM'\n\nclass Backspace(Operation):\n @staticmethod\n def apply(n):\n return int(n / 10)\n \n @staticmethod\n def __str__():\n return '<<'\n\ndef solve(moves, init, goal, num_moves):\n for pattern in product(moves, repeat=num_moves):\n n = init\n for move in pattern:\n n = move.apply(n)\n if n == goal:\n return pattern\n"} {"blob_id": "393a5047d096cd19734491d0321ca9a98bec8dfc", "repo_name": "rishabhzn200/Leetcode", "path": "/RotateList.py", "length_bytes": 1168, "score": 3.734375, "int_score": 4, "content": "\"\"\"\n61. Rotate List\n\nGiven a list, rotate the list to the right by k places, where k is non-negative.\n\n\nExample:\n\nGiven 1->2->3->4->5->NULL and k = 2,\n\nreturn 4->5->1->2->3->NULL.\n\"\"\"\n\n\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def rotateRight(self, head, k):\n \"\"\"\n :type head: ListNode\n :type k: int\n :rtype: ListNode\n \"\"\"\n\n if head == None or head.next == None or k == 0:\n return head\n\n c = 0\n\n x = head\n prevL1 = None\n while True:\n c += 1\n\n if x.next == None:\n x.next = head\n prevL1 = x\n break\n x = x.next\n\n if k > c:\n k = k % c\n\n l1 = head\n\n prev = prevL1\n\n while k != 0:\n prevL1 = l1\n l1 = l1.next\n k -= 1\n\n curr = head\n\n while l1 != head:\n prev = curr\n curr = curr.next\n l1 = l1.next\n\n head = curr\n prev.next = None\n\n return head\n "} {"blob_id": "947bbafea1323b45eaea08f6883388639d6d7b66", "repo_name": "xizhang77/LeetCode", "path": "/Array/311-sparse-matrix-multiplication.py", "length_bytes": 639, "score": 3.609375, "int_score": 4, "content": "# -*- coding: utf-8 -*-\n\n'''\nhttps://leetcode.com/problems/sparse-matrix-multiplication/\n'''\n\nclass Solution(object):\n def multiply(self, A, B):\n \"\"\"\n :type A: List[List[int]]\n :type B: List[List[int]]\n :rtype: List[List[int]]\n \"\"\"\n m, n = len(A), len(B[0])\n \n res = [ [0]*n for _ in range(m) ]\n \n for i in range(m):\n for k in range( len(A[0]) ):\n if A[i][k] != 0:\n for j in range( n ):\n if B[k][j] != 0:\n res[i][j] += A[i][k]*B[k][j]\n \n \n return res"} {"blob_id": "0e14edb69e384ecb19c62b69ebe7fb09a1fdf813", "repo_name": "arsaikia/Data_Structures_and_Algorithms", "path": "/Data Structures and Algorithms/Python/LeetCode/Contiguous Array.py", "length_bytes": 1230, "score": 4.0625, "int_score": 4, "content": "'''\n\ud83c\udf88\ud83c\udf88\nGiven a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.\n\nExample 1:\nInput: [0,1]\nOutput: 2\nExplanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1.\n\nExample 2:\nInput: [0,1,0]\nOutput: 2\nExplanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.\n\nNote: The length of the given binary array will not exceed 50,000.\n'''\nfrom typing import List\n\n\nclass Solution:\n def findMaxLength(self, nums: List[int]) -> int:\n\n if(len(nums) <= 1):\n return 0\n\n globalMax = 0\n myDict = {0: -1}\n sums = 0\n\n for i in range(len(nums)):\n if(nums[i] == 0):\n nums[i] = -1\n sums = sums + nums[i]\n if(sums in myDict.keys()):\n globalMax = max(globalMax, i-myDict.get(sums))\n else:\n myDict[sums] = i\n return globalMax\n\n\nif __name__ == \"__main__\":\n # myFile = pd.read_csv(\"../Test Data/ContiguousArray.csv\", sep=',')\n # print(myFile)\n sol = Solution()\n Input = [0, 1, 1, 0, 1, 1, 1, 0]\n Input1 = [0, 0, 1, 0, 0, 0, 1, 1]\n print(f'Max Length is: {sol.findMaxLength([0,0,1])}')\n"} {"blob_id": "3e6727e19be5a1d464a4f35ad3cd77df46408663", "repo_name": "xyzhang7/Machine-Learning-Projects", "path": "/Project 2/ex1.py", "length_bytes": 3480, "score": 3.875, "int_score": 4, "content": "import numpy as np\nfrom sklearn.decomposition import PCA\nimport matplotlib.pyplot as plt\n\ndef create_data(x1, x2, x3):\n x4 = np.multiply(x2, x2)\n x5 = 10 * x1 + 10\n x6 = -1 * x2 / 2\n X = np.hstack((x1, x2, x3, x4, x5, x6))\n return X\n\ndef pca(X):\n '''\n # PCA step by step\n # 1. normalize matrix X\n # 2. compute the covariance matrix of the normalized matrix X\n # 3. do the eigenvalue decomposition on the covariance matrix\n # If you do not remember Eigenvalue Decomposition, please review the linear\n # algebra\n # In this assignment, we use the ``unbiased estimator'' of covariance. You\n # can refer to this website for more information\n # http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.cov.html\n # Actually, Singular Value Decomposition (SVD) is another way to do the\n # PCA, if you are interested, you can google SVD.\n # YOUR CODE HERE!\n '''\n norm_X = X - np.mean(X, axis=0)\n cova = np.cov(norm_X.T)\n D, V = np.linalg.eig(cova)\n index = np.argsort(D)[::-1]\n V = V.T[index]\n D = D[index]\n ####################################################################\n # here V is the matrix containing all the eigenvectors, D is the\n # column vector containing all the corresponding eigenvalues.\n return [V, D]\n\n\ndef main():\n N = 1000\n shape = (N, 1)\n x1 = np.random.normal(0, 1, shape) # samples from normal distribution\n x2 = np.random.exponential(10.0, shape) # samples from exponential distribution\n x3 = np.random.uniform(-100, 100, shape) # uniformly sampled data points\n X = create_data(x1, x2, x3)\n\n ####################################################################\n # Use the definition in the lecture notes,\n # 1. perform PCA on matrix X\n # 2. plot the eigenvalues against the order of eigenvalues,\n # 3. plot POV v.s. the order of eigenvalues\n # YOUR CODE HERE!\n V, D = pca(X)\n print([V, D])\n # [array([[1.70773519e-04, -2.16410974e-02, 4.21111727e-04,\n # -9.99705685e-01, 1.70773519e-03, 1.08205487e-02],\n # [-6.13880620e-04, -7.33365948e-04, -9.99980548e-01,\n # -4.11974521e-04, -6.13880620e-03, 3.66682974e-04],\n # [-9.95012593e-02, 2.56403373e-03, 6.16777563e-03,\n # -1.78349842e-03, -9.95012593e-01, -1.28201686e-03],\n # [2.88952443e-04, 8.94161367e-01, -8.27650102e-04,\n # -2.41907759e-02, 2.88952443e-03, -4.47080684e-01],\n # [9.84870275e-01, -6.37665218e-02, 1.39783075e-17,\n # -1.62840542e-16, -9.84870275e-02, -1.27533044e-01],\n # [1.00428801e-01, 4.44929926e-01, 4.00672210e-17,\n # 4.23807620e-16, -1.00428801e-02, 8.89859853e-01]]),\n # array([1.80469530e+05, 3.27681920e+03, 9.24028915e+01, 2.17950420e+01,\n # 7.11550639e-13, 7.13997068e-14])]\n\n order = [i for i in range(1, len(V)+1)]\n plt.plot(order, D, \"o-\")\n plt.xlabel(\"order of eigenvalue\")\n plt.ylabel(\"eigenvalue\")\n plt.title(\"eigenvalues v.s. the order of eigenvalues\")\n plt.show()\n summ = sum(D)\n cumsum = []\n pre = 0\n for i, e in enumerate(D):\n cumsum.append((pre+e)/summ)\n pre += e\n plt.plot(order,cumsum,\"o-\")\n plt.ylabel(\"POV\")\n plt.xlabel(\"order of eigenvalue\")\n plt.title(\"POV v.s the order of eigenvalues\")\n plt.show()\n ####################################################################\n\n\nif __name__ == '__main__':\n main()\n\n"} {"blob_id": "c4c30347cf0e6b6a1dbfae0684adb6a0eeb743bb", "repo_name": "pkdism/leetcode", "path": "/july-leetcoding-challenge/d24-all-paths-from-source-to-target.py", "length_bytes": 661, "score": 3.671875, "int_score": 4, "content": "\"\"\"\nGiven a directed, acyclic graph of N nodes. Find all possible paths from node 0 to node N-1, and return them in any order.\nThe graph is given as follows: the nodes are 0, 1, ..., graph.length - 1. graph[i] is a list of all nodes j for which the edge (i, j) exists.\n\"\"\"\n\n\nclass Solution:\n def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:\n def explore(ls):\n if ls[-1] == n-1:\n res.append(ls)\n return\n for x in graph[ls[-1]]:\n explore(ls + [x])\n \n \n n = len(graph)\n res = []\n explore([0])\n return res"} {"blob_id": "4b98873539cc53ab1fcedf5a9d6113235a03ccdb", "repo_name": "kameranis/Project_Euler", "path": "/Problem 34 - Digit Factorials/digit_factorials.py", "length_bytes": 452, "score": 3.546875, "int_score": 4, "content": "\"\"\"\nDigit Factorials Euler Problem 34\nThe sum of the factorials of the digits is equal to the number itself\nKonstantinos Ameranis 27/1/2015\n\"\"\"\n\nimport math\nimport numpy as np\n\nfact = np.array(map(math.factorial, range(10)))\n\ndef main(number):\n facts = map(lambda x: sum(fact[map(int, str(x))]), np.arange(10, number))\n print sum(np.arange(10, number)[np.where([facts[i-10] == i for i in np.arange(10, number)])])\n\nif __name__ == '__main__':\n main(1000000)\n\n"} {"blob_id": "d5f354c5555cc39250d9187f2434a4f5f4aae374", "repo_name": "IvanWoo/coding-interview-questions", "path": "/puzzles/strange_printer.py", "length_bytes": 1167, "score": 4.125, "int_score": 4, "content": "# https://leetcode.com/problems/strange-printer/\n\"\"\"\nThere is a strange printer with the following two special requirements:\n\nThe printer can only print a sequence of the same character each time.\nAt each turn, the printer can print new characters starting from and ending at any places, and will cover the original existing characters.\nGiven a string consists of lower English letters only, your job is to count the minimum number of turns the printer needed in order to print it.\n\n\nExample 1:\nInput: \"aaabbb\"\nOutput: 2\nExplanation: Print \"aaa\" first and then print \"bbb\".\n\nExample 2:\nInput: \"aba\"\nOutput: 2\nExplanation: Print \"aaa\" first and then print \"b\" from the second place of the string, which will cover the existing character 'a'.\nHint: Length of the given string will not exceed 100.\n\"\"\"\nfrom functools import lru_cache\n\n\ndef strange_printer(s: str) -> int:\n @lru_cache(None)\n def helper(s):\n if not s:\n return 0\n cost = helper(s[:-1]) + 1\n for i, c in enumerate(s[:-1]):\n if c == s[-1]:\n cost = min(cost, helper(s[: i + 1]) + helper(s[i + 1 : -1]))\n return cost\n\n return helper(s)\n"} {"blob_id": "1776355c34a6f43dbcd7e8d0e27c494035ee56d7", "repo_name": "sidhumeher/PyPractice", "path": "/Coding/PalindromString.py", "length_bytes": 976, "score": 3.96875, "int_score": 4, "content": "'''\r\nCreated on Dec 31, 2018\r\n\r\n@author: siddardha.teegela\r\n'''\r\n\r\n# Complete the palindromeIndex function below.\r\ndef palindromeIndex(s):\r\n if s[::-1] == s:\r\n return -1\r\n #substr = ''\r\n for index in range(0,len(s)):\r\n #substr = \"\"\r\n if index == 0:\r\n substr1 = \"\"\r\n substr1 = s[index+1:]\r\n print('Inside first if',substr1)\r\n if substr1[::-1] == substr1:\r\n return index\r\n else:\r\n substr2 = \"\"\r\n substr2 = s[:index]+s[index+1:]\r\n print('Inside second if',substr2)\r\n print('rev',substr2[::-1])\r\n if substr2[::-1] == substr2:\r\n return index\r\n \r\n return -1\r\n\r\nif __name__ == '__main__':\r\n result = palindromeIndex('aaab')\r\n print(result)\r\n '''\r\n result = palindromeIndex('baa')\r\n print(result)\r\n result = palindromeIndex('aaa')\r\n print(result)\r\n '''"} {"blob_id": "db57e14816dbc927cbcf3cc96538c631614d93b1", "repo_name": "oxhead/CodingYourWay", "path": "/src/lt_234.py", "length_bytes": 2396, "score": 4.03125, "int_score": 4, "content": "\"\"\"\nhttps://leetcode.com/problems/palindrome-linked-list\n\nRelated:\n - lt_9_palindrome-number\n - lt_125_valid-palindrome\n - lt_206_reverse-linked-list\n\"\"\"\n\n\"\"\"\nGiven a singly linked list, determine if it is a palindrome.\n\nFollow up:\nCould you do it in O(n) time and O(1) space?\n\"\"\"\n\nfrom utils import to_linked_list\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n def isPalindrome(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: bool\n \"\"\"\n # Time: O(n)\n # Space: O(1)\n # Hints:\n # 1) Find the middle point with fast/slow pointers\n # 2) Reverse the second half of the linked list\n # 3) Compare the two sub-lists\n # Notes:\n # 1) Better to find the middle point from a dummy node (before head), which avoids the two-node problem.\n def find_middle_node(node):\n slow = fast = node\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow\n def reverse(node):\n previous = None\n while node:\n node.next, previous, node = previous, node, node.next\n return previous\n\n # this handles two nodes cases becasue head2 will compare with head at least once\n middle = find_middle_node(head)\n head2 = reverse(middle)\n while head2:\n if head.val != head2.val: return False\n head = head.next\n head2 = head2.next\n return True\n\n def isPalindrome_naive(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: bool\n \"\"\"\n stack = []\n tmp = head\n while tmp:\n stack.append(tmp.val)\n tmp = tmp.next\n while head:\n if len(stack) == 0: return False\n if stack.pop() != head.val: return False\n head = head.next\n return True\n\n\nif __name__ == '__main__':\n test_cases = [\n ([], True),\n ([1], True),\n ([1, 2, 1], True),\n ([1, 1], True),\n ([1, 2], False),\n ]\n\n for test_case in test_cases:\n print('case:', test_case)\n output = Solution().isPalindrome(to_linked_list(test_case[0]))\n print('output:', output)\n assert output == test_case[1]\n\n"} {"blob_id": "5faeed47ff8cd54ea8f02848b363af0e6b827710", "repo_name": "cjxnew/Programming-Training", "path": "/\u5251\u6307offer(Sword for offer)/\u4e8c\u53c9\u6811\u7684\u4e0b\u4e00\u4e2a\u7ed3\u70b9.py", "length_bytes": 635, "score": 3.78125, "int_score": 4, "content": "# \u7ed9\u5b9a\u4e00\u4e2a\u4e8c\u53c9\u6811\u548c\u5176\u4e2d\u7684\u4e00\u4e2a\u7ed3\u70b9\uff0c\u8bf7\u627e\u51fa\u4e2d\u5e8f\u904d\u5386\u987a\u5e8f\u7684\u4e0b\u4e00\u4e2a\u7ed3\u70b9\u5e76\u4e14\u8fd4\u56de\u3002\n# \u6ce8\u610f\uff0c\u6811\u4e2d\u7684\u7ed3\u70b9\u4e0d\u4ec5\u5305\u542b\u5de6\u53f3\u5b50\u7ed3\u70b9\uff0c\u540c\u65f6\u5305\u542b\u6307\u5411\u7236\u7ed3\u70b9\u7684\u6307\u9488\u3002\n\nclass Solution:\n def GetNext(self, pNode):\n # write code here\n if not pNode:\n return pNode\n if pNode.right:\n left1=pNode.right\n while left1.left:\n left1=left1.left\n return left1\n p=pNode\n while pNode.next:\n tmp=pNode.next\n if tmp.left==pNode:\n return tmp\n pNode=tmp\n \n"} {"blob_id": "4e67c28d126d590c4b53b8608f81140c0d5494e7", "repo_name": "frankhjwx/osu-storyboard-engine", "path": "/Storyboard Engine/BeatmapParser/curve.py", "length_bytes": 5475, "score": 3.640625, "int_score": 4, "content": "import math\n\n\n# Translated from JavaScript to Python by Awlex\n\ndef is_point_in_circle(point, center, radius):\n return distance_points(point, center) <= radius\n\n\ndef distance_points(p1, p2):\n x = (p1[0] - p2[0])\n y = (p1[1] - p2[1])\n return math.sqrt(x * x + y * y)\n\n\ndef distance_from_points(array):\n distance = 0\n\n for i in range(1, len(array)):\n distance += distance_points(array[i], array[i - 1])\n\n return distance\n\n\ndef angle_from_points(p1, p2):\n return math.atan2(p2[1] - p1[1], p2[0] - p1[0])\n\n\ndef cart_from_pol(r, teta):\n x2 = (r * math.cos(teta))\n y2 = (r * math.sin(teta))\n\n return [x2, y2]\n\n\ndef point_at_distance(array, distance):\n # needs a serious cleanup !\n global new_distance, i\n current_distance = 0\n\n if len(array) < 2:\n return [0, 0, 0, 0]\n\n if distance == 0:\n angle = angle_from_points(array[0], array[1])\n return [array[0][0], array[0][1], angle, 0]\n\n if distance_from_points(array) <= distance:\n angle = angle_from_points(array[len(array) - 2], array[len(array) - 1])\n return [array[len(array) - 1][0],\n array[len(array) - 1][1],\n angle,\n len(array) - 2]\n\n for i in range(len(array) - 2):\n x = (array[i][0] - array[i + 1][0])\n y = (array[i][1] - array[i + 1][1])\n\n new_distance = (math.sqrt(x * x + y * y))\n current_distance += new_distance\n\n if distance <= current_distance:\n break\n\n current_distance -= new_distance\n\n if distance == current_distance:\n coord = [array[i][0], array[i][1]]\n angle = angle_from_points(array[i], array[i + 1])\n else:\n angle = angle_from_points(array[i], array[i + 1])\n cart = cart_from_pol((distance - current_distance), angle)\n\n if array[i][0] > array[i + 1][0]:\n coord = [(array[i][0] - cart[0]), (array[i][1] - cart[1])]\n else:\n coord = [(array[i][0] + cart[0]), (array[i][1] + cart[1])]\n\n return [coord[0], coord[1], angle, i]\n\n\ndef cpn(p, n):\n if p < 0 or p > n:\n return 0\n p = min(p, n - p)\n out = 1\n for i in range(1, p + 1):\n out = out * (n - p + i) / i\n return out\n\n\ndef array_values(array):\n out = []\n for i in array:\n out.append(array[i])\n return out\n\n\ndef array_calc(op, array1, array2):\n minimum = min(len(array1), len(array2))\n retour = []\n\n for i in range(minimum):\n retour.append(array1[i] + op * array2[i])\n\n return retour\n\n\n# ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** *\n\nclass Bezier:\n def __init__(self, points):\n self.points = points\n self.order = len(points)\n\n self.step = (0.0025 / self.order) if self.order > 0 else 1 # // x0.10\n self.pos = {}\n self.calc_points()\n\n def at(self, t: int):\n\n # B(t) = sum_(i=0) ^ n(iparmisn) (1 - t) ^ (n - i) * t ^ i * P_i\n if t in self.pos:\n return self.pos[t]\n\n x = 0\n y = 0\n n = self.order - 1\n\n for i in range(n + 1):\n x += cpn(i, n) * ((1 - t) ** (n - i)) * (t ** i) * self.points[i][0]\n y += cpn(i, n) * ((1 - t) ** (n - i)) * (t ** i) * self.points[i][1]\n\n self.pos[t] = [x, y]\n\n return [x, y]\n\n # Changed to approximate length\n def calc_points(self):\n if len(self.pos): return\n\n self.pxlength = 0\n prev = self.at(0)\n i = 0\n end = 1 + self.step\n\n while i < end:\n current = self.at(i)\n self.pxlength += distance_points(prev, current)\n prev = current\n i += self.step\n # ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** *\n\n def point_at_distance(self, dist):\n return {\n 0: False,\n 1: self.points[0],\n }.get(self.order, self.rec(dist))\n\n def rec(self, dist):\n self.calc_points()\n return point_at_distance(array_values(self.pos), dist)[:2]\n\n\n# ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** * #\n\nclass Catmull:\n def __init__(self, points):\n self.points = points\n self.order = len(points)\n\n self.step = 0.025\n self.pos = []\n self.calc_points()\n\n def at(self, x, t):\n v1 = self.points[x - 1] if x >= 1 else self.points[x]\n v2 = self.points[x]\n v3 = self.points[x + 1] if x + 1 < self.order else array_calc('1', v2, array_calc('-1', v2, v1))\n v4 = self.points[x + 2] if x + 2 < self.order else array_calc('1', v3, array_calc('-1', v3, v2))\n\n retour = []\n for i in range(2):\n retour[i] = 0.5 * (\n (-v1[i] + 3 * v2[i] - 3 * v3[i] + v4[i]) * t * t * t + (\n 2 * v1[i] - 5 * v2[i] + 4 * v3[i] - v4[i]) * t * t + (\n -v1[i] + v3[i]) * t + 2 * v2[i])\n\n return retour\n\n def calc_points(self):\n if len(self.pos):\n return\n for i in range(self.order - 1):\n for t in range(start=0, stop=1 + self.step, step=self.step):\n self.pos.append(self.at(i, t))\n\n def point_at_distance(self, dist):\n return {\n 0: False,\n 1: self.points[0],\n }.get(self.order, self.rec(dist))\n\n def rec(self, dist):\n self.calc_points()\n return point_at_distance(array_values(self.pos), dist)[:2]\n"} {"blob_id": "5f925a45a218c704e499fcc76920fa9038a7e5ca", "repo_name": "HopeCheung/leetcode", "path": "/leetcode-first_time/sudo.py", "length_bytes": 2887, "score": 3.515625, "int_score": 4, "content": "class Solution(object):\n def isValidSudoku(self, board):\n \"\"\"\n :type board: List[List[str]]\n :rtype: bool\n \"\"\"\n def judge(lst):\n new_lst = [k for k in lst if k != '.']\n length = len(new_lst)\n return not length == len(set(new_lst))\n \n for elem in board:\n if judge(elem):\n return False\n \n for i in range(9):\n path = []\n for elem in board:\n path += [elem[i]]\n if judge(path):\n return False\n \n for k in range(9):\n path = []\n for r in range(3):\n for c in range(3):\n path += board[(k//3)*3 + r][(k%3)*3 + c]\n if judge(path):\n return False\n \n return True\n\n\n\n def solveSudoku(self, board):\n def isvaild(i,j):\n for m in range(9):\n if m!=i and board[m][j]==board[i][j]:\n return False\n for n in range(9):\n if n!=j and board[i][n]==board[i][j]:\n return False\n for m in range(i//3*3, i//3*3+3):\n for n in range(j//3*3, j//3*3+3):\n if m!=i and n!=j and board[m][n]==board[i][j]:\n return False\n return True\n for i in range(9):\n for j in range(9):\n if board[i][j]=='.':\n for c in '123456789':\n board[i][j]=c\n if isvaild(i,j):\n if self.solveSudoku(board):\n return True\n else:\n board[i][j] = '.'\n else:\n board[i][j] = '.'\n return False\n return True\n\nclass Solution2():\n\tdef solveSudo(board):\n\t\tdfs(board, 0, 0)\n\tdef is_valid(x, y, board, k):\n\t\tfor i in range(9):\n\t\t\tif i != x and board[i][y] == k:\n\t\t\t\treturn False\n\t\t\tif i != y and board[x][i] == k:\n\t\t\t\treturn False\n\t\tfor i in range(x//3*3, x//3*3+3):\n\t\t\tfor j in range(y//3*3, y//3*3+3):\n\t\t\t\tif x != i and y != j and borad[i][j] == k:\n\t\t\t\t\treturn False\n\t\treturn True\n\tdef dfs(board, x, y):\n\t\tif x > 8 or y > 8:\n\t\t\treturn True\n\t\tif board[x][y] == '.':\n\t\t\tfor k in '123456789':\n\t\t\t\tif is_valid(board, x, y, k): #\u5f53\u524d\u6570\u5b57\u7b26\u5408\u8981\u6c42\n\t\t\t\t\tboard[x][y] = k\n\t\t\t\t\tnextx = x\n\t\t\t\t\tnexty = y + 1\n\t\t\t\t\tif nexty == 9:\n\t\t\t\t\t\tnexty = 0\n\t\t\t\t\t\tnextx = nextx + 1\n\t\t\t\t\tif dfs(board, nextx, nexty): #\u641c\u7d22\u4e0b\u4e00\u4e2a\u7a7a\u683c\n\t\t\t\t\t\treturn True\n\t\t\t\t\tboard[x][y] = '.'\n\t\t\treturn False #\u65e0\u6ee1\u8db3\u6761\u4ef6\u5b58\u5728\uff0c \u6570\u72ec\u65e0\u89e3\n\t\telse: #\u5f53\u524d\u975e\u7a7a\u683c\uff0c \u5373\u6709\u6570\u5b57\uff0c \u8df3\u8fc7\u7ee7\u7eed\u6df1\u641c\n\t\t\tnextx = x\n\t\t\tnexty = y+1\n\t\t\tif nexty == 9:\n\t\t\t\tnexty = 0\n\t\t\t\tnextx = nextx + 1\n\t\t\treturn dfs(board, nextx, nexty)\n\n\n"} {"blob_id": "40e09c039ad8878064930b534b232c120409f356", "repo_name": "dav1dn/projecteuler", "path": "/python/004.py", "length_bytes": 1382, "score": 4.25, "int_score": 4, "content": "\"\"\"A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 \u00d7 99.\n\nFind the largest palindrome made from the product of two 3-digit numbers.\"\"\"\n\nimport time\n\ndef is_palindrome(n):\n # Sorta hacky way to determine if a number is a palindrome.\n return str(n) == str(n)[::-1]\n\ndef three_digit_multiples_of_11():\n lst = [11*n for n in range(10,100)]\n return [n for n in lst if len(str(n)) == 3]\n\ndef solution():\n # Each even-digited palindrome is divisible by 11, so we'll use multiples of 11.\n # Proof: http://jwilson.coe.uga.edu/emt669/Student.Folders/Bacchus.Mohamed/pal/pal.html\n # We'll bruteforce each 3 digit multiple of 11 with each 3 digit number. \n # This is pretty inefficient...\n largest_palindrome = 1\n\n for x in three_digit_multiples_of_11()[::-1]:\n for y in list(range(100,999))[::-1]:\n product = x * y\n if product < largest_palindrome: # because we count down, break out of y loop if no more valid sol\n break\n elif is_palindrome(product) and product > largest_palindrome:\n largest_palindrome = product\n return largest_palindrome\n \n\n \nif __name__ == '__main__':\n start = time.time()\n answer = solution()\n print(\"answer {0} found in {1} seconds\".format(answer, time.time() - start))\n"} {"blob_id": "0e1f4a7d852b53e8314482d0e7fc2a37ac5e1fa6", "repo_name": "UKPLab/tacl2018-preference-convincing", "path": "/python/likelihoodtest.py", "length_bytes": 640, "score": 3.5625, "int_score": 4, "content": "import numpy as np\nfrom scipy.stats import norm\n\nlabel = 1\n\n# z has a normal distribution with\nmu = 0\nsigmasq = 1\n\n# we want to compute the expected log likelihood:\ndef loglikelihood(z):\n return np.log(norm.cdf(z))\n\ndef likelihood(z):\n return norm.cdf(z)\n\n# to take an expectation, we sample z:\nsamplez = norm.rvs(mu, sigmasq**0.5, 2000)\n\nell = np.mean(loglikelihood(samplez))\n\nprint(ell)\n\n# if we compute the log likelihood of the expectation:\nlle = loglikelihood(mu / np.sqrt(1 + sigmasq))\nprint(lle)\n\nz_i = mu+norm.pdf(mu)/(1-likelihood(mu))\nprint(z_i)\n\nlle = -0.5 * (mu**2 + sigmasq + np.log(2*np.pi) + z_i**2) + mu*z_i\nprint(lle)"} {"blob_id": "bbfc5e4e5f00010592d122097f27388cc3d63686", "repo_name": "justinmk/smurf", "path": "/py-misc/binary_tree_height.py", "length_bytes": 4966, "score": 3.875, "int_score": 4, "content": "# binary search tree:\n# - Nodes on the left branch are less than the node value.\n# - Nodes on the right branch are greater than the node value.\n\nimport math\nimport collections\n\nclass Node:\n def __init__(self, data):\n self.data = data\n self.left = None\n self.right = None\n def __str__(self):\n h = height(self)\n s = ''\n fill_fake_nodes_to_level(self, height(self))\n for level in range(0, h+1):\n nodes = get_nodes_at_level(self, None, level, 0)\n # print(nodes)\n print(f'len(nodes)={len(nodes)}')\n for i,n in enumerate(nodes):\n fill = (h - level + 1) * (2 if i % 2 == 0 else 1)\n if n is not None:\n s += (fill * ' ') + str(n)\n s+= '\\n'\n return s\n\ndef bfs_traverse(n, visitorfn):\n q = collections.deque()\n if n is not None:\n q.appendleft(n)\n while len(q) > 0:\n n = q.pop()\n visitorfn(n)\n if n.left is not None:\n q.appendleft(n.left)\n if n.right is not None:\n q.appendleft(n.right)\n\ndef dfs_inorder_traverse(n, visitorfn):\n thisfn = dfs_inorder_traverse\n if n is None:\n return\n if n.left is not None:\n thisfn(n.left, visitorfn)\n visitorfn(n)\n if n.right is not None:\n thisfn(n.right, visitorfn)\n\ndef dfs_outorder_traverse(n, visitorfn):\n thisfn = dfs_outorder_traverse\n if n is None:\n return\n if n.right is not None:\n thisfn(n.right, visitorfn)\n visitorfn(n)\n if n.left is not None:\n thisfn(n.left, visitorfn)\n\ndef dfs_preorder_traverse(n, visitorfn):\n thisfn = dfs_preorder_traverse\n if n is None:\n return\n visitorfn(n)\n if n.left is not None:\n thisfn(n.left, visitorfn)\n if n.right is not None:\n thisfn(n.right, visitorfn)\n\ndef fill_fake_nodes_to_level(root, level, curlevel=0):\n if root is None:\n return\n if root.left is None:\n root.left = Node('L')\n if root.right is None:\n root.right = Node('R')\n if curlevel < level:\n fill_fake_nodes_to_level(root.left, level, curlevel+1)\n fill_fake_nodes_to_level(root.right, level, curlevel+1)\n\n# Must do fill_fake_nodes_to_level() first.\n#\n# nodes = get_nodes_at_level(root, None, 3, 0) # => [None, 1, None, None, 9, None]\ndef get_nodes_at_level(root, nodes, level, curlevel):\n if nodes is None:\n # \"grid\" row, each cell is:\n # None: no node here\n # \".\": fake/dummy node\n # other: actual data\n row_width = (pow(2, height(root) - 1) + 1)\n # Remove nodes. These will be filled as the tree is walked.\n # Remove half of all, plus half of level^2.\n row_width = (row_width\n - int(row_width/2) + math.floor(pow(2, level)/2) - 1)\n nodes = [None] * row_width\n print(f'level={level}, len(nodes)={len(nodes)} row_width={row_width}')\n if root is None:\n return nodes\n if curlevel == level:\n # print(f'{i}: {root.data}')\n nodes.append(root.data)\n return nodes\n if root.left:\n get_nodes_at_level(root.left, nodes, level, curlevel+1)\n if root.right:\n get_nodes_at_level(root.right, nodes, level, curlevel+1)\n return nodes\n\nclass BinarySearchTree:\n def __init__(self):\n self.root = None\n def create(self, val):\n if self.root == None:\n self.root = Node(val)\n else:\n current = self.root\n while True:\n if val < current.data:\n if current.left:\n current = current.left\n else:\n current.left = Node(val)\n break\n elif val > current.data:\n if current.right:\n current = current.right\n else:\n current.right = Node(val)\n break\n else:\n break\n\ndef height(root):\n return heightrec(root, 0)\ndef heightrec(root, h):\n if root is None or (root.left is None and root.right is None):\n return h\n hl = 1\n hr = 1\n # print('left={} right={}'.format(root.left,root.right))\n if root.left:\n hl += heightrec(root.left, h)\n if root.right:\n hr += heightrec(root.right, h)\n if hl > hr:\n return h + hl\n return h + hr\n\ntree = BinarySearchTree()\n# t = [4, 2, 3, 1, 7, 6]\nt = [3, 3.3, 5, 2, 1, 4, 4.1, 6, 5.1, 6.1, 9]\n# t = [0]\n# t = [9,1,999,9999]\nfor i in range(len(t)):\n tree.create(t[i])\n\ndfs_outorder_traverse(tree.root, lambda n: print(n.data))\n\n# print(height(tree.root))\n# print(get_nodes_at_level(tree.root, None, 3, 0, 0))\nprint(tree.root)\n\n# Level-order traversal.\n# s = ''\n# def visitor(n):\n# global s\n# if n.data not in ('L', 'R'):\n# s += ('{}, '.format(n.data))\n# bfs_traverse(tree.root, visitor)\n# print(s)\n"} {"blob_id": "d01488782d195da979d0d567d72673037416061b", "repo_name": "Csellers15/Discrete-Mathematics", "path": "/MTH325 Projects/Bipartite.py", "length_bytes": 4275, "score": 4.28125, "int_score": 4, "content": "'''\nThe Power function returns the power set of the dictionary that is inputted as\nthe graph.\n'''\ndef power(graph):\n #sets graph equal to a set and a list.\n graph = set(graph)\n graph = list(graph)\n #temporary array used as the holder of the power set\n temp =[]\n #temporary variable that golds the length of the graph\n temp2 = len(graph)\n #iterates through the temp array that is shifted over\n for count in range(1 << temp2):\n # appends the graph at the position of the count to temp\n temp.append([graph[count2]\n # for loop for count 2\n for count2 in range(temp2)\n if (count & (1 << count2))])\n # returns temp\n return (temp)\n\n\n'''\nThis method splits the graph into its partite sets assuming that the graph is\nbipartite\n'''\ndef partite_sets(graph):\n #temporary sets to hold the values\n setA = []\n setB =[]\n\n #iterates throhg the keys of the graphs and adds the fist one to set A\n for key in graph:\n setA += key\n break\n\n #Iterates throught the rest of the keys\n for key in graph:\n #if the key is in set A.\n if key in setA:\n #iterates through the graphs specific key\n for value in graph[key]:\n #if the value of the keys specific location isnt in setB it adds it to setA\n if value not in setB:\n setB += value\n #if the key isnt in setA it enters this.\n else:\n #iterates through the graphs specific key\n for value in graph[key]:\n #if the value isnt in setA then it adds it to setA\n if value not in setA:\n setA += value\n #variable for the final set\n finalSet = []\n #appends the values of set a and set b to the final set\n finalSet.append(setA)\n finalSet.append(setB)\n\n #returns the final set\n return finalSet\n\n'''\nChecks if the graph is bipartite or not\n'''\ndef is_bipartite(graph):\n #creates a temprary array and sets calls partite_sets againn making puting the partite sets intto left and right variables\n temp = partite_sets(graph)\n left = temp[0]\n right = temp[1]\n result = True\n\n # Iterates throught the left array\n for i in left:\n # if the position i is in the right arrray set the result to false\n if i in right:\n result = False\n #Returns false\n return result\n\n\n'''\nChecks if the graph is a perfect matching or not\n'''\ndef is_perfect(graph):\n #sets the partite sets into x and y and status to true.\n status = True\n partite = partite_sets(graph)\n x = power(partite[0])\n y = power(partite[1])\n\n #iterates through the x array\n for nh in x:\n temp = []\n #iterates through the nodes in nh\n for node in nh:\n #sets temp variable equal to the list of the set of temp and unions it to graph at a specific node\n temp = list(set(temp).union(graph[node]))\n # if the length of temp is less that nh set the status to false\n if len(temp) < len(nh):\n status = False\n\n #iterates through the y array\n for nh in y:\n temp = []\n #iterates through the nodes in nh\n for node in nh:\n #sets temp variable equal to the list of the set of temp and unions it to graph at a specific node\n temp = list(set(temp).union(graph[node]))\n # if the length of temp is less that nh set the status to false\n if len(temp) < len(nh):\n status = False\n\n #returns the status variable\n return status\n\n\n\nprint(power(['A', 'B']))\nprint(power(['A', 'B', 'C']) )\n\nprint(partite_sets({'A': ['B', 'C'], 'B': ['A'], 'C': ['A']}))\n#return ['A'],[\u201cB\u201d,\u201cC\u201d] (or [\u201cB\u201d, \u201cC\u201d], ['A'])\nprint(partite_sets({'A': ['B', 'C'], 'B': ['A', 'D'], 'C': ['A','D'], 'D': ['B', 'C']}))\n#return ['A', \u201cD\u201d], [\u201cB\u201d, \u201cC\u201d] (or [\u201cB\u201d, \u201cC\u201d], ['A', \u201cD\u201d])\n\nprint(is_bipartite({'A': ['B', 'C'], 'B': ['A'],'C': ['A']}))\n#return True\nprint(is_bipartite({'A': ['B', 'C'], 'B': ['A', 'C'], 'C': ['A', 'B']}))\n #return False\n\nprint(is_perfect({'A': ['B', 'C'], 'B': ['A', 'D'], 'C': ['A', 'D'], 'D': ['B', 'C']})) # return True\nprint(is_perfect({'A': ['B', 'C'], 'B': ['A'], 'C': ['A']})) # return False\n"} {"blob_id": "6a4408bc394ec3a2983b6941b508d00dfe44da95", "repo_name": "jbburt/advent-of-code-20", "path": "/day-07/day_7.py", "length_bytes": 1411, "score": 3.546875, "int_score": 4, "content": "\"\"\"\nhttps://adventofcode.com/2020/day/7\n\"\"\"\n\nfrom collections import defaultdict\n\n# Read input\nf = 'day-07/input.txt'\nwith open(f, 'r') as fp:\n data = fp.read().replace(\" bags\", '').replace(\" bag\", '').replace('.', '')\ndata = data.split(\"\\n\")\n\n# Parse input: map from a bag to other bags contained therein\nmappings = dict()\nfor d in data:\n k, v = d.split(' contain ')\n if v == \"no other\":\n mappings[k] = None\n else:\n mappings[k] = [(x[2:], int(x[0])) for x in v.split(', ')]\n\n# Problem 1:\n# How many bag colors can contain at least one shiny gold bag?\nuntested = set(mappings.keys()) # colors which have not been tested\nqueue = {'shiny gold'} # bags which may contain a shiny gold bag\nn = -1\nwhile queue:\n c = queue.pop()\n n += 1\n for k, v in mappings.items():\n if v is not None: # if bag contains other bags\n colors = [x[0] for x in v]\n if c in colors and k in untested:\n queue.add(k)\n untested.remove(k)\nprint(f'problem 1: {n}')\n\n# Problem 2:\n# How many individual bags are required inside your single shiny gold bag?\nn = -1\nqueue = defaultdict(lambda: 0)\nqueue['shiny gold'] = 1\nwhile queue:\n bag_color, nbags = queue.popitem()\n n += nbags\n nested_items = mappings[bag_color]\n if nested_items is not None:\n for c, nb in nested_items:\n queue[c] += nb*nbags\nprint(f'problem 2: {n}')\n"} {"blob_id": "1fba09f5e70b6e42a056e56e04b074adb51eb4a9", "repo_name": "aewiens/stat-8060", "path": "/final.py", "length_bytes": 4832, "score": 3.828125, "int_score": 4, "content": "#!/usr/bin/env python3\n\"\"\" STAT 8060 Final\n Avery Wiens\n December 8, 2017\n\"\"\"\nimport numpy as np\nimport numpy.random as npr\nimport numpy.matlib as ml\n\ndef pivot_matrix(i, A):\n \"\"\" Build the pivoting matrix for A \"\"\"\n M = A.copy()\n m = len(M)\n I = np.identity(m)\n\n col = np.fabs(M[:,i])\n row = np.argmax(col)\n \n if row != i: \n II = I.copy()\n I[i] = II[row]\n I[row] = II[i]\n\n return I\n\n\n############################################################################\n############################ PROBLEM 1 #####################################\n############################################################################\n# Write a function that does LU decomposition of a square matrix A\n\n\ndef LUdecomp(A, pivot=False): \n \"\"\" Perform LU decomposition using Crout's algorithm\n\n Parameters\n ----------\n A : ndarray\n Square matrix\n\n Return\n ------\n L, U : ndarray\n Square matrices s.t. LU = A\n \"\"\"\n n, m = A.shape\n assert m==n, \"LU decomposition is only meant for square matrices!\"\n\n U = np.zeros_like(A)\n L = np.identity(n)\n\n if pivot:\n P = pivot_matrix(0, A)\n A = P @ A\n\n for j in range(n):\n for i in range(j+1):\n U[i,j] = A[i,j] \n if j > 0:\n U[i,j] -= sum(U[k,j] * L[i,k] for k in range(i))\n\n for i in range(j, n):\n L[i,j] = (A[i,j] - sum(U[k,j] * L[i,k] for k in range(j))) / U[j,j]\n\n\n L -= np.identity(n)\n return L + U\n\n\n\n\n############################################################################\n############################ PROBLEM 2 #####################################\n############################################################################\n\n# Write a function that takes the LU decomposition for matrix A and solves the\n# system of equations AX = Y for the vector X. \n\n\ndef LUsolve(B, Y):\n \"\"\" Solve system of equations AX = Y (where B is LU decomposition of A)\n\n Parameters\n ----------\n B : np.array\n Square matrix corresponding to the LU decomposition of A, with elements\n of the L matrix below the diagonal and elements of the U matrix above\n the diagonal\n\n Y : np.array\n Column vector Y for which the solution AX = Y is desired\n\n Return\n ------\n x : np.ndarray\n numpy 1D array containing the solution for the system \n \"\"\"\n\n n = len(B)\n U = np.zeros_like(B)\n L = np.identity(n)\n\n for i in range(n):\n for j in range(i):\n L[i,j] = B[i,j]\n \n for k in range(i, n):\n U[i,k] = B[i,k]\n\n LL = np.concatenate((L, Y), axis=1)\n Z = forward_substitute(LL)\n\n UU = np.concatenate((U, np.array([Z]).T), axis=1)\n X = back_substitute(UU)\n\n return X\n\n\ndef forward_substitute(L):\n \"\"\" Solve the system of equations contained in a lower triangular, augmented\n matrix L\n \"\"\"\n m, n = L.shape\n x = np.zeros(m)\n for i in range(m):\n x[i] = L[i, n-1] / L[i,i]\n for i in range(1, m):\n x[i] -= sum(L[i,k] * x[k] for k in range(i))\n\n return x\n\n\ndef back_substitute(U):\n \"\"\" Solve the system of equations contained in an upper triangular, \n augmented matrix U\n \"\"\"\n n = len(U)\n x = np.zeros(n) \n for i in range(n-1, -1, -1):\n x[i] = U[i,n] / U[i,i]\n for k in range(i-1, -1, -1):\n U[k,n] -= U[k,i] * x[i]\n return x\n\n\n\n\n# Set seed to make sure my answer is staying the same every time\nnp.random.seed(0)\n\ndef MakeSeq(begin, end, by):\n A=[]\n \n i=0\n while (begin+by*i) 0:\n sum += 1\n freq[i] -= 1\n sum += self.dfs(freq, memo)\n freq[i] += 1\n\n memo[hash] = sum\n return sum\n\n\n\n# print(Solution().numTilePossibilities('AAB'))\n# leetcode submit region end(Prohibit modification and deletion)\n"} {"blob_id": "e5b819957ed79320d85500f954e5f09047d79f2f", "repo_name": "Drahushchak/TestRepository", "path": "/test3.py", "length_bytes": 2156, "score": 4.125, "int_score": 4, "content": "# Python3 program to find the mirror node in \n# Binary tree \nraw_input = \"\"\" 7 3 2\n 2 3 R\n 2 4 L\n 3 5 R\n 3 6 L\n 4 7 R\n 4 8 L\n 5 9 L\n 7\n 9\n 2 \"\"\"\nraw_input = (i for i in map(lambda x: x.strip(), raw_input.split('\\n')))\nclass Node: \n\t'''A binary tree node has data, reference to left child \n\t\tand a reference to right child '''\n\n\tdef __init__(self, key, lchild=None, rchild=None): \n\t\tself.key = key \n\t\tself.lchild = None\n\t\tself.rchild = None\n\ndef formNodes(data, root):\n L = R = False\n for i in range(len(data)):\n perent, child, side = data[i].values()\n if perent==root.key:\n if side=='L':\n root.lchild = formNodes(data[:i]+data[i+1:], Node(child))\n L = True\n elif side=='R':\n root.rchild = formNodes(data[:i]+data[i+1:], Node(child))\n R = True\n if L and R:\n break\n return root\n \n# recursive function to find mirror \ndef findMirrorRec(target, left, right): \n\n\t# If any of the node is none then node itself \n\t# and decendent have no mirror, so return \n\t# none, no need to further explore! \n\tif left == None or right == None: \n\t\treturn None\n\n\t# if left node is target node, then return \n\t# right's key (that is mirror) and vice versa \n\tif left.key == target: \n\t\treturn right.key \n\tif right.key == target: \n\t\treturn left.key \n\n\t# first recur external nodes \n\tmirror_val = findMirrorRec(target, left.lchild, right.rchild) \n\tif mirror_val != None: \n\t\treturn mirror_val \n\n\t# if no mirror found, recur internal nodes \n\treturn findMirrorRec(target, left.rchild, right.lchild) \n\n# interface for mirror search \ndef findMirror(root, target): \n\tif root == None: \n\t\treturn None\n\n\tif root.key == target: \n\t\treturn target \n\n\treturn findMirrorRec(target, root.lchild, root.rchild) \n\n \nN, Q, X = map(int, next(raw_input).split())\ndata = [dict(zip(['perent','child','side'], next(raw_input).split()))for i in range(N)]\nroot = formNodes(data, Node(str(X)))\nfor _ in range(Q):\n mirror = findMirror(root, next(raw_input))\n print(mirror if mirror else 'Not Exist')\n"} {"blob_id": "243fd196046b66fc1f6eedb757564b3e6afeb763", "repo_name": "DxSharp/car-flocking", "path": "/car.py", "length_bytes": 11675, "score": 4.625, "int_score": 5, "content": "\"\"\"This module contains functionality to represent a car in the simulation.\n\nA car is represented by its dimensions and limitations with respect to velocity and turning radius. The distance between\nthe front axle and the front of the car is considered equal to the distance between the back axle and the back of the\ncar. In other words, the midpoint of the wheelbase is equal to the midpoint of the length of the car. The movement of\nthe car is based on a Simple Car kinematics model (see: http://planning.cs.uiuc.edu/node658.html).\n\nThis module contains functions to calculate the flocking forces experienced by a car. These flocking forces are then\ntranslated into adjustment of the control parameters of a car: acceleration and steering.\n\n\"\"\"\n\nfrom typing import List, Tuple\nfrom goal import Goal\nfrom vector import Vector\nfrom math import radians, tan, inf\nfrom wall import Wall\n\n\nclass Car:\n\n def __init__(self, length: float, width: float, wheelbase: float, max_velocity: float, max_acceleration: float,\n max_steering_angle: float, max_steering_change: float, x: float = 0, y: float = 0, angle: float = 0,\n velocity: float = 0, steering_angle: float = 0, acceleration: float = 0, steering_change: float = 0):\n \"\"\"Initializes a new car object.\n\n Args:\n length (float): The length of the car in meters.\n width (float): The width of the car in meters.\n wheelbase (float): The distance between the front and back axle of the car in meters.\n max_velocity (float): The maximum velocity the car can achieve in meters per second.\n max_acceleration (float): The maximum acceleration the car can achieve in meters per second squared.\n max_steering_angle (float): The maximum possible angle the wheels of the car can rotate in degrees.\n max_steering_change (float): The maximum speed with which the wheel angle of the car can change in degrees\n per second.\n x (float): The x-value of the initial position of the car in meters.\n y (float): The y-value of the initial position of the car in meters.\n angle (float): The initial angle of the car relative to the positive x-axis.\n velocity (float): The initial velocity of the car in meters per second.\n steering_angle (float): The initial angle of the wheels of the car in degrees.\n acceleration (float): The initial acceleration of the car in meters per second squared.\n steering_change (float): The initial change of wheel angle in degrees per seconds.\n\n \"\"\"\n self.length: float = length\n self.width: float = width\n self.wheelbase: float = wheelbase\n\n self.x: float = x\n self.y: float = y\n self.direction: Vector = Vector.from_degrees(angle)\n self.steering_angle: float = radians(steering_angle)\n\n self.velocity: float = velocity\n self.steering_change: float = radians(steering_change)\n\n self.acceleration: float = acceleration\n\n self.max_velocity: float = max_velocity\n self.max_acceleration: float = max_acceleration\n self.max_steering_angle: float = radians(max_steering_angle)\n self.max_steering_change: float = radians(max_steering_change)\n\n self.overlapping_cars: List[Car] = []\n self.goal_reached: bool = False\n self.flocking_vector: Vector = Vector()\n\n def update(self, dt: float):\n \"\"\"Updates position, direction, velocity and steering angle given a time step in seconds.\n\n Args:\n dt (float): The amount of time in seconds to progress the simulation.\n\n \"\"\"\n x_change = self.velocity * self.direction.x\n y_change = self.velocity * self.direction.y\n angle_change = tan(self.steering_angle) * self.velocity / self.wheelbase\n\n self.x = self.x + x_change * dt\n self.y = self.y + y_change * dt\n self.direction = self.direction.rotate_radians(angle_change * dt)\n\n new_velocity = self.velocity + self.acceleration * dt\n new_steering_angle = self.steering_angle + self.steering_change * dt\n\n self.velocity = min(self.max_velocity, new_velocity)\n self.steering_angle = max(-self.max_steering_angle, min(new_steering_angle, self.max_steering_angle))\n\n def adjust_behavior(self, neighbors: List[Tuple['Car', float]], goal: Goal, rule_weights: List[float]):\n \"\"\"Changes the control parameters of this car given its neighbors, its goal and the flocking rule weights.\n\n First, it is determined if the car has reached its goal yet. Next, the flocking forces experienced are\n calculated, of which the weighted average is taken to obtain the final flocking vector. This final vector is\n used to determine the steering change.\n\n Args:\n neighbors (List[Tuple[Car, float]]): A list of neighboring cars and the distance between this car and each\n respective neighboring car.\n goal (Goal): The goal that this car should steer towards.\n rule_weights (List[float]): A list with the weights of each flocking force. The respective flocking forces\n are [Separation, Alignment, Cohesion, Goal].\n\n \"\"\"\n if goal.active:\n goal_force = self.goal_force(goal)\n if goal_force.get_length() < self.length:\n self.goal_reached = True\n else:\n goal_force = Vector(0.0, 0.0)\n\n if not self.goal_reached:\n for neighbor in neighbors:\n self.goal_reached = self.goal_reached or neighbor[0].goal_reached\n\n separation_force = self.separation(neighbors)\n alignment_force = self.alignment(neighbors)\n cohesion_force = self.cohesion(neighbors)\n\n self.flocking_vector = separation_force * rule_weights[0] + alignment_force * rule_weights[1] + \\\n cohesion_force * rule_weights[2] + goal_force * rule_weights[3]\n\n steering_direction = self.direction.rotate_radians(self.steering_angle)\n\n if self.flocking_vector == Vector(0, 0):\n angle_dif = 0\n else:\n angle_dif = steering_direction.angle_to(self.flocking_vector)\n\n if angle_dif > 0:\n self.steering_change = self.max_steering_change\n elif angle_dif < 0:\n self.steering_change = -self.max_steering_change\n elif self.steering_angle > 0:\n self.steering_change = -self.max_steering_change\n else:\n self.steering_change = self.max_steering_change\n\n def goal_force(self, goal: Goal) -> 'Vector':\n \"\"\"Determines the force this car experiences to towards the specified goal.\n\n Args:\n goal (Goal): The goal that this car should steer towards.\n\n Returns:\n Vector: A vector representing the force experienced by this car towards the goal.\n\n \"\"\"\n return Vector(goal.x - self.x, goal.y - self.y)\n\n def wall_avoidance(self, walls: List[Wall], wall_radius) -> 'Vector':\n \"\"\"Determines the force this car experiences to avoid given walls within the specified radius.\n\n TODO: Revise and incorporate into simulation.\n\n Args:\n walls (List[Wall]): A list of walls that the car can collide with.\n wall_radius (float): The radius around this car a wall must be in to be taken into account.\n\n Returns:\n Vector: A vector representing the wall avoidance force experienced by this car.\n\n \"\"\"\n resulting_force = Vector()\n heading = self.direction.rotate_radians(self.steering_angle)\n for wall in walls:\n steering_vector = wall.perpendicular_vector(self.x, self.y)\n vector_length = steering_vector.get_length()\n if vector_length < wall_radius:\n rotation = steering_vector.angle_to(heading)\n if rotation > 0.0:\n steering_vector = steering_vector.rotate_degrees(90)\n else:\n steering_vector = steering_vector.rotate_degrees(-90)\n\n if abs(rotation) < radians(90):\n steering_force = steering_vector.change_length(0)\n else:\n steering_force = steering_vector.change_length(wall_radius - vector_length)\n\n resulting_force += steering_force\n\n return resulting_force\n\n def separation(self, neighbors: List[Tuple['Car', float]]) -> Vector:\n \"\"\"Determines the separation force this car experiences given its neighbors.\n\n Args:\n neighbors (List[Tuple[Car, float]]): A list of neighboring cars and the distance between this car and each\n respective neighboring car.\n\n Returns:\n Vector: A vector representing the separation force experienced by this car.\n\n \"\"\"\n resulting_force = Vector()\n for neighbor in neighbors:\n distance = neighbor[1]\n n = neighbor[0]\n separation_vector = Vector(self.x - n.x, self.y - n.y)\n if distance == 0:\n separation_length = inf\n else:\n separation_length = 1 / distance\n separation_force = separation_vector.change_length(separation_length)\n resulting_force += separation_force\n return resulting_force\n\n @staticmethod\n def alignment(neighbors: List[Tuple['Car', float]]) -> 'Vector':\n \"\"\"Determines the alignment force this car experiences given its neighbors.\n\n Args:\n neighbors (List[Tuple[Car, float]]): A list of neighboring cars and the distance between this car and each\n respective neighboring car.\n\n Returns:\n Vector: A vector representing the alignment force experienced by this car.\n\n \"\"\"\n resulting_force = Vector()\n for neighbor in neighbors:\n resulting_force += neighbor[0].direction\n return resulting_force\n\n def cohesion(self, neighbors: List[Tuple['Car', float]]) -> Vector:\n \"\"\"Determines the cohesion force this car experiences given its neighbors.\n\n Args:\n neighbors (List[Tuple[Car, float]]): A list of neighboring cars and the distance between this car and each\n respective neighboring car.\n\n Returns:\n Vector: A vector representing the cohesion force experienced by this car.\n\n \"\"\"\n x_summation = 0\n y_summation = 0\n for neighbor in neighbors:\n n = neighbor[0]\n x_summation += n.x\n y_summation += n.y\n neighbor_count = len(neighbors)\n x_average = x_summation / neighbor_count\n y_average = y_summation / neighbor_count\n return Vector(x_average - self.x, y_average - self.y)\n\n def wall_collision(self, walls: List[Wall], new_x: float, new_y: float) -> bool:\n \"\"\"Determines if this car will collide with a wall if moving to the specified new position.\n\n TODO: Revise and incorporate into simulation.\n\n Args:\n walls (List[Wall]): A list of walls that the car can collide with.\n new_x (float): The x-value of the new position.\n new_y (float): The y-value of the new position.\n\n Returns:\n bool: True if the specified movement will result in a collision, false otherwise.\n\n \"\"\"\n for wall in walls:\n v1 = wall.perpendicular_vector(self.x, self.y)\n v2 = wall.perpendicular_vector(new_x, new_y)\n angle = v1.angle_to(v2)\n if angle != 0.0:\n return True\n return False\n"} {"blob_id": "c187c74a73389894f30b3709b8a42f86304be158", "repo_name": "LukeBurgessYeo/final-year-project", "path": "/findingsl3.py", "length_bytes": 2275, "score": 3.546875, "int_score": 4, "content": "import math\r\n\r\nincrement = 36000 # 2PI/increment is the step size around the circle\r\nradius = 100\r\n\r\n# this function generates the coefficients of a,b,a-b\r\ndef coefficients(n):\r\n result = []\r\n for i in range(n+1):\r\n for j in range(n-i+1):\r\n for k in range(n-i-j+1):\r\n if (i+j+k == n):\r\n result.append([k, j, i])\r\n return result\r\n\r\n# these functions are the elements in our expressions (in polar coordinates)\r\ndef a(x):\r\n return math.sin(x*2*math.pi/increment)*radius\r\n\r\ndef b(x):\r\n return math.cos(x*2*math.pi/increment)*radius\r\n\r\ndef c(x):\r\n return a(x) - b(x)\r\n\r\n# now the calculations begin\r\ndef calculator(sp):\r\n coef = coefficients(sp)\r\n\r\n # this function defines our inequalities\r\n def inequality(n, t):\r\n return a(t)*int(coef[n][0]) + b(t)*int(coef[n][1]) + c(t)*int(coef[n][2])\r\n\r\n indexes = [] # the angles\r\n values = [] # the values of a,b,a-b for a given angle\r\n result = {} # holds the values of a,b,a-b at a particular angle\r\n\r\n for t in range(increment):\r\n indexes.append(t)\r\n values.append(t)\r\n expressions = {} # lables the elements: 0->a, 1->b, 2->a-b\r\n for n in range(len(coef)):\r\n expressions[n+1] = round(inequality(n, t), 3)\r\n values[t] = expressions\r\n result[indexes[t]] = values[t]\r\n\r\n for x in result:\r\n result[x] = sorted(result[x], key = result[x].get)\r\n\r\n fin_len = [] # simply used to check how many unique flags we get\r\n points = []\r\n for key in range(min(result), max(result)):\r\n if result[key] != result[key+1]:\r\n fin_len.append(key*360/increment)\r\n points.append(key*360/increment) #uncomment to see what the angles are\r\n\r\n return points #len(fin_len)\r\n\r\nfile = open(\"results.txt\", \"w\") #write the results to a text file\r\nfor n in range(1, 51): #change 51 to whichever symmetric power you want\r\n file.write(str(calculator(n))+'\\n')\r\nfile.close()\r\n\r\n#each new line of the text file shows a list of angles for the points at that symmetric power\r\n\r\n#to see only the number of points at a given symmetric power, change line 57 to \"return len(fin_len)\" and then uncomment the following:\r\n#for n in range(1, 51):\r\n# print(calculator(n))\r\n"} {"blob_id": "9ef98ccdc395b6a27d4afdd98495d66cf2ec0002", "repo_name": "noelladsa/pyramid", "path": "/pyramidmaxset.py", "length_bytes": 2619, "score": 3.796875, "int_score": 4, "content": "#By starting at the top of the triangle and moving to adjacent numbers on the row below, the maximum total from top to bottom is 27.\n\n# 5\n# 9 6\n# 4 6 8\n# 0 7 1 5\n\n#I.e. 5 + 9 + 6 + 7 = 27.\n\nimport sys\nimport time\n\n\nclass PyramidGraph(object):\n\n # Parses line and returns an array of numbers \n def GetNumbers(self,stringOfNumbers):\n nodeList = []\n if not stringOfNumbers:\n return nodeList\n \n numberStrs = stringOfNumbers.strip().split(\" \")\n for numberStr in numberStrs:\n number = int(numberStr)\n nodeList.append(number)\n return nodeList\n \n \n def __init__(self,filePath):\n file = open(filePath,\"r\")\n str = file.read()\n file.close()\n self.lines = str.split(\"\\n\")\n \n # Evaluates pyramid from bottom and calculates the individual sum of each path possibility\n # as we move up tier by tier.\n # Example\n #\n def MaxSweep(self):\n maxVal = []\n lineindex = len(self.lines) - 1\n if lineindex == 0:\n maxVal = self.GetNumbers(self.lines[0])\n print \"There is only one line\"\n else:\n newSets = None\n while lineindex >= 0:\n tier = self.GetNumbers(self.lines[lineindex])\n start = time.time()\n newSets = self.EvaluateTiers(newSets,tier)\n end = time.time()\n print \"Evaluation of tier\",lineindex, end - start\n lineindex = lineindex - 1 \n print \"Maximum total from top to bottom\",max(newSets[0])\n return \n \n def GetPathSum(self,number,sets):\n singleSet = []\n if sets is None: \n singleSet.append(number)\n else:\n for currMax in sets[0]:\n singleSet.append(currMax+number)\n sets.remove(sets[0])\n for currMax in sets[0]:\n singleSet.append(currMax+number)\n \n return singleSet \n \n def EvaluateTiers(self,sets,tier):\n newSets = []\n for number in tier:\n singleSet = self.GetPathSum(number,sets)\n newSets.append(singleSet)\n return newSets \n\n \n \nif len(sys.argv) == 1:\n print \"Usage: pyramidmax.py \"\n print \"Example of possible file contents:\"\n print \"5\"\n print \"9 6\"\n print \"4 6 8\"\n print \"0 7 1 5\"\nelse:\n pyrData = PyramidGraph(sys.argv[1])\n pyrData.MaxSweep()\n# print \"The Maximum value in this pyramid is\",pyrData.max"} {"blob_id": "26d28eeaeba0101f658ef6d7833acf22b6836c8a", "repo_name": "kkchaitu27/Algorithms", "path": "/SortingAlgorithms/heapsort.py", "length_bytes": 1153, "score": 4.40625, "int_score": 4, "content": "#Heap Sort Algorithm for sorting in increasing order:\n#1. Build a max heap from the input data.\n#2. At this point, the largest item is stored at the root of the heap. Replace it with the last item of the heap followed by reducing the size of heap by 1. Finally, heapify the root of tree.\n#3. Repeat above steps while size of heap is greater than 1.\n\n#Heapify the array\ndef heapify(array,n,i):\n largest = i\n left = 2*i + 1\n right = 2*i + 2\n #Check Left child if it is larger\n if left < n and array[largest] < array[left]:\n largest = left\n #Check right child if it is larger \n if right < n and array[largest] < array[right]:\n largest = right\n #If left or right child is larger,swap and heapify again\n if largest != i:\n array[i],array[largest] = array[largest],array[i]\n\n heapify(array,n,largest)\n\n#Main function to heapify and swap elements to sort the array\ndef heapsort(array):\n\n n = len(array)\n\n for i in range(n,-1,-1):\n heapify(array,n,i)\n\n for i in range(n-1,0,-1):\n array[i],array[0] = array[0],array[i]\n heapify(array,i,0)\n\n\nA = [5,1,3,8,9,10,12,3]\n\nheapsort(A)\n\nprint(A)\n"} {"blob_id": "dbcd2c9ee49318359844b47feb2a970c50e459be", "repo_name": "AlexClowes/advent_of_code", "path": "/2018/08/metadata_sum.py", "length_bytes": 789, "score": 3.59375, "int_score": 4, "content": "def recurse(data):\n n_children, n_metadata = next(data), next(data)\n metadata_sum = 0\n value = 0\n child_vals = []\n for _ in range(n_children):\n child_metadata_sum, child_value = recurse(data)\n metadata_sum += child_metadata_sum\n child_vals.append(child_value)\n for _ in range(n_metadata):\n metadata = next(data)\n metadata_sum += metadata\n if 0 < metadata <= n_children:\n value += child_vals[metadata - 1]\n if n_children == 0:\n value = metadata_sum\n return metadata_sum, value\n\n\ndef main():\n with open(\"data.txt\") as f:\n data = map(int, f.read().strip().split())\n metadata_sum, value = recurse(data)\n print(metadata_sum)\n print(value)\n\n\nif __name__ == \"__main__\":\n main()\n"} {"blob_id": "552b44e8a6b415dbd94ecadc8146bb0b0357a210", "repo_name": "young31/Algorithm", "path": "/\ucf54\ub529\ud14c\uc2a4\ud2b8(\ucc45)/ch9.\ucd5c\ub2e8\uacbd\ub85c/\ub2e4\uc775\uc2a4\ud2b8\ub77c.py", "length_bytes": 1718, "score": 3.515625, "int_score": 4, "content": "# input\nn, m = 6, 11\nstart = 1\ninf = int(float(1e10))\ndistance = [inf for _ in range(n+1)]\nvisited = [False for _ in range(n+1)]\n# \ub515\uc154\ub108\ub9ac\uac00 \ud3b8\ud574\uc11c \uc0ac\uc6a9\ud588\uc9c0\ub9cc \uc77c\ubc18\uc801\uc73c\ub85c \ub9ac\uc2a4\ud2b8\ub97c \uc0ac\uc6a9\ngraph = {\n 1: {\n 2: 2, 3: 5, 4: 1\n },\n 2: {\n 3: 3, 4: 2,\n },\n 3: {\n 2: 3, 6: 5\n },\n 4: {\n 3: 3, 5: 1\n },\n 5: {\n 3: 1, 6: 2\n }\n}\n# answer: \n\n# algo\n# \uacc4\uc18d\ud574\uc11c \uc791\uc740 \uac12\ubd80\ud130 \ucd08\uae30\ud654\ud574\uc11c \uc81c\uc77c \uc9e7\uc740 \uae38\uc744 \ub354\ud574\uac00\uae30 \uc704\ud574\uc11c\ndef get_smallest_node():\n index = 0\n min_ = inf\n for i in range(1, n+1):\n if distance[i] < min_ and not visited[i]:\n min_ = distance[i]\n index = i\n return index\n\ndef dijkstra1(start):\n # initialize\n distance[start] = 0\n visited[start] = True\n for k, v in graph[start].items():\n distance[k] = v\n for _ in range(n-1):\n cur = get_smallest_node()\n visited[cur] = True\n if cur in graph.keys():\n for k, v in graph[cur].items():\n cost = v + distance[cur]\n if cost < distance[k]:\n distance[k] = cost\n\n\ndef dijkstra2(start): # smallest node\ub97c \ucc3e\ub294 \uacfc\uc815\uc744 \ub2e8\ucd95\uc2dc\ud0b4\n import heapq\n distance[start] = 0\n visited[start] = True\n q = [] # \ucc28\uc774\uc810\n heapq.heappush(q, (0, start))\n while q:\n dist, cur = heapq.heappop(q)\n if distance[cur] < dist:\n continue\n if cur in graph.keys():\n for k, v in graph[cur].items():\n cost = dist + v\n if cost < distance[k]:\n distance[k] = cost\n heapq.heappush(q, (cost, k))\n\ndijkstra2(start)\nprint(distance)"} {"blob_id": "fb78a2d4570d877a3e842cb8181323a5a4447eb7", "repo_name": "Code-Beast/LeetCode", "path": "/017_Letter_Combinations_Of_A_Phone_Number/Solution.py", "length_bytes": 2868, "score": 3.5, "int_score": 4, "content": "#!python3\n# Author: Code-Beast\n\n# MY SOLUTION 3 (Iteration: Fatest)\nclass Solution:\n def letterCombinations(self, digits):\n \"\"\"\n :type digits: str\n :rtype: List[str]\n\n >>> Solution().letterCombinations(\"23\")\n ['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf']\n >>> Solution().letterCombinations(\"234\")\n \"\"\"\n if len(digits) == 0:\n return []\n\n digitLetterMap = {\n '2': 'abc',\n '3': 'def',\n '4': 'ghi',\n '5': 'jkl',\n '6': 'mno',\n '7': 'pqrs',\n '8': 'tuv',\n '9': 'wxyz'\n }\n\n combs = ['']\n res = []\n\n for digit in digits:\n for combPrev in combs:\n for letter in digitLetterMap[digit]:\n res.append(combPrev + letter)\n combs = res\n res = []\n\n return combs\n\n\n\n# # MY SOLUTION 2 (Recursion)\n# class Solution:\n# def letterCombinations(self, digits):\n# \"\"\"\n# :type digits: str\n# :rtype: List[str]\n\n# >>> Solution().letterCombinations(\"23\")\n# ['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf']\n# \"\"\"\n# if len(digits) == 0:\n# \treturn []\n\n# digitLetterMap = {\n# \t\"2\": ['a', 'b', 'c'],\n# \t\"3\": ['d', 'e',\t'f'],\n# \t\"4\": ['g', 'h', 'i'],\n# \t\"5\": ['j', 'k', 'l'],\n# \t\"6\": ['m', 'n', 'o'],\n# \t\"7\": ['p', 'q', 'r', 's'],\n# \t\"8\": ['t', 'u', 'v'],\n# \t\"9\": ['w', 'x', 'y', 'z']\n# }\n\n# def digitToLetterCombinations(currentIdx):\n# \tif currentIdx == len(digits) - 1:\n# \t\treturn digitLetterMap[digits[-1]]\n\n# \tcombinations = []\n\n# \tfor letter in digitLetterMap[digits[currentIdx]]:\n# \t\tfor rest in digitToLetterCombinations(currentIdx + 1):\n# \t\t\tcombinations.append(letter + rest)\n\n# \treturn combinations\n\n# return digitToLetterCombinations(0)\n \n\n\n# # MY SOLUTION 1 (reduce() from functools: Worst Solution)\n# from functools import reduce\n\n# class Solution:\n# def letterCombinations(self, digits):\n# \"\"\"\n# :type digits: str\n# :rtype: List[str]\n\n# >>> Solution().letterCombinations(\"23\")\n# ['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf']\n# >>> Solution().letterCombinations(\"234\")\n# \"\"\"\n# if len(digits) == 0:\n# \treturn []\n\n# digitLetterMap = {\n# '2': 'abc',\n# '3': 'def',\n# '4': 'ghi',\n# '5': 'jkl',\n# '6': 'mno',\n# '7': 'pqrs',\n# '8': 'tuv',\n# '9': 'wxyz'\n# }\n\n# return reduce(lambda combPrev, digit: [comb + letter for comb in combPrev for letter in digitLetterMap[digit]], digits, [''])\n"} {"blob_id": "94a557d950315fe4d759a440035f951bf65f143e", "repo_name": "miketran238/LeetCode", "path": "/Trie/211. Design Add and Search Words Data Structure.py", "length_bytes": 1012, "score": 3.8125, "int_score": 4, "content": "class TrieNode:\n def __init__(self):\n self.child = {}\n self.isLeaf = False\n \nclass WordDictionary:\n \n def __init__(self):\n self.root = TrieNode()\n \n def addWord(self, word: str) -> None:\n node = self.root\n for w in word:\n if not w in node.child:\n node.child[w] = TrieNode()\n node = node.child[w]\n node.isLeaf = True\n\n def search(self, word: str) -> bool:\n def dfs(root, idx):\n #print(root.child.keys(), idx)\n if idx == len(word):\n #print('here')\n return root.isLeaf\n if word[idx] == '.':\n for c in root.child.values():\n if dfs(c, idx+1):\n return True\n return False\n if word[idx] not in root.child: \n return False\n root = root.child[word[idx]]\n return dfs(root, idx+1)\n \n return dfs(self.root, 0)\n"} {"blob_id": "be4b80c8b1f4066a33decc02db70743e665ccc86", "repo_name": "basvasilich/leet-code", "path": "/142.py", "length_bytes": 923, "score": 3.703125, "int_score": 4, "content": "# https://leetcode.com/problems/linked-list-cycle-ii/\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution:\n def detectCycle(self, head: ListNode) -> ListNode:\n cur = head\n pointer_1 = None\n pointer_2 = None\n counter = 0\n need_pointer_2 = True\n\n while cur is not None and cur != pointer_1:\n\n if cur == pointer_2:\n need_pointer_2 = False\n pointer_1 = pointer_1.next\n\n if counter == 4 and need_pointer_2:\n counter = 0\n pointer_2 = pointer_2.next\n\n if pointer_1 is None:\n pointer_1 = head\n if pointer_2 is None:\n pointer_2 = head\n\n counter += 1\n cur = cur.next\n\n if cur is None:\n return cur\n\n return pointer_1\n"} {"blob_id": "af3b0005a3ad6bdd30882a06d8d4e0a2f3455f0c", "repo_name": "crazymerlyn/code", "path": "/euler/293.py", "length_bytes": 448, "score": 3.515625, "int_score": 4, "content": "from utils import primes, is_prime\n\nps = list(primes(40))\n\nlimit = 10 ** 9\n\nadmissible = set()\n\ndef make_admissibles(f):\n if f >= limit: return\n if f in admissible: return\n admissible.add(f)\n for p in ps:\n make_admissibles(f * p)\n if f % p: return\n\nmake_admissibles(2)\nadmissible = sorted(admissible)\n\nres = set()\nfor n in admissible:\n m = 2\n while not is_prime(m + n):\n m += 1\n res.add(m)\n\nprint sum(res)\n"} {"blob_id": "f5a8c264db14893dbc1d475d828933f6747ee27a", "repo_name": "dongxiaohuang/Naive-Bayesian-networks", "path": "/DAPICoursework01.py", "length_bytes": 3958, "score": 3.53125, "int_score": 4, "content": "#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# Coursework in Python\nfrom DAPICourseworkLibrary import *\nfrom numpy import *\n#\n# Coursework 1 begins here\n#\n# Function to compute the prior distribution of the variable root from the data set\ndef Prior(theData, root, noStates):\n prior = zeros((noStates[root]), float )\n# Coursework 1 task 1 should be inserted here\n for i in theData[:,root]:\n prior[i] += 1\n prior /= len(theData[:,root])\n# end of Coursework 1 task 1\n return prior\n# Function to compute a CPT with parent node varP and xchild node varC from the data array\n# it is assumed that the states are designated by consecutive integers starting with 0\ndef CPT(theData, varC, varP, noStates):\n cPT = zeros((noStates[varC], noStates[varP]), float )\n# Coursework 1 task 2 should be inserte4d here\n counterP = zeros((noStates[varP])) # the number of states of P\n for c,p in theData[:, [varC,varP]]:\n counterP[p] += 1\n cPT[c,p] += 1\n cPT /= counterP\n# end of coursework 1 task 2\n return cPT\n# Function to calculate the joint probability table of two variables in the data set\ndef JPT(theData, varRow, varCol, noStates):\n jPT = zeros((noStates[varRow], noStates[varCol]), float )\n#Coursework 1 task 3 should be inserted here\n for row,col in theData[:,[varRow, varCol]]:\n jPT[row, col] += 1\n jPT /= len(theData[:,varRow]);\n# end of coursework 1 task 3\n return jPT\n#\n# Function to convert a joint probability table to a conditional probability table\ndef JPT2CPT(aJPT):\n#Coursework 1 task 4 should be inserted here\n prior = zeros(len(aJPT[0])) # column length\n for row in range(len(aJPT[:,0])):\n for col in range(len(aJPT[0])):\n prior[col] += aJPT[row,col]\n prior /= sum(prior)\n aJPT /= prior\n# coursework 1 taks 4 ends here\n return aJPT\n\n\n# Function to query a naive Bayesian network\ndef Query(theQuery, naiveBayes):\n rootPdf = zeros((naiveBayes[0].shape[0]), float)\n# Coursework 1 task 5 should be inserted here\n for i in range(len(rootPdf)):\n rootPdf[i] = prior[i] # initial\n for j in range(len(theQuery)):\n rootPdf[i] *= naiveBayes[j+1][theQuery[j],i]\n rootPdf /= sum(rootPdf)\n# end of coursework 1 task 5\n return rootPdf\n\n# End of Coursework 1\n\n#\n# main program part for Coursework 1\n#\nnoVariables, noRoots, noStates, noDataPoints, datain = ReadFile(\"Neurones.txt\")\ntheData = array(datain)\nAppendString(\"results.txt\",\"Coursework One Results by Dongxiao Huang(dh4317)\")\nAppendString(\"results.txt\",\"\") #blank line\nAppendString(\"results.txt\",\"The prior probability of node 0\")\nprior = Prior(theData, 0, noStates)\nAppendList(\"results.txt\", prior)\n# Part1 Q2\nAppendString(\"results.txt\",\"\") #blank line\nAppendString(\"results.txt\",\"The conditional probability matrix P(2|0)\")\ncPT = CPT(theData, 2, 0, noStates)\nAppendArray(\"results.txt\", cPT)\n# Part1 Q3\nAppendString(\"results.txt\",\"\") #blank line\nAppendString(\"results.txt\",\"The joint probability matrix P(2&0)\")\njPT = JPT(theData, 2, 0, noStates)\nAppendArray(\"results.txt\", jPT)\n\n# Part1 Q4\nAppendString(\"results.txt\",\"\") #blank line\nAppendString(\"results.txt\",\"The conditional probability matrix P(2|0) calculated from the joint probability matrix P(2&0)\")\naJPT = JPT2CPT(jPT)\nAppendArray(\"results.txt\", aJPT)\n# Part1 Q5\nAppendString(\"results.txt\",\"\") #blank line\n\ncpt1 = CPT(theData, 1, 0, noStates)\ncpt2 = CPT(theData, 2, 0, noStates)\ncpt3 = CPT(theData, 3, 0, noStates)\ncpt4 = CPT(theData, 4, 0, noStates)\ncpt5 = CPT(theData, 5, 0, noStates)\nnaiveBayes = [prior,cpt1,cpt2,cpt3,cpt4,cpt5]\nAppendString(\"results.txt\",\"The results of queries[4,0,0,0,5] on the naive network\")\ntheQuery = [4,0,0,0,5]\nrootPdf = Query(theQuery, naiveBayes)\nAppendList(\"results.txt\", rootPdf)\nAppendString(\"results.txt\",\"The results of queries[6,5,2,5,5] on the naive network\")\ntheQuery = [6,5,2,5,5]\nrootPdf = Query(theQuery, naiveBayes)\nAppendList(\"results.txt\", rootPdf)\n\n\n# continue as described\n#\n"} {"blob_id": "c507f5ffcf16b39964b96c56c63b9c8188cfda4f", "repo_name": "robertjones/project-euler", "path": "/python/problem_35.py", "length_bytes": 793, "score": 3.640625, "int_score": 4, "content": "import math\nimport itertools as it\n\n\ndef prime_gen(lim):\n D = {}\n q = 2\n while q < lim:\n if q not in D:\n yield q\n D[q * q] = [q]\n else:\n for p in D[q]:\n D.setdefault(p + q, []).append(p)\n del D[q]\n q += 1\n\n\nLim = 10**6\nPrimes = list(prime_gen(Lim))\n\n\ndef isprime(x):\n return not(any(x % factor == 0\n for factor\n in it.takewhile(lambda n: n < math.ceil(x ** (1/2)),\n Primes)))\n\n\ndef rotations(num):\n digs = str(num)\n return (int(digs[i:] + digs[0:i]) for i in range(0, len(digs)))\n\n\ndef iscircular(num):\n return all(isprime(rotation) for rotation in rotations(num))\n\n\nprint(sum(1 for prime in Primes if iscircular(prime)))\n"} {"blob_id": "1cd548f1d7fd3d55b898fd5ae3584ff28b886d40", "repo_name": "dotastar/Leetcode-Design-CompanyEx", "path": "/Array/Reverse_Nodes_in_k-Group.py", "length_bytes": 1564, "score": 3.828125, "int_score": 4, "content": "'''\nGiven a linked list, reverse the nodes of a linked list k at a time and return its modified list.\n\nIf the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.\n\nYou may not alter the values in the nodes, only nodes itself may be changed.\n\nOnly constant memory is allowed.\n\nFor example,\nGiven this linked list: 1->2->3->4->5\n\nFor k = 2, you should return: 2->1->4->3->5\n\nFor k = 3, you should return: 3->2->1->4->5\n'''\n\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n # @param {ListNode} head\n # @param {integer} k\n # @return {ListNode}\n def reverseKGroup(self, head, k):\n if not head or k == 1: return head\n dummy = ListNode(0)\n dummy.next = head\n pre = dummy; cur = dummy\n num = 0\n \n while cur.next:\n cur = cur.next \n num += 1\n \n while num >= k:\n cur = pre.next\n for i in xrange(k-1):\n tmp = pre.next\n pre.next = cur.next\n cur.next = cur.next.next\n pre.next.next = tmp \n \n pre = cur\n num -= k\n \n return dummy.next \n \n # https://leetcode.com/discuss/20923/simple-python-solution-one-pass-no-additional-space-109ms\n # https://leetcode.com/discuss/21301/short-but-recursive-java-code-with-comments\n # https://leetcode.com/discuss/39901/python-o-n-time-o-1-space-recursive-solution\n"} {"blob_id": "9b7332b66b8c57ddb863c229bf6a2b92ad568ed6", "repo_name": "hisck/MC", "path": "/modelo ieee 754/sqrt.py", "length_bytes": 513, "score": 3.796875, "int_score": 4, "content": "import math\nfrom math import factorial\n\ndef sqrtSerie(x):\n res = 0\n for i in range(0, 100):\n res = res + (((((-1)**i) * factorial(2*i)) /\n ((1-2*i) * (factorial(i)**2) * (4**i))) * x**i)\n return res\n\ndef argumentReduction(x):\n return x/(2**k(x))\n\n\ndef k(x):\n return math.ceil(math.log2(x))\n\n\ndef g(x):\n return (2**(k(x)/2)) * (sqrtSerie(argumentReduction(x) - 1))\n\nvalor = input(\"valor a ser calculado: \")\nvalor_int = int (valor)\nres = g(valor_int)\nprint(f\"A resposta \u00e9 : {res}\")"} {"blob_id": "377433f890b6fa129d169b7203747b7626093e91", "repo_name": "pombredanne/GenomeIndexerAligner", "path": "/compression.py", "length_bytes": 4940, "score": 3.515625, "int_score": 4, "content": "# -*- coding: utf-8 -*-\r\n# @Time : 23.10.20\r\n# @Authors : Chenxi N. / Guillaume T.\r\n# @FileName: compression.py\r\n\r\n## IMPORT\r\n\r\nfrom input import read_fa\r\nfrom bwt import Burrows_Wheeler_Transform\r\n\r\n## FUNCTIONS\r\n\r\ndef save_string(string, filename):\r\n '''\r\n Save a string in a .txt file\r\n :param string: string to save\r\n :param filename: name of the save file (not the path)\r\n :return: Nothing\r\n '''\r\n\r\n directory = \"A:/Mes documents (HDD)/CBM/Project 1/save/\" #to change for each computer\r\n file = directory + filename + \".txt\"\r\n f = open(file, 'w')\r\n f.write(string)\r\n f.close()\r\n\r\ndef rle_compression(seq):\r\n '''\r\n Does a basic Run-Lenght Encoding\r\n :param seq: sequence to compress (string)\r\n :return: the compressed sequence (string)\r\n '''\r\n\r\n n = len(seq)\r\n i = 1\r\n res = ''\r\n previous = seq[0]\r\n count = 1\r\n while(i=1):\r\n if n>=k:\r\n res += '1'\r\n n = n-k\r\n else:\r\n res += '0'\r\n k /= 2\r\n return res\r\n\r\ndef binary_compression(seq):\r\n '''\r\n Compresses a genome sequence using binary sequences and ASCII characters\r\n :param seq: genome sequence to compress (string)\r\n :return: compressed sequence (string)\r\n '''\r\n n = len(seq)\r\n i = 0\r\n current = \"\"\r\n res = \"\"\r\n while(i=7:\r\n code = binary(current[0:7])\r\n current = current[7:]\r\n res += chr(code)\r\n i+=1\r\n res = current + '\\n' + res\r\n return res\r\n\r\ndef binary_decompression(seq):\r\n '''\r\n Decompresses a genome sequence using binary sequences and ASCII characters\r\n :param seq: genome sequence to decompress (string)\r\n :return: decompressed sequence (string)\r\n '''\r\n n = len(seq)\r\n i = 0\r\n current = \"\"\r\n res = \"\"\r\n end = \"\"\r\n while(seq[i]!=\"\\n\"):\r\n end += seq[i]\r\n i += 1\r\n i += 1\r\n while(i2):\r\n res += decode_dict[current[0:3]]\r\n current = current[3:]\r\n current = current + end\r\n while(len(current)>0):\r\n res += decode_dict[current[0:3]]\r\n current = current[3:]\r\n return res\r\n\r\n\r\n## EXAMPLES\r\n'''\r\nfa_example = \"A:/Mes documents (HDD)/CBM/Project 1/data_small/-CSCO-3h--genome.chr22.5K.fa\"\r\ngenome = read_fa(fa_example)\r\n\r\nbwt, rotated_genome = Burrows_Wheeler_Transform(genome)\r\n\r\nrle = rle_compression(bwt)\r\nbin = binary_compression(bwt)\r\n\r\nprint()\r\nprint(\"Original length : \", len(bwt))\r\nprint(\"RLE length : \", len(rle))\r\nprint(\"Binary length : \", len(bin))\r\n\r\nprint()\r\nprint(rle_decompression(rle) == bwt)\r\nprint(binary_decompression(bin) == bwt)\r\n'''\r\n"} {"blob_id": "14b6d3724cef13617a77954d111dfd1cc658cf90", "repo_name": "bhuvanradj/Artificial-Intelligence", "path": "/A* Maze Search/search.py", "length_bytes": 8831, "score": 3.5625, "int_score": 4, "content": "# search.py\n# ---------------\n# Licensing Information: You are free to use or extend this projects for\n# educational purposes provided that (1) you do not distribute or publish\n# solutions, (2) you retain this notice, and (3) you provide clear\n# attribution to the University of Illinois at Urbana-Champaign\n#\n# Created by Michael Abir (abir2@illinois.edu) on 08/28/2018\n\n\"\"\"\nThis is the main entry point for MP1. You should only modify code\nwithin this file -- the unrevised staff files will be used for all other\nfiles and classes when code is run, so be careful to not modify anything else.\n\"\"\"\n# Search should return the path.\n# The path should be a list of tuples in the form (row, col) that correspond\n# to the positions of the path taken by your search algorithm.\n# maze is a Maze object based on the maze from the file specified by input filename\n# searchMethod is the search method specified by --method flag (bfs,dfs,astar,astar_multi,extra)\nfrom itertools import groupby\nimport math\nimport queue\n\ndef search(maze, searchMethod):\n return {\n \"bfs\": bfs,\n \"astar\": astar,\n \"astar_corner\": astar_corner,\n \"astar_multi\": astar_multi,\n \"extra\": extra,\n }.get(searchMethod)(maze)\n\n\ndef bfs(maze):\n \"\"\"\n Runs BFS for part 1 of the assignment.\n\n @param maze: The maze to execute the search on.\n\n @return path: a list of tuples containing the coordinates of each state in the computed path\n \"\"\"\n # TODO: Write your code here\n start = maze.getStart()\n dots = maze.getObjectives()\n goal = dots[0]\n Q = queue.Queue()\n vis = []\n p = []\n paths = {}\n \n Q.put(start)\n vis.append(start)\n paths[start] = None\n p.append(goal)\n\n while (not Q.empty()):\n cur = Q.get()\n ngb = maze.getNeighbors(cur[0],cur[1])\n \n for n in ngb:\n if (n not in vis and maze.isValidMove(n[0],n[1])):\n Q.put(n)\n vis.append(n)\n paths[n] = cur\n \n itr = goal\n while(itr!=start):\n p.append(paths[itr])\n itr = paths[itr]\n p.append(start)\n p.reverse()\n p.pop(0)\n \n return p\n\n\ndef astar(maze):\n \"\"\"\n Runs A star for part 1 of the assignment.\n\n @param maze: The maze to execute the search on.\n\n @return path: a list of tuples containing the coordinates of each state in the computed path\n \"\"\"\n # TODO: Write your code here\n start = maze.getStart()\n dots = maze.getObjectives()\n goal = dots[0]\n openl = []\n closel = []\n path = {}\n f = {}\n g = {}\n h = {}\n\n g[start] = 0\n h[start] = manh_dist(start,goal)\n f[start] = g[start] + h[start]\n openl.append(start)\n \n while(len(openl)!=0):\n q = minf(openl,g,h)\n closel.append(q)\n openl.remove(q)\n\n if(q==goal):\n tmp = []\n itr = goal\n tmp.append(itr)\n while(itr!=start):\n tmp.append(path[itr])\n itr = path[itr]\n tmp.append(start)\n tmp.reverse()\n tmp.pop(0)\n \n return tmp\n\n ngb = maze.getNeighbors(q[0],q[1]) \n for n in ngb:\n if(not maze.isValidMove(n[0],n[1]) or n in closel):\n continue\n else:\n if(n not in openl):\n openl.append(n)\n path[n] = q\n g[n] = g[q] + 1\n h[n] = manh_dist(n,goal)\n f[n] = g[n] + h[n]\n elif(n in openl):\n if(g[n]>g[q]+1):\n path[n] = q\n g[n] = g[q] + 1\n h[n] = manh_dist(n,goal)\n f[n] = g[n] + h[n]\n\n\ndef astar_corner(maze):\n \"\"\"\n Runs A star for part 2 of the assignment in the case where there are four corner objectives.\n \n @param maze: The maze to execute the search on.\n \n @return path: a list of tuples containing the coordinates of each state in the computed path\n \"\"\"\n # TODO: Write your code here\n\n return astar_multi(maze)\n\ndef astar_multi(maze):\n \"\"\"\n Runs A star for part 3 of the assignment in the case where there are\n multiple objectives.\n\n @param maze: The maze to execute the search on.\n\n @return path: a list of tuples containing the coordinates of each state in the computed path\n \"\"\"\n # TODO: Write your code here\n \n mst = minspantree(maze)\n #print(mst)\n start = mst.pop(0)\n path = []\n '''\n mstdic = {}\n order={}\n for m in mst:\n mstdic[m] = len(multhelp(maze,m,start))-2\n mstdic = sorted(mstdic.items(),key=lambda x: x[1])\n \n f1 = mstdic[-1][0]\n f2 = mstdic[-2][0]\n \n while(len(mstdic)>2):\n x=len(multhelp(maze,f1,f2))-2\n y=len(multhelp(maze,f2,start))-2\n order[f2]=x+y\n mstdic.remove(mstdic[-2])\n f1 = mstdic[-1][0]\n f2 = mstdic[-2][0]\n dict(mstdic)\n # print(order)\n '''\n\n while(len(mst)!=0):\n v = mst[0]\n mst.remove(v)\n p = multhelp(maze,v,start)\n path.extend(p)\n start = p[-1]\n '''\n i=0\n while(ig[q]+1):\n path[n] = q\n g[n] = g[q] + 1\n h[n] = manh_dist(n,goal)\n f[n] = g[n] + h[n]\n\n \n\ndef manh_dist(cur,goal):\n \"\"\"\n Returns Manhattan Distance from current position to goal position.\n\n @param cur: current position in maze.\n\n @param goal: goal destination\n\n @return dist: Manhattan Distance from cur to goal\n \n \"\"\"\n \n h = abs(cur[0]-goal[0]) + abs(cur[1]-goal[1])\n return h\n\ndef minf(openl,g,h):\n \"\"\"\n Returns the position with the minimum f=g+h value on the openl list\n\n @param openl: Open list of positions\n\n @param g: Dictionary for position and distance from start pairings\n\n @param h: Dictionary for position and distance to goal pairings\n \n @return minpos: Position with the least f=g+h score\n \"\"\"\n \n tmp = {}\n for k in openl:\n tmp[k] = g[k]+h[k]\n minpos = min(tmp,key=tmp.get)\n return minpos\n\ndef minspantree(maze):\n \"\"\"\n Returns the MST in set of ordered coordinates\n\n @param maze: Input maze\n\n @return mstset: Minimum Spanning set of coordinates\n \"\"\"\n start = maze.getStart()\n dots = maze.getObjectives()\n mst = {}\n mstset = []\n for d in dots:\n mst[d] = math.inf\n mst[start] = 0\n num=len(mst)\n\n while(len(mstset)!= num):\n cur = min(mst,key=mst.get)\n del mst[cur]\n if(cur not in mstset):\n mstset.append(cur)\n for v in dots:\n if(v!=cur and v in mst):\n if(mst[v] > manh_dist(cur,v)):\n mst[v] = manh_dist(cur,v)\n #print(mst)\n #print(mstset)\n return mstset\n\ndef extra(maze):\n \"\"\"\n Runs extra credit suggestion.\n\n @param maze: The maze to execute the search on.\n\n @return path: a list of tuples containing the coordinates of each state in the computed path\n \"\"\"\n # TODO: Write your code here\n return astar_multi(maze)\n"} {"blob_id": "da3db9aea6500c8315df4dad26d5ea188426c362", "repo_name": "zelalemgetahun9374/Tic-tac-toe-AI", "path": "/player.py", "length_bytes": 2956, "score": 3.96875, "int_score": 4, "content": "from abc import ABC, abstractmethod\r\nfrom time import sleep\r\nimport random\r\nimport math\r\n\r\n\r\nclass Player(ABC):\r\n def __init__(self, letter):\r\n self.letter = letter\r\n\r\n @abstractmethod\r\n def get_move(self, game):\r\n pass\r\n\r\n\r\nclass HumanPlayer(Player):\r\n def __init__(self, letter):\r\n super().__init__(letter)\r\n\r\n def get_move(self, game):\r\n while True:\r\n square = input(f\"{self.letter}'s turn. Enter your move (0 - 8): \")\r\n\r\n try:\r\n square = int(square)\r\n\r\n if square not in game.available_moves():\r\n raise ValueError\r\n\r\n return square\r\n except:\r\n print(\"Invalid move. Try again!\")\r\n\r\n\r\nclass RandomComputerPlayer(Player):\r\n def __init__(self, letter):\r\n super().__init__(letter)\r\n\r\n def get_move(self, game):\r\n square = random.choice(game.available_moves())\r\n print(f\"{self.letter}'s turn. Move: {square}\")\r\n sleep(0.5) # wait for 0.5 seconds\r\n return square\r\n\r\n\r\nclass SmartComputerPlayer(Player):\r\n def __init__(self, letter):\r\n super().__init__(letter)\r\n\r\n def get_move(self, game):\r\n if len(game.available_moves()) == 9:\r\n print('available moves')\r\n print(game.available_moves())\r\n square = random.choice(game.available_moves())\r\n else:\r\n square = self.minmax(game, self.letter)['position']\r\n\r\n print(f\"{self.letter}'s turn. Move: {square}\")\r\n sleep(0.5) # wait for 0.5 seconds\r\n return square\r\n\r\n # use the maximize minimize algorithm\r\n def minmax(self, game, player):\r\n max_player = self.letter\r\n other_player = 'X' if player == 'O' else 'O'\r\n\r\n if game.winner == other_player:\r\n return {'position': None, 'score': 1 * (game.num_empty_squares() + 1) if other_player == self.letter else -1 * (game.num_empty_squares() + 1)}\r\n\r\n if not game.num_empty_squares():\r\n return {'position': None, 'score': 0}\r\n\r\n if player == self.letter:\r\n best = {'position': None, 'score': -math.inf} # maximize our score\r\n else:\r\n # minimize opponent's score\r\n best = {'position': None, 'score': math.inf}\r\n\r\n for possible_move in game.available_moves():\r\n game.make_move(possible_move, player)\r\n simulation = self.minmax(game, other_player)\r\n\r\n # indicates the next optimal move\r\n simulation['position'] = possible_move\r\n game.board[possible_move] = ' ' # remove simulated move\r\n game.winner = None # set winner back to None\r\n\r\n if player == self.letter:\r\n if simulation['score'] > best['score']:\r\n best = simulation\r\n else:\r\n if simulation['score'] < best['score']:\r\n best = simulation\r\n\r\n return best\r\n"} {"blob_id": "bd53d6ffa56eada607acd27987aeb0bb5d053aee", "repo_name": "burakbayramli/books", "path": "/programming_computer_vision_with_python/cvbook-contrib/sfm.py", "length_bytes": 5464, "score": 3.59375, "int_score": 4, "content": "import numpy\n\ndef compute_fundamental(x1, x2):\n '''Computes the fundamental matrix from corresponding points x1, x2 using\n the 8 point algorithm.'''\n n = x1.shape[1]\n if x2.shape[1] != n:\n raise ValueError('Number of points do not match.')\n\n # Normalization is done in compute_fundamental_normalized().\n A = numpy.zeros((n, 9))\n for i in range(n):\n A[i] = [x1[0, i] * x2[0, i], x1[0, i] * x2[1, i], x1[0, i] * x2[2, i],\n x1[1, i] * x2[0, i], x1[1, i] * x2[1, i], x1[1, i] * x2[2, i],\n x1[2, i] * x2[0, i], x1[2, i] * x2[1, i], x1[2, i] * x2[2, i],\n ]\n\n # Solve A*f = 0 using least squares.\n U, S, V = numpy.linalg.svd(A)\n F = V[-1].reshape(3, 3)\n\n # Constrain F to rank 2 by zeroing out last singular value.\n U, S, V = numpy.linalg.svd(F)\n S[2] = 0\n F = numpy.dot(U, numpy.dot(numpy.diag(S), V))\n return F / F[2, 2]\n\n\ndef compute_fundamental_normalized(x1, x2):\n '''Computes the fundamental matrix from corresponding points x1, x2 using\n the normalized 8 point algorithm.'''\n n = x1.shape[1]\n if x2.shape[1] != n:\n raise ValueError('Number of points do not match.')\n\n # normalize.\n x1 = x1 / x1[2]\n mean_1 = numpy.mean(x1[:2], axis=1)\n S1 = numpy.sqrt(2) / numpy.std(x1[:2])\n T1 = numpy.array([[S1, 0, -S1 * mean_1[0]],\n [0, S1, -S1 * mean_1[1]],\n [0, 0, 1]])\n x1 = numpy.dot(T1, x1)\n\n x2 = x2 / x2[2]\n mean_2 = numpy.mean(x2[:2], axis=1)\n S2 = numpy.sqrt(2) / numpy.std(x2[:2])\n T2 = numpy.array([[S2, 0, -S2 * mean_2[0]],\n [0, S2, -S2 * mean_2[1]],\n [0, 0, 1]])\n x2 = numpy.dot(T2, x2)\n\n F = compute_fundamental(x1, x2)\n\n # denormalize.\n F = numpy.dot(T1.T, numpy.dot(F, T2))\n return F / F[2, 2]\n\n\ndef compute_right_epipole(F):\n '''Returns e with F * e = 0 (call with F.T for left epipole).'''\n U, S, V = numpy.linalg.svd(F)\n e = V[-1] # S is diag([l1, l2, 0]). e's scale is arbitrary.\n return e / e[2]\n\n\ndef plot_epipolar_line(im, F, x, epipole=None, show_epipole=True):\n '''Plot the epipole and epipolar line F*x = 0.'''\n import pylab\n\n m, n = im.shape[:2]\n line = numpy.dot(F, x)\n\n t = numpy.linspace(0, n, 100)\n lt = numpy.array([(line[2] + line[0] * tt) / (-line[1]) for tt in t])\n\n ndx = (lt >= 0) & (lt < m)\n pylab.plot(t[ndx], lt[ndx], linewidth=2)\n\n if show_epipole:\n if epipole is None:\n epipole = compute_right_epipole(F)\n pylab.plot(epipole[0] / epipole[2], epipole[1] / epipole[2], 'r*')\n\n\ndef triangulate_point(x1, x2, P1, P2):\n '''Given two image coordinates x1, x2 of the same point X under different\n projections P1, P2, recovers X.'''\n M = numpy.zeros((6, 6))\n M[:3, :4] = P1\n M[:3, 4] = -x1\n\n M[3:, :4] = P2\n M[3:, 5] = -x2 # Intentionally 5, not 4.\n\n U, S, V = numpy.linalg.svd(M)\n X = V[-1, :4]\n return X / X[3]\n\n\ndef triangulate(x1, x2, P1, P2):\n '''Given n pairs of points, returns their 3d coordinates.'''\n n = x1.shape[1]\n if x2.shape[1] != n:\n raise ValueError('Number of points do not match.')\n\n X = [triangulate_point(x1[:, i], x2[:, i], P1, P2) for i in range(n)]\n return numpy.array(X).T\n\n\ndef compute_P(x, X):\n '''Computes camera matrix from corresponding (homogeneous)\n 2D and 3D points.'''\n n = x.shape[1]\n if X.shape[1] != n:\n raise ValueError('Number of points do not match.')\n\n M = numpy.zeros((3 * n, 12 + n))\n for i in range(n):\n M[3 * i , 0:4] = X[:, i]\n M[3 * i + 1 , 4:8] = X[:, i]\n M[3 * i + 2 , 8:12] = X[:, i]\n M[3 * i:3 * i + 3, i + 12] = -x[:, i]\n\n U, S, V = numpy.linalg.svd(M)\n return V[-1, :12].reshape((3, 4))\n\n\ndef skew(a):\n '''Skew matrix A such that a x v = A*v for any v.'''\n return numpy.array([[0, -a[2], a[1]],\n [a[2], 0, -a[0]],\n [-a[1], a[0], 0]])\n\n\ndef compute_P_from_fundamental(F):\n '''Computes second camera matrix, assuming P1 = [I 0].\n Only up to a homography, since no calibration is given.'''\n e = compute_right_epipole(F.T) # left epipole\n Te = skew(e)\n return numpy.vstack((numpy.dot(Te, F.T).T, e)).T\n\n\ndef compute_P_from_essential(E):\n # make sure E is rank 2\n U, S, V = numpy.linalg.svd(E)\n if numpy.linalg.det(numpy.dot(U, V)) < 0:\n V = -V\n E = numpy.dot(U, numpy.dot(numpy.diag([1, 1, 0]), V))\n\n # create matrices (\"Hartley p 258\" XXX)\n Z = skew([0, 0, -1]) # FIXME: Unused?\n W = numpy.array([[0, -1, 0], [1, 0, 0], [0, 0, 1]])\n\n P2 = [numpy.vstack((numpy.dot(U, numpy.dot(W, V)).T, U[:,2])).T,\n numpy.vstack((numpy.dot(U, numpy.dot(W, V)).T, -U[:,2])).T,\n numpy.vstack((numpy.dot(U, numpy.dot(W.T, V)).T, U[:,2])).T,\n numpy.vstack((numpy.dot(U, numpy.dot(W.T, V)).T, -U[:,2])).T]\n return P2\n\n\nclass RansacModel(object):\n def fit(self, data):\n data = data.T\n x1 = data[:3, :8]\n x2 = data[3:, :8]\n return compute_fundamental_normalized(x1, x2)\n\n def get_error(self, data, F):\n data = data.T\n x1 = data[:3]\n x2 = data[3:]\n\n # Sampson distance as error.\n Fx1 = numpy.dot(F, x1)\n Fx2 = numpy.dot(F, x2)\n denom = Fx1[0]**2 + Fx1[1]**2 + Fx2[0]**2 + Fx2[1]**2\n err = (numpy.diag(numpy.dot(x1.T, numpy.dot(F, x2))))**2 / denom\n return err\n\n\ndef F_from_ransac(x1, x2, model, maxiter=5000, match_threshold=1e-6):\n import ransac\n data = numpy.vstack((x1, x2))\n F, ransac_data = ransac.ransac(data.T, model, 8, maxiter, match_threshold, 20,\n return_all=True)\n return F, ransac_data['inliers']\n"} {"blob_id": "5c39650f25a57ae94ceb83d32aa34c5b4c928e28", "repo_name": "henrylin2008/Coding_Problems", "path": "/Graphs/Single-Cycle-Check.py", "length_bytes": 3144, "score": 3.703125, "int_score": 4, "content": "# link: https://www.algoexpert.io/questions/Single%20Cycle%20Check\n# Single Cycle Check\n# Difficulty: Medium\n\n# You're given an array of integers where each integer represents a jump of its value in the array. For instance, the\n# integer 2 represents a jump of two indices forward in the array; the integer -3 represents a jump of three indices\n# backward in the array.\n# If a jump spills past the array's bounds, it wraps over to the other side. For instance, a jump of -1 at index 0\n# brings us to the last index in the array. Similarly, a jump of 1 at the last index in the array brings us to index 0.\n# Write a function that returns a boolean representing whether the jumps in the array form a single cycle. A single\n# cycle occurs if, starting at any index in the array and following the jumps, every element in the array is visited\n# exactly once before landing back on the starting index.\n\n# Sample Input:\n# array = [2, 3, 1, -4, -4, 2]\n\n# Sample Output:\n# true\n\n\n# Time: O(n)\n# Space: O(1)\n# Logic: set a variable numElementsVisited to keep track number of elements have visited, and a variable currentIdx to\n# keep track of current index; the goal is while moving around the array, it should return to the first index\n# last. Edge cases to check when there's a loop that it returns to first index before reaching all elements in\n# the array. Run a while loop before less than the length of array, an edge case where if it returns to the first\n# index before reaching all elements in the array, then return False; next increment numElementsVisit by 1, and\n# calculate the next index; use a separate function to find out the next index, which it covers the wrap\n# around cases in the array. For case that is moving forward, next index is calculated as\n# (currentIdx + jump) % len(array); if moving backward, the formula to find out next index:\n# (currentIdx + jump) % len(array) + len(array). Then return true if currentIdx is at index 0 (starting point)\n# conditions:\n# * number of elements visited == len(array)\n# * last Index is back to the initial index (0)\n# * edge case: loop/s that returns to initial index before reaches all elements\n# * next index wrap around cases: moving forward and moving backward\ndef hasSingleCycle(array):\n numElementsVisited = 0 # number of elements have visited\n currentIdx = 0 # starting index\n while numElementsVisited < len(array): # when total number of elements visited < len(array)\n if numElementsVisited > 0 and currentIdx == 0: # in case a repeated loop/s happens before reach all elements\n return False\n numElementsVisited += 1 # increment elements visited\n currentIdx = getNextIdx(currentIdx, array) # next index\n return currentIdx == 0 # back to the starting index\n\n\ndef getNextIdx(currentIdx, array):\n jump = array[currentIdx] # how many index have to jump\n nextIdx = (currentIdx + jump) % len(array) # next index, it covers wrap around cases\n return nextIdx if nextIdx >= 0 else nextIdx + len(array) # nextIdx + len(array) covers negative case\n"} {"blob_id": "25c67e3b036a40b761dc7427675cdf0ac86c5d8c", "repo_name": "davidebiasion/project-euler", "path": "/p41.py", "length_bytes": 1972, "score": 4.25, "int_score": 4, "content": "# Utility function to swap the characters in a character list\ndef swap(A, i, j):\n\n\tc = A[i]\n\tA[i] = A[j]\n\tA[j] = c\n\n\n# Utility function to reverse a list between specified indexes\ndef reverse(A, i, j):\n\n\t# do till two endpoints intersect\n\twhile i < j:\n\t\tswap(A, i, j)\n\t\ti = i + 1\n\t\tj = j - 1\n\n\n# Iterative function to find permutations of a string in Python\ndef permutations(str, n):\n\tperm = []\n\n\t# sort the string in a natural order\n\ts = sorted(list(str))\n\n\twhile True:\n\n\t\t# print the current permutation\n\t\tperm.append(''.join(s))\n\t\t#print(''.join(s), end=' ')\n\n\t\t''' The following code will rearrange the string to the next lexicographically\n\t\t\tordered permutation (if any) or return if we are already at\n\t\t\tthe highest possible permutation '''\n\n\t\t# Find the largest index `i` such that `s[i-1]` is less than `s[i]`\n\t\ti = n - 1\n\t\twhile s[i - 1] >= s[i]:\n\t\t\t# if `i` is the first index of the string, we are already at the\n\t\t\t# last possible permutation (string is sorted in reverse order)\n\t\t\ti = i - 1\n\t\t\tif i == 0:\n\t\t\t\treturn perm\n\n\t\t# find the highest index `j` to the right of index `i` such that\n\t\t# `s[j] > s[i-1]` (`s[i\u2026n-1]` is sorted in reverse order)\n\n\t\tj = n - 1\n\t\twhile j > i and s[j] <= s[i - 1]:\n\t\t\tj = j - 1\n\n\t\t# swap character at index `i-1` with index `j`\n\t\tswap(s, i - 1, j)\n\n\t\t# reverse substring `s[i\u2026n-1]`\n\t\treverse(s, i, n - 1)\n\n\n\ndef is_pandigital(s, n):\n\ts = sorted(s)\n\n\tj = 0\n\twhile j M:\n\t\t\t\tM = num_p\n\n\tif M != -1:\n\t\tprint(M)\n\t\tbreak\n"} {"blob_id": "57cd1a13986ce44b1a338b3b20c05a913df313b3", "repo_name": "Seremane/tutorial-3", "path": "/Tut2Q2.py", "length_bytes": 799, "score": 3.546875, "int_score": 4, "content": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jun 13 01:10:03 2016\n\n@author: ontibile\n\"\"\"\n\nimport numpy\nfrom matplotlib import pyplot as plt\n\n#the correlaltion function f*g=int(f(x)*g(x+y)).it can be proved that \n################f*g=ifft(dft(f)*conj(dft(g)))######################\n#write a routine to take the correlation function of two arrays\n#plot the correlation function of the gaussian with itself\n\nfrom numpy.fft import fft,ifft\n\n\ndef mycorr(x,y):\n assert(x.size==y.size) \n ft1=fft(x)\n ft2=fft(y)\n ft2conj=numpy.conj(ft2)\n return numpy.real(ifft(ft1*ft2conj))\n\nif __name__=='__main__':\n x=numpy.arange(-20,20,0.1)\n y=numpy.exp(-0.5*x**2/(2**2))\n \n ycorr=mycorr(y,y)\n plt.plot(x,ycorr)\n plt.savefig('correlation_fit')\n plt.show()\n\n"} {"blob_id": "301ae436e59ff7609113d9c4e8aff4061090a4b9", "repo_name": "VVKot/coding-competitions", "path": "/leetcode/python/979_distribute_coins_in_binary_tree.py", "length_bytes": 1633, "score": 3.734375, "int_score": 4, "content": "\"\"\"\nT: O(N)\nS: O(N)\n\nWe need to find how far we move coins from each subtree. We find the number of\ncoins that we more from left and right, and add their magnitude to the result.\nThat's because these coins will be moved at least this number of times. After\nthat, we return the correct balance for the current node, which possibly will\nbe processed by its parent. Note that since the number of coins is guaranteed\nto be the same as the number of nodes, the balance of root is guaranteed\nto be zero.\n\"\"\"\n\nfrom typing import Dict, Optional\n\n\nclass TreeNode:\n\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution:\n\n def distributeCoins(self, root: TreeNode) -> int:\n distribution_cost = 0\n nodes_to_process = [root]\n nodes_balances = {None: 0} # type: Dict[Optional[TreeNode], int]\n while nodes_to_process:\n curr = nodes_to_process[-1]\n if curr:\n left, right = curr.left, curr.right\n if left and left not in nodes_balances:\n nodes_to_process.append(left)\n elif right and right not in nodes_balances:\n nodes_to_process.append(right)\n else:\n nodes_to_process.pop()\n left_balance = nodes_balances[left]\n right_balance = nodes_balances[right]\n distribution_cost += abs(left_balance) + abs(right_balance)\n nodes_balances[curr] = left_balance + right_balance + \\\n curr.val - 1\n return distribution_cost\n"} {"blob_id": "3bbc6e46566b85345390bdf8a4441e1bfddef920", "repo_name": "cs1201/AOC_2019", "path": "/Day3/Day3.py", "length_bytes": 1026, "score": 3.78125, "int_score": 4, "content": "# ADVENT OF CODE 2019 - Day 3\nimport math\nfrom itertools import accumulate, count\n\n# Open file and return lines as list\nwith open(\"input.txt\") as fp:\n data = fp.readlines()\n wires = list(l.split(',') for l in data)\n\nmove = {'R': (1,0), 'L': (-1,0), 'U': (0,1), 'D': (0,-1)}\n\ndef get_steps(wire):\n step = (move[inst[0]] for inst in wire for _ in range(int(inst[1:])))\n return dict(reversed(list(zip(zip(*map(accumulate, zip(*step))), count(1)))))\n\ndef manhattan(point):\n return (abs(point[0]) + abs(point[1]))\n\nroute1 = get_steps(wires[0])\nroute2 = get_steps(wires[1])\n\n# Get duplicate points in each route\nduplicate_points = set(route1.keys()) & set(route2.keys())\n\ndef part_1():\n return min(map(manhattan, duplicate_points))\n\ndef part_2():\n # Get distance for each duplicate point\n distances = ((route1[p], route2[p]) for p in duplicate_points)\n return int(min(map(sum, distances)))\n\nif __name__ == \"__main__\":\n print(f\"Day2: pt.1 Result: {part_1()}\")\n print(f\"Day2: pt.2 Result: {part_2()}\")"} {"blob_id": "fe6334eedd387a78dd01954716eca67a12d61dba", "repo_name": "annefreeman/PythonPractice", "path": "/SortingSearching/binary_search.py", "length_bytes": 1441, "score": 4.0625, "int_score": 4, "content": "# Uses python3\nimport sys\n\n\n# Task: The goal in this code problem is to implement the binary search algorithm.\n# Input: The first line of the input contains an integer \ud835\udc5b \n# and a sequence \ud835\udc4e0 < \ud835\udc4e1 < . . . < \ud835\udc4e\ud835\udc5b\u22121 of \ud835\udc5b pairwise distinct positive integers in increasing order. \n# The next line contains an integer \ud835\udc58 and \ud835\udc58 positive integers \ud835\udc4f0, \ud835\udc4f1, . . . , \ud835\udc4f\ud835\udc58\u22121.\n# Output: For all \ud835\udc56 from 0 to \ud835\udc58\u22121, output an index 0\u2264\ud835\udc57\u2264\ud835\udc5b\u22121 such that \ud835\udc4e\ud835\udc57 =\ud835\udc4f\ud835\udc56 \n# or -1 if there is no such index.\n\ndef binary_search(A, low, high, key):\n if high < low:\n return -1\n middle = int(low + ((high-low)/2))\n if key == A[middle]:\n return middle\n elif key < A[middle]:\n return binary_search(A, low, middle-1, key)\n else:\n return binary_search(A, middle+1, high, key)\n\ndef linear_search(a, x):\n for i in range(len(a)):\n if a[i] == x:\n return i\n return -1\n\nif __name__ == '__main__':\n # type in control + D to get this to work\n input = sys.stdin.read()\n data = list(map(int, input.split()))\n n = data[0]\n m = data[n + 1] #raw data to search with\n a = data[1 : n + 1] #keys to search in/compare to\n \n for x in data[n + 2:]:\n print(binary_search(a, 0, len(a)-1, x), end = ' ')\n # replace with the call to binary_search when implemented\n #print(linear_search(a, x), end = ' ')\n"} {"blob_id": "d6e7f1f4451dacf5e4f5021368bb83f6ce813370", "repo_name": "vincent507cpu/Comprehensive-Algorithm-Solution", "path": "/LeetCode/easy - Hash Table/690. Employee Importance/solution.py", "length_bytes": 1322, "score": 3.75, "int_score": 4, "content": "\"\"\"\n# Definition for Employee.\nclass Employee:\n def __init__(self, id: int, importance: int, subordinates: List[int]):\n self.id = id\n self.importance = importance\n self.subordinates = subordinates\n\"\"\"\n\nclass Solution:\n # my solution (my 1st recruseion!)\n def getImportance(self, employees: List['Employee'], id: int) -> int:\n res = 0\n\n for k in employees:\n if k.id == id:\n res += k.importance\n if not k.subordinates:\n return res\n else:\n for j in k.subordinates:\n res += self.getImportance(employees, j)\n \n return res\n \n # best solution\n # https://leetcode.com/problems/employee-importance/discuss/112611/3-liner-Python-Solution-(beats-99)\n def getImportance(self, employees: List['Employee'], id: int) -> int:\n \"\"\"\n :type employees: Employee\n :type id: int\n :rtype: int\n \"\"\"\n # Time: O(n)\n # Space: O(n)\n emps = {employee.id: employee for employee in employees}\n def dfs(id):\n subordinates_importance = sum([dfs(sub_id) for sub_id in emps[id].subordinates])\n return subordinates_importance + emps[id].importance\n return dfs(id)"} {"blob_id": "aba1ebeee163adc3adc9ff174602b6b5e3ad63ab", "repo_name": "aguerra/exercises", "path": "/bit_manipulation/counting_bits.py", "length_bytes": 492, "score": 3.703125, "int_score": 4, "content": "\"\"\"\nThere's an array of 10,000 16-bit values, how do you count the bits most\nefficiently.\n\"\"\"\n\nlookup_table = [bin(n).count(\"1\") for n in range(256)]\n\n\ndef bit_count(array):\n \"\"\"Return the bit count.\n\n >>> bit_count([])\n 0\n\n >>> bit_count([0, 1])\n 1\n\n >>> bit_count([2, 65535])\n 17\n \"\"\"\n s = 0\n for item in array:\n s += lookup_table[item >> 8] + lookup_table[item & 0xff]\n return s\n\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n"} {"blob_id": "7975325728caa5fe8ca34d41fb27a89a5d9b1ffc", "repo_name": "iamsims/Neural_Networks", "path": "/3_neuron_Hopfield_network.py", "length_bytes": 933, "score": 3.828125, "int_score": 4, "content": "# Three-neuron Hopfield network\n# memory upto 3 stages\n\nimport numpy as np\n\n\nclass Hopfield:\n def __init__(self, y):\n self.y = y\n self.memory = 3 # number of states to be memorised by the network\n self.I = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]\n\n def calculate(self):\n sum = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]\n\n for i in range(self.memory):\n y = np.array(self.y[i]).reshape(1,3) # convert 1D to 1*3\n transpose = np.array(y).T.reshape(3,1) # transpose of 1*3 reshaping into 3*1\n sum = np.add(sum, np.multiply(transpose,y))\n\n # calculate memory*I (multiply all elements by M)\n arr = self.I\n for i in range(len(arr)):\n arr[i] = [self.memory * x for x in arr[i]]\n\n result = np.subtract(sum,arr)\n\n print(result)\n\n\ny = [[1, 1, 1],[-1, -1, -1], [1, -1, -1]] # input for network [y1,y2]\n\n\nobj = Hopfield(y)\nobj.calculate()\n"} {"blob_id": "d50eeb6425063c6eff1d84e531a5cb367d525add", "repo_name": "luckytime10000/AlgorithmCHUNZHAO", "path": "/Week_02/347topKFrequent.py", "length_bytes": 2794, "score": 3.671875, "int_score": 4, "content": "import collections\n\nclass Solution(object):\n def topKFrequent(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: List[int]\n \"\"\"\n # \u624b\u52a8\u7ef4\u62a4\u4e00\u4e2a\u6700\u5c0f\u5806\uff0c\u4ee5[\u6570\u5b57, \u6b21\u6570]\u4e2d\u7684\u6b21\u6570\u4f5c\u4e3a\u6bd4\u8f83\u7684\u6839\u636e\n\n # \u6700\u5c0f\u5806\u4e0b\u6c89\u51fd\u6570\n # \u8f93\u5165 \u6700\u5c0f\u5806 \u5f53\u524d\u7684\u4e0b\u6807\n # \u529f\u80fd\uff1a \u4ece\u5f53\u524d\u4e0b\u6807\u5f00\u59cb\u4e0b\u6c89\uff0c\u76f4\u5230\u6700\u5c0f\u5806\u5408\u6cd5\n def siftDown(minHeap, cur):\n val = minHeap[cur] # \u4fdd\u5b58\u5f53\u524d\u4e0b\u6807\u7684\u503c\n left = 2 * cur + 1\n right = 2 * cur + 2\n # mi \u6307\u5411 \u5de6\u53f3\u513f\u5b50\u4e2d\u8f83\u5c0f\u8005\uff0c\u6700\u5c0f\u5806\u9700\u8981\u8f83\u5c0f\u503c\u4e0a\u4f4d\n if right < len(minHeap) and minHeap[right][1] < minHeap[left][1]:\n mi = right\n else:\n mi = left\n # while \u4e2d\u53ea\u8ba8\u8bba\u53f3\u8282\u70b9\u5408\u6cd5\u65f6\u7684\u4e0b\u6c89\n while right < len(minHeap) and minHeap[mi][1] < val[1]:\n minHeap[cur] = minHeap[mi] # \u7b26\u5408\u6761\u4ef6\uff0c\u4e0b\u6c89\n cur = mi # \u5404\u4e2a\u6307\u9488\u5411\u4e0b\u8d70\n left = 2 * cur + 1\n right = 2 * cur + 2\n if right < len(minHeap) and minHeap[right][1] < minHeap[left][1]:\n mi = right\n else:\n mi = left\n # \u5faa\u73af\u7ed3\u675f\u540e\uff1a \u6ca1\u6709\u53f3\u513f\u5b50 \u6216\u8005 \u503c\u4e0d\u7b26\u5408\u6761\u4ef6\n\n # \u5982\u679c\u6709\u5de6\u513f\u5b50\uff0c\u76f4\u63a5\u4e0e\u5de6\u513f\u5b50\u6bd4\u8f83\n if left == len(minHeap) - 1 and minHeap[left][1] < val[1]:\n minHeap[cur] = minHeap[left]\n cur = left\n minHeap[cur] = val # \u628a\u6700\u5f00\u59cb\u7684\u503c\u653e\u5165\u6b63\u786e\u4f4d\u7f6e\n\n # \u6700\u5c0f\u5806\u4e0a\u6d6e\u51fd\u6570 \u4e0a\u6d6e\u8f83\u5c0f\u503c\n # \u8f93\u5165 \u6700\u5c0f\u5806 \u5f53\u524d\u4e0b\u6807\n # \u529f\u80fd\uff1a\u4ece\u5f53\u524d\u4e0b\u6807\u5f00\u59cb\u4e0a\u6d6e\uff0c\u76f4\u5230\u6700\u5c0f\u5806\u5408\u6cd5\n def siftUp(minHeap, cur):\n val = minHeap[cur] # \u5b58\u50a8\u5f53\u524d\u4e0a\u6d6e\u7684\u503c\n par = (cur - 1) // 2 # \u7236\u8282\u70b9\u4e0b\u6807\n while par >= 0 and val[1] < minHeap[par][1]:\n minHeap[cur] = minHeap[par] # \u7b26\u5408\u6761\u4ef6\uff0c\u4e0a\u6d6e\n cur = par\n par = (cur - 1) // 2\n minHeap[cur] = val # \u6700\u5f00\u59cb\u7684\u503c\u653e\u5165\u6b63\u786e\u4f4d\u7f6e\n\n stat = collections.Counter(nums) # \u8fd4\u56de\u5b57\u5178 {\"\u6570\u5b57\":\u51fa\u73b0\u6b21\u6570}\n stat = list(stat.items()) # \u8fd4\u56de\u5d4c\u5957\u5217\u8868 [[\u6570\u5b57,\u51fa\u73b0\u6b21\u6570], [], []]\n minHeap = []\n\n # \u5c06\u524d k \u4e2a\u6570\u5b57\u653e\u5165\uff0c\u6784\u9020\u6700\u5c0f\u5806\n for i in range(k):\n minHeap.append(stat[i])\n siftUp(minHeap, i)\n\n for i in range(k, len(stat)):\n if stat[i][1] > minHeap[0][1]:\n minHeap[0] = stat[i]\n siftDown(minHeap, 0)\n\n result = [row[0] for row in minHeap]\n return result\n"} {"blob_id": "3a996c4610ce75902e6084a81e27935bfb1d24f9", "repo_name": "loremIpsum1771/python_implementations", "path": "/scholarships.py", "length_bytes": 2711, "score": 3.78125, "int_score": 4, "content": "def maxPathProduct(matrix, maxLen):\n \"\"\"\n Take a 2D Array of ints\n and return the largest Product of list of ints of length maxLen\n and the product of the list integers\n \"\"\" \n maxProduct = -1\n maxList = [] \n if len(matrix) == 0 or len(matrix) < maxLen and len(matrix[0]) < maxLen:\n return maxProduct, maxList\n numRows = len(matrix)\n numCols = len(matrix[0])\n numDiagonals = numRows + numCols -1\n directions = [(1, 0,numCols), (0, 1,numRows), (1, 1,numDiagonals)] #list containing protocol for iterating through lines based on direction\n for i in range(len(directions)):\n numLines = directions[i][2] #Set numLines based on the current direction \n for line in range (0,numLines):\n pathProduct = 1\n pathLen = 0\n if i == 0: #iterate through columns\n headRow = 0 #reset the start of the path to the first row\n headCol = line #reset the start of the path to the current column\n elif i ==1:#iterate through rows\n headCol = 0\n headRow = line\n else:#iterate through diagonals\n headRow = 0 if line >= numRows else line #if all diagonal paths have been considered in bottom half of matrix, reset row start to the first row\n headCol = line-numRows if line >= numRows else 0 #if all diagonal paths have been considered in bottom half of matrix, reset column for each unexplored diagonal\n tailRow = headRow\n tailCol = headCol\n pathList = []\n while headRow < numRows and headCol < numCols: #iterate while the current column and row are inside the matrix\n pathList.append(matrix[headRow][headCol]) #add current element to the current path\n pathProduct *= matrix[headRow][headCol] #accumulate the product\n pathLen+=1\n if pathLen > maxLen: \n pathProduct /= matrix[tailRow][tailCol] #if current pathLen is greater than maxLen, shave off first element\n pathList = pathList[1:]\n tailRow += directions[i][0] #move beginning (tail) of path by one\n tailCol += directions[i][1]\n if pathProduct > maxProduct: #if current pathProduct is best seen so far, update max value\n maxProduct = pathProduct\n maxList = pathList\n headRow += directions[i][0] #move end (head) of path by one\n headCol += directions[i][1]\n \n return maxProduct, maxList\n\nmatrix = [[1,2,3,4,5], [1,1,2,3,5], [3,4,5,5,5], [3,4,5,9,5], [1,1,5,5,25]]\n\nprint maxPathProduct(matrix,3)\n"} {"blob_id": "009320be6a6a203ddb96373ab51a065c607fbcf5", "repo_name": "Kaluzhskaia/cellular-automata", "path": "/ca-heat-eq.py", "length_bytes": 2815, "score": 3.984375, "int_score": 4, "content": "# -*- coding: utf-8 -*-\n\n\"\"\"This is a simple implementation of a heat equation solver based on a cellular automaton in Python. It uses matplotlib's matshow to represent the cells' temperature. Cells can be heated by clicking and the animation can be controlled by the keyboard (spacebar to play/pause append the right arrow button to advance by one frame).\"\"\"\n\n# first we import necessary packages: numpy (for arrays), pyplot and animation (for visualization)\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\n# then we declare necessary global variables\nrows = 100 # number of rows\ncols = 100 # number of columns\nhot = 1 # value of a cell that is hot\ncold = 0 # value of a cold cell\ncp = 0\npause = True # pause flag\n\n# now we can create the grid and fill them with cold cells\ncell = np.full((rows, cols), cold)\n# we add a starting configuration (block)\nfor i in range(40, 60):\n for j in range(40, 60):\n cell[i, j] = hot\n\n\n# we need a function that updates the plot each frame\ndef update(*args):\n if not pause:\n advance()\n\n# this is the main function that advances the animation by one frame (time step)\ndef advance(*args):\n global cell\n # we create a new (actual) copy of all cell states\n newcell = cell.copy()\n # and then sum up the values of all neighboring cells and find the average\n for i in range(rows):\n for j in range(cols):\n total = (cp*cell[i, j] + cell[i, (j - 1) % cols] + cell[i, (j + 1) % cols] + cell[(i - 1) % rows, j] + cell[(i + 1) % rows, j] + cell[(i - 1) % rows, (j - 1) % cols] + cell[(i - 1) % rows, (j + 1) % cols] + cell[(i + 1) % rows, (j - 1) % cols] + cell[(i + 1) % rows, (j + 1) % cols])\n avg = total/(9.0+cp)\n newcell[i, j] = avg\n # the new cells are now the old cells and are returned\n grid.set_data(newcell)\n cell = newcell\n return [grid]\n\n# this catches keyboard events (spacebar for play/pause, right arrow key for advancing one frame)\ndef press(event):\n global pause\n if event.key == \" \":\n pause = not pause\n return pause\n elif event.key == \"right\":\n advance()\n\n# catches mouseclick events to draw hot cells\ndef click(event):\n if pause:\n global cell\n if isinstance(event.xdata, float) and isinstance(event.ydata, float):\n j = int(round(event.xdata))\n i = int(round(event.ydata))\n cell[i, j] = hot\n grid.set_data(cell)\n return grid\n\n# plot and animation commands\nfig = plt.figure(figsize=(5, 5))\nax = plt.subplot()\ngrid = ax.matshow(cell, cmap=\"nipy_spectral\")\nfig.canvas.mpl_connect('key_press_event', press)\nfig.canvas.mpl_connect('button_press_event', click)\nani = animation.FuncAnimation(fig, update, interval=50)\nplt.show()\n"} {"blob_id": "c8dec18697420f2f35f7fb414ac4d06b7615fdc6", "repo_name": "oknashar/interview-preparation", "path": "/amazonPY/OA/992.Subarrays-with-K-Different-Integers.py", "length_bytes": 1398, "score": 4.0625, "int_score": 4, "content": "'''\r\nGiven an array A of positive integers, call a (contiguous, not necessarily distinct) subarray of A good if the number of different integers in that subarray is exactly K.\r\n\r\n(For example, [1,2,3,1,2] has 3 different integers: 1, 2, and 3.)\r\n\r\nReturn the number of good subarrays of A.\r\n\r\n\r\n\r\nExample 1:\r\n\r\nInput: A = [1,2,1,2,3], K = 2\r\nOutput: 7\r\nExplanation: Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2].\r\nExample 2:\r\n\r\nInput: A = [1,2,1,3,4], K = 3\r\nOutput: 3\r\nExplanation: Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4].\r\n\r\n\r\nNote:\r\n\r\n1 <= A.length <= 20000\r\n1 <= A[i] <= A.length\r\n1 <= K <= A.length\r\n'''\r\ndef sol(a,k):\r\n count = 0\r\n for i in range(len(a)):\r\n for j in range(i+k,len(a)+1):\r\n newComb = a[i:j]\r\n if len(set(newComb)) == k:\r\n count += 1\r\n return count\r\n\r\n# Sliding Window\r\n\r\ndef sol2(A,K):\r\n def atMostK(A, K):\r\n count = collections.Counter()\r\n res = i = 0\r\n for j in range(len(A)):\r\n if count[A[j]] == 0: K -= 1\r\n count[A[j]] += 1\r\n while K < 0:\r\n count[A[i]] -= 1\r\n if count[A[i]] == 0: K += 1\r\n i += 1\r\n res += j - i + 1\r\n return res\r\n \r\n return self.atMostK(A, K) - self.atMostK(A, K - 1)\r\n"} {"blob_id": "e2bbad621af278662d9aa8986ba99c995656bb12", "repo_name": "ErwanDL/aoc2019", "path": "/Day6/sol.py", "length_bytes": 2114, "score": 3.515625, "int_score": 4, "content": "import os\nfrom typing import List\ndirname = os.path.dirname(__file__)\ninput_txt = open(dirname + \"/input.txt\", \"r\").read()\ninput_list = list(map(lambda x: x.split(\")\"), input_txt.split(\"\\n\")))\n\n\nclass Node():\n # static dictionary that maps each planet name\n # to the corresponding Node object\n planets = {}\n\n def __init__(self, parent: str = None):\n self.parent = parent\n self.children: List[str] = []\n\n def add_child(self, child: str):\n self.children.append(child)\n\n\n# creating the dictionary that gives all direct children for each planet\nfor pair in input_list:\n parent, child = pair\n if parent not in Node.planets:\n Node.planets[parent] = Node()\n Node.planets[parent].add_child(child)\n if child not in Node.planets:\n Node.planets[child] = Node(parent)\n else:\n Node.planets[child].parent = parent\n\nplanets_counts = dict.fromkeys(Node.planets.keys(), 0)\n\n\n# depth first search of the resulting tree starting at COM to populate\n# the dictionary that gives the number of indirect planets for each planet\ndef dfs(planet_name, count_so_far):\n if planet_name not in Node.planets:\n return\n\n for child in Node.planets[planet_name].children:\n planets_counts[child] = count_so_far + 1\n dfs(child, count_so_far + 1)\n return\n\n\n# intializing DFS at \"COM\"\ndfs(\"COM\", 0)\n# summing all indirect orbit counts\nprint(sum(planets_counts.values()))\n\n\ndef get_parents_chain(planet_name: str, parents_list: List[str]):\n parent_name = Node.planets[planet_name].parent\n if not parent_name:\n return\n parents_list.append(parent_name)\n get_parents_chain(parent_name, parents_list)\n return\n\n\nYOU_parent_chain = []\nSAN_parent_chain = []\nget_parents_chain(\"YOU\", YOU_parent_chain)\nget_parents_chain(\"SAN\", SAN_parent_chain)\n\nindex_closest_parent = -1\nfor i in range(1, max(len(YOU_parent_chain), len(SAN_parent_chain)) + 1):\n if YOU_parent_chain[-i] != SAN_parent_chain[-i]:\n break\n index_closest_parent += 1\n\nprint(\n len(YOU_parent_chain) + len(SAN_parent_chain) - 2 *\n (index_closest_parent + 1))\n"} {"blob_id": "ed7915c7cf3bbf8e54e9ae6e0eb5f1231e721e00", "repo_name": "cute-jumper/LeetCode", "path": "/Python/651-700/FindDuplicateSubtrees.py", "length_bytes": 789, "score": 3.703125, "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\nclass Solution(object):\n def findDuplicateSubtrees(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[TreeNode]\n \"\"\"\n from collections import defaultdict\n m = defaultdict(int)\n res = []\n def to_s(root):\n if root == None:\n return 'null'\n s = str(root.val)\n if root.left != None or root.right != None:\n s += ',' + to_s(root.left) + ',' + to_s(root.right)\n if m[s] == 1:\n res.append(root)\n m[s] += 1\n return s\n to_s(root)\n return res\n"} {"blob_id": "de4e7e423b9cd23db064b533add03ed9ef67ae9a", "repo_name": "LDymarczyk/Boggle", "path": "/simulated_annealing.py", "length_bytes": 1820, "score": 3.703125, "int_score": 4, "content": "from classes import *\nimport time, random, copy\nfrom math import exp\n\n\nclass SimulatedAnnealing:\n\n def __init__(self):\n self.temperature = 600\n self.n = 0.91\n self.random_generator = Default\n self.board = None\n self.new_board = None\n self.results = []\n\n def set_random_generator(self, generator=Default):\n self.random_generator = generator\n print \"Set new random generator\"\n\n def get_started(self):\n self.board = Boggle(self.random_generator)\n print \"Created boggle board {}\".format(str(self.board.board))\n\n def count_points(self, board):\n return boggle_solver(\"slowa.txt\", board.board)\n\n def change_board(self):\n number_of_slots = random.randint(1, 5)\n self.new_board = copy.copy(self.board)\n self.new_board.update_board(number_of_slots)\n\n def execute(self):\n self.get_started()\n i = 1\n points = self.count_points(self.board)\n self.results.append(str(points))\n print \"result \", self.results\n while self.temperature > 6: #6\n self.change_board()\n new_points = self.count_points(self.new_board)\n self.results.append(str(new_points))\n if new_points > points or exp((points - new_points)/self.temperature) > random.random():\n self.board = self.new_board\n points = new_points\n i += 1\n self.temperature *= self.n\n print \"result \", self.results, \" temperature: \", self.temperature\n print(\"done!\")\n return self.results, self.board.board\n\n\nif __name__ == \"__main__\":\n sa = SimulatedAnnealing()\n start_time = time.time()\n sa.execute()\n elapsed_time = time.time() - start_time\n print time.strftime(\"%H:%M:%S\", time.gmtime(elapsed_time))\n"} {"blob_id": "5273c82aa2b1258ddd5b19d361e907ce2b09b466", "repo_name": "fulv1o/sorting_algorithms", "path": "/mergesort.py", "length_bytes": 2604, "score": 3.921875, "int_score": 4, "content": "\"\"\"\"\r\nAlgoritmo de ordena\u00e7\u00e3o Merge Sort\r\n\"\"\"\r\n\r\nimport random\r\nimport time\r\n\r\n# vari\u00e1vel global para contar o n\u00famero de compara\u00e7\u00f5es\r\ncomp = 0\r\n\r\n# ----------------------------------------------------------------------------------------------------------------------\r\n# As entradas s\u00e3o o vetor a ser ordenado, a posi\u00e7\u00e3o inicial e a posi\u00e7\u00e3o final.\r\ndef mergesort(vetor, pI, pF):\r\n if pI < pF: # condi\u00e7\u00e3o de exist\u00eancia\r\n q = (pI + pF) // 2 # meio do vetor\r\n mergesort(vetor, pI, q ) # cria um subvetor que \u00e9 a metade a esquerda do vetor anterior\r\n mergesort(vetor, q+1, pF) # cria um subvetor que \u00e9 a metade a direita do vetor anterior\r\n intercalar(vetor, pI, q, pF)\r\n# ----------------------------------------------------------------------------------------------------------------------\r\n\r\n# ----------------------------------------------------------------------------------------------------------------------\r\n# Compara os elementos entre dois subvetores\r\ndef intercalar(vetor, pI, q, pF):\r\n global comp\r\n vetorCopia = vetor.copy() # C\u00f3pia do vetor real\r\n contE = pI # Contador do subvetor a esquerda\r\n contD = q+1 # Contador do subvetor a direita\r\n contR = pI # Contador do vetor real\r\n\r\n while contR <= pF:\r\n comp+=1\r\n # Entra quando n\u00e3o existe mais elementos no subvetor a esquerda\r\n if contE > q:\r\n vetor[contR] = vetorCopia[contD]\r\n contD += 1\r\n # Entra quando n\u00e3o existe mais elementos no subvetor a direita\r\n elif contD > pF:\r\n vetor[contR] = vetorCopia[contE]\r\n # Troca elemento do subvetor a esquerda\r\n elif vetorCopia[contE] <= vetorCopia[contD]:\r\n vetor[contR] = vetorCopia[contE]\r\n contE += 1\r\n # Troca elemento do subvetor a direita\r\n else:\r\n vetor[contR] = vetorCopia[contD]\r\n contD += 1\r\n contR += 1\r\n# ----------------------------------------------------------------------------------------------------------------------\r\n\r\n\r\n# main------------------------------------------------------------------------------------------------------------------\r\n# Implementa\u00e7\u00e3o da lista a ser utilizada para a ordena\u00e7\u00e3o\r\nvetor = list(range(0, 10000))\r\nrandom.shuffle(vetor)\r\n\r\nprint(\"O vetor inicial \u00e9:\", end=\" \")\r\nprint(vetor)\r\n\r\ntI = time.time()\r\nmergesort(vetor, 0, len(vetor)-1)\r\ntF = time.time()\r\n\r\ntempo = (tF-tI)*1000\r\n\r\nprint(\"O vetor ordenado \u00e9:\", end=\" \")\r\nprint(vetor)\r\nprint(f'O n\u00famero de compara\u00e7\u00f5es \u00e9: {comp}')\r\nprint(f'O tempo total foi: {round(tempo, 2)} ms')"} {"blob_id": "ee9d866a4ad94aa9f29bac6911314a78d19ac7cc", "repo_name": "vishsanghishetty/LC-Python", "path": "/hard/Trapping Rain Water/solution.py", "length_bytes": 712, "score": 3.5, "int_score": 4, "content": "# Time complexity: O(n)\n# Approach: Pre-computing arrays containing information about max height poles around it. With that, finding the water contained over specific position becomes easier.\n\nclass Solution:\n def trap(self, height: List[int]) -> int:\n n = len(height)\n if n == 1:\n return 0\n left, right = [0]*n, [0]*n\n left[0] = height[0]\n for i in range(1, n):\n left[i] = max(height[i], left[i-1])\n right[n-1] = height[n-1]\n for i in range(n-2, -1, -1):\n right[i] = max(height[i], right[i+1])\n ans = 0\n for i in range(n):\n ans += (min(left[i], right[i])-height[i])\n return ans\n "} {"blob_id": "d3aa8b83057d6feac5565058c68a7179198ef8e4", "repo_name": "dh256/adventofcode", "path": "/2020/Day24/HexGrid.py", "length_bytes": 6072, "score": 3.78125, "int_score": 4, "content": "from enum import Enum\n\nclass Directions(Enum):\n NE=\"ne\"\n E=\"e\"\n SE=\"se\"\n SW=\"sw\"\n W=\"w\"\n NW=\"nw\"\nclass Colour(Enum):\n WHITE=0\n BLACK=1\nclass Hexagon():\n\n @staticmethod\n def all_adjacent(x,y,z):\n '''\n Returns a list of all the coords of all hexagons adjacent to given coords\n '''\n hexagons = []\n\n # ne: inc x, dec z\n hexagons.append((x+1,y,z-1))\n # e: inc x, dec y\n hexagons.append((x+1,y-1,z))\n # se: dec y, inc z\n hexagons.append((x,y-1,z+1))\n # sw: dec x, inc z\n hexagons.append((x-1,y,z+1))\n # w: dec x, inc y\n hexagons.append((x-1,y+1,z))\n # nw: inc y, dec z\n hexagons.append((x,y+1,z-1))\n\n return hexagons\n\n @staticmethod\n def adjacent(x,y,z,direction):\n if direction == \"e\":\n # move east inc x, dec y\n x += 1\n y -= 1\n elif direction == \"w\":\n # move west: dec x, inc y, \n x -= 1\n y += 1 \n elif direction == \"nw\":\n # move north west: inc y, dec z, \n y += 1\n z -= 1\n elif direction == \"ne\":\n # move north east: inc x, dec z\n x += 1\n z -= 1\n elif direction == \"sw\":\n # move south west: dec x, inc z\n x -= 1\n z += 1\n elif direction == \"se\":\n #\u00a0move south east: dec y, inc z\n y -= 1\n z += 1\n return (x,y,z)\n\n \n\nclass Instructions:\n def __init__(self,instructions_str):\n #\u00a0break instructions string into a set of individual instructions\n self.instructions = []\n curr_index = 0\n while curr_index < len(instructions_str):\n if instructions_str[curr_index] == 'e' or instructions_str[curr_index] == 'w':\n self.instructions.append(instructions_str[curr_index:curr_index+1])\n curr_index += 1\n else:\n self.instructions.append(instructions_str[curr_index:curr_index+2])\n curr_index += 2\n\nclass HexGrid:\n # need a coordinate system for HexGrid\n # See: https://www.redblobgames.com/grids/hexagons/ \n #\u00a0grid will be a dictionary where key is coord and value is current colour 0 - white; 1 - black\n \n def __init__(self,file_name):\n self.grid = {}\n with open(file_name,\"r\") as input_file:\n self.instructions = [Instructions(line.strip('\\n')) for line in input_file]\n\n def process_instructions(self):\n # if coord not found then create new entry and set color to 0\n # if coord found set colour to !colour (i.e. 0 becomes 1 and 1 becomes 0)\n # after all instructions, count all entries where colour == 1 and return value\n for instructions in self.instructions:\n # reset curr_coord to origin hexagon\n x = 0\n y = 0\n z = 0\n for instruction in instructions.instructions:\n (x,y,z) = Hexagon.adjacent(x,y,z,instruction)\n \n #\u00a0set colour\n if (x,y,z) in self.grid.keys():\n # invert colour\n self.flip((x,y,z)) \n else:\n #\u00a0first time, grid space visited, set to black\n self.grid[(x,y,z)] = Colour.BLACK\n \n def get_colour(self,key):\n # check if tile exists in grid - if not create a new white one\n if not key in self.grid.keys():\n self.grid[key] = Colour.WHITE\n\n #\u00a0return colour\n return self.grid[key]\n\n @property\n def black_tiles(self):\n # return number of black tiles\n return len(list(filter(lambda v: v == Colour.BLACK, self.grid.values())))\n\n def flip(self,key):\n if self.grid[key] == Colour.BLACK:\n self.grid[key] = Colour.WHITE\n else:\n self.grid[key] = Colour.BLACK\n \n def flip_tiles(self,days):\n # now do daily transformation\n # get all the black tiles and count number of black adjacent tiles, if number is 0 or > 2, then add tile to flip list\n #\u00a0for each white tile adjacent to one of the black tiles, count number of adjacent black tiles; if number is 2 then add to flip list (if not already added)\n # When complete, flip all tiles in flip list and repeat for given number of days \n for day in range(1,days+1):\n tiles_to_flip = []\n \n #\u00a0get every black tile\n black_tiles = [item[0] for item in list(filter(lambda i: i[1] == Colour.BLACK, self.grid.items()))]\n for black_tile in black_tiles:\n # get all tiles adjacent to black_tile\n adjacent_tiles_b = Hexagon.all_adjacent(black_tile[0],black_tile[1],black_tile[2])\n num_black_tiles1 = 0\n for tile in adjacent_tiles_b:\n if self.get_colour(tile) == Colour.BLACK:\n #\u00a0if black, count \n num_black_tiles1 += 1\n else:\n # if white, get all adjacent tiles to white tile and count number that are black\n adjacent_tiles_w = Hexagon.all_adjacent(tile[0],tile[1],tile[2])\n num_black_tiles2 = 0\n for tile_w in adjacent_tiles_w:\n if self.get_colour(tile_w) == Colour.BLACK:\n num_black_tiles2 += 1\n \n # should white tile be flipped\n if num_black_tiles2 == 2 and tile not in tiles_to_flip:\n tiles_to_flip.append(tile) \n \n\n # should black tile be flipped\n if (num_black_tiles1 == 0 or num_black_tiles1 > 2) and black_tile not in tiles_to_flip:\n tiles_to_flip.append(black_tile) \n\n #\u00a0flip tiles\n for tile in tiles_to_flip:\n self.flip(tile)\n\n \n\n\n \n"} {"blob_id": "398253504327c08288967facfe3c44659d6f8290", "repo_name": "ilovequant/Practise", "path": "/SerializeDeserializeBinaryTree.py", "length_bytes": 2026, "score": 3.8125, "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\nclass Codec:\n\n def serialize(self, root):\n \"\"\"Encodes a tree to a single string.\n\n :type root: TreeNode\n :rtype: str\n \"\"\"\n queue = []\n ans = \"\"\n if not root:\n return \"\"\n\n queue.append(root)\n ans += str(root.val) + ','\n\n while queue:\n temp = \"\"\n n = len(queue)\n for i in range(n):\n cur = queue.pop()\n if cur.left:\n queue.insert(0, cur.left)\n temp += str(cur.left.val) + ','\n if not cur.left:\n temp += '#,'\n if cur.right:\n queue.insert(0, cur.right)\n temp += str(cur.right.val) + ','\n if not cur.right:\n temp += '#,'\n\n if len(temp) > 0:\n ans += temp\n\n ans = ans[:-1]\n return ans\n\n def deserialize(self, data):\n \"\"\"Decodes your encoded data to tree.\n\n :type data: str\n :rtype: TreeNode\n \"\"\"\n\n if not data or len(data) == 0:\n return None\n\n readin = data.split(',')\n root = TreeNode(int(readin[0]))\n n = len(readin)\n if n == 1:\n return root\n isleft = True\n index = 0\n queue = [root]\n\n for i in range(1, n):\n if readin[i] is not '#':\n node = TreeNode(int(readin[i]))\n if isleft:\n queue[index].left = node\n else:\n queue[index].right = node\n queue.append(node)\n\n if not isleft:\n index += 1\n\n isleft = not isleft\n\n return root\n\n# Your Codec object will be instantiated and called as such:\n# codec = Codec()\n# codec.deserialize(codec.serialize(root))"} {"blob_id": "78d649e71b55dbc9770f4c813ab1eef7596902aa", "repo_name": "wojsamjan/clabs", "path": "/950-Y2004/asiekiel/labirynt/gtklab/mazegen.py", "length_bytes": 4346, "score": 3.53125, "int_score": 4, "content": "#!/usr/bin/python\n# -*- coding: iso-8859-2 -*-\n\n# Skrypt generujcy doskonae labirynty.\n# Przy odpalaniu z linii komend wypisze na stdout\n# losowy labirynt prostoktny\n\nimport random\nimport math\n\nWALL = '#'\nHARD_WALL = '@'\nNORMAL = ' '\nSTART = 'S'\n\ndef any(f, seq):\n \"True if f(e) is true for some e from sequence seq\"\n for e in seq:\n\tif f(e):\n\t return True\n return False\n\ndef insideMaze(maze, pt):\n \"Is 'pt' inside maze?\"\n return pt[0] >= 0 and pt[1] >= 0 and pt[1] < len(maze) and pt[0] < len(maze[pt[1]])\n\ndef borderPoints(maze):\n return [ (0, i) for i in range(0, len(maze)) ] +\\\n [ (len(maze[i])-1, i) for i in range(0, len(maze)) ] +\\\n [ (i, 0) for i in range(0, len(maze[0])) ] +\\\n [ (i, len(maze)-1) for i in range(0, len(maze[-1])) ]\n\ndef neighbourPoints(maze, pt):\n (x, y) = pt\n xs = range(x-1, x+2)\n ys = range(y-1, y+2)\n allPoints = [ (a, b) for a in xs for b in ys ]\n allPoints.remove((x,y))\n return filter(lambda a: insideMaze(maze, a), allPoints)\n\ndef directNeighbours(maze, (x,y)):\n return filter(lambda a: insideMaze(maze, a), ((x-1,y),(x+1,y),(y-1,x),(y+1,x)))\n\ndef makeExit(maze):\n def borderWithoutCorners():\n return [ (0, i) for i in range(2, len(maze) - 2) ] +\\\n [ (len(maze[i])-1, i) for i in range(2, len(maze) - 2) ] +\\\n [ (i, 0) for i in range(2, len(maze[0]) - 2) ] +\\\n [ (i, len(maze)-1) for i in range(2, len(maze[-1]) - 2) ]\n\n def makeSuccFunction((x,y)):\n if x == 0:\n return lambda (x, y): (x+1, y)\n elif y == 0:\n return lambda (x, y): (x, y+1)\n elif x == len(maze[y]) - 1:\n return lambda (x, y): (x-1, y)\n else:\n return lambda (x, y): (x, y-1)\n bc = borderWithoutCorners()\n pt = bc[random.randrange(0, len(bc))]\n succ = makeSuccFunction(pt)\n while 1:\n maze[pt[1]][pt[0]] = NORMAL\n (xp, yp) = succ(pt)\n if maze[yp][xp] == NORMAL:\n break\n pt = (xp, yp)\n\ndef makeStart(maze):\n all = [ (x, y) for y in range(0, len(maze)) for x in range(0, len(maze[y]))]\n normals = filter(lambda (x,y): maze[y][x] == NORMAL, all)\n (a, b) = normals[random.randrange(0, len(normals))]\n maze[b][a] = START\n\ndef surroundMaze(maze):\n \"Surround maze by hard wall\"\n for (x, y) in borderPoints(maze):\n maze[y][x] = HARD_WALL\n\ndef Random2PointPaths(pt):\n \"Gives random list of all 2-point paths from one of 4 directions\"\n (x, y) = pt\n nearPaths = [ [(x-1, y),(x-2,y)], [(x+1, y),(x+2,y)],\n\t\t [(x,y-1),(x,y-2)], [(x,y+1),(x,y+2)] ]\n random.shuffle(nearPaths)\n return nearPaths\n\ndef surroundedByWall(maze, pt):\n \"Is pt surrounded by wall?\"\n return any(lambda (a,b): maze[b][a] == WALL, neighbourPoints(maze, pt))\n\ndef mazeBuilder(maze, pt):\n \"Main building algorithm\"\n for [(x1, y1), (x2,y2)] in Random2PointPaths(pt):\n\tif insideMaze(maze, (x2, y2)) and maze[y1][x1] == WALL and \\\n\t maze[y2][x2] == WALL and surroundedByWall(maze, (x2,y2)):\n\t maze[y1][x1] = maze[y2][x2] = NORMAL\n\t mazeBuilder(maze, (x2, y2))\n\t\ndef makeSquareMaze(x, y):\n maze = []\n for i in range(0, y):\n\tmaze.append([ WALL for i in range(0, x) ])\n surroundMaze(maze)\n return maze\n\ndef makeCircleMaze(r):\n maze = makeSquareMaze(2*r, 2*r)\n all = [ (x, y) for x in range(0, 2*r) for y in range(0, 2*r) ]\n bad = filter(lambda (x,y): (x-r)**2 + (y-r)**2 > r*r + 6, all)\n lim = filter(lambda (x,y): (x-r)*(x-r) + (y-r)*(y-r) < r*r + 6, all)\n good =filter(lambda (x,y): (x-r)*(x-r) + (y-r)*(y-r) < r*r, all)\n for (x, y) in lim:\n\tmaze[y][x] = HARD_WALL\n for (x, y) in bad:\n\tmaze[y][x] = NORMAL\n for (x, y) in good:\n\tmaze[y][x] = WALL\n return maze\n \n\ndef normalizeWalls(maze):\n \"Change hard to normal walls\"\n for e in maze:\n\tfor i in range(0, len(e)):\n\t if e[i] == HARD_WALL:\n\t\te[i] = WALL\n\ndef printMaze(maze):\n for e in maze:\n\tprint ''.join(e)\n\ndef main():\n import sys\n sys.setrecursionlimit(1000000)\n\n size1 = random.randrange(12, 50)\n size2 = random.randrange(12, 50)\n m = makeSquareMaze(size1, size2)\n\n mazeBuilder(m, (10,10))\n normalizeWalls(m)\n makeStart(m)\n makeExit(m)\n\n printMaze(m)\n\nif __name__ == '__main__':\n main()\n"} {"blob_id": "218e5db8d8b0e6173cbe1ad27acd43ab03d0f4e0", "repo_name": "RohanMiraje/DSAwithPython", "path": "/DSA/stack/next_prev_smaller_greater.py", "length_bytes": 3350, "score": 3.875, "int_score": 4, "content": "\"\"\"\ninput array\n 5 8 1 2 10 5 8\noutputs\nnext greater\n 8 10 2 10 -1 8 -1\nprevious greater\n -1 -1 8 8 -1 10 10\nnext smaller\n 1 1 -1 -1 5 -1 -1\nprev smaller\n -1 5 -1 1 2 2 5\n\"\"\"\n\n\ndef next_greater(array):\n \"\"\"\n Using stack\n if curr ele is greater than top of stack\n pop until top has greater value than curr\n for every pop ele -->next greater is curr element\n at last after array traversal\n if stack has values\n those don't have any next greater element\n :param array:\n :return:\n \"\"\"\n stack = list()\n print('next greater elements:')\n for curr_ele in array:\n while len(stack) != 0 and stack[-1] < curr_ele:\n print(\"{} ->{}\".format(stack.pop(), curr_ele))\n stack.append(curr_ele)\n while stack:\n print(\"{} ->{}\".format(stack.pop(), -1))\n\n\ndef previous_greater(array):\n \"\"\"\n Using stack\n top maintained is always greater till prev of curr element traversing\n pop when curr ele is greater than top\n if stack empty then\n print -1 as previous greater of curr ele\n else\n print top as previous greater of curr ele\n push curr ele to stack\n :param array:\n :return:\n \"\"\"\n stack = list()\n print('previous greater elements:')\n stack.append(array[0])\n print(-1, end=' ')\n i = 1\n n = len(array)\n while i < n:\n while len(stack) != 0 and array[i] > stack[-1]:\n stack.pop()\n if not stack:\n print(-1, end=' ')\n else:\n print(stack[-1], end=' ')\n stack.append(array[i])\n i += 1\n\n\ndef previous_smaller(array):\n \"\"\"\n Using stack\n Idea is to keep top as smaller till prev of curr ele\n If curr ele is smaller than top ....pop until top is smaller or it becomes empty\n :param array:\n :return:\n \"\"\"\n stack = list()\n print('previous smaller elements:')\n stack.append(array[0])\n print(-1, end=\" \")\n i = 1\n n = len(array)\n while i < n:\n while stack and stack[-1] > array[i]:\n stack.pop()\n if not stack:\n print(-1, end=\" \")\n else:\n print(stack[-1], end=\" \")\n stack.append(array[i])\n i += 1\n\n\ndef next_smaller(array):\n \"\"\"\n Using stack:\n 1.create empty stack\n 2.start traversing array\n -loop:check if stack is not empty and top is greater than curr ele:\n print curr ele as next smaller of pop element\n push curr ele to stack\n 3. check if stack is not empty\n loop:pop all ele and print there next smaller as -1\n Idea is to pop all elements from stack if curr ele is less than top until top becomes\n small or stack becomes empty\n for every pop ele -->next smaller is curr element\n after whole traversal of input array\n if anything is left in stack then they don't have any next smaller\n :param array:\n :return:\n \"\"\"\n print('next smaller elements:')\n stack = list()\n for val in array:\n while stack and stack[-1] > val:\n print(\"{}-->{}\".format(stack.pop(), val))\n stack.append(val)\n while stack:\n print(\"{}-->{}\".format(stack.pop(), -1))\n\n\nif __name__ == '__main__':\n a = [5, 8, 1, 2, 10, 5, 8]\n # next_greater(a)\n # previous_greater(a)\n # previous_smaller(a)\n next_smaller(a)\n"} {"blob_id": "d08c54431fee63492adbf53cb9dc71728bb7ded3", "repo_name": "CodersInSeattle/InterviewProblems", "path": "/problems/bit/single_number.py", "length_bytes": 1079, "score": 3.6875, "int_score": 4, "content": "\"\"\"\nNUMS = [1, 2, 3, 2, 3, 1, 4, 4, 9]\n1 ^ 2 ^ 3 ^ 2 ^ 3 = 1 ^ (2 ^ 2) ^ (3 ^ 3) = 1 ^ 0 ^ 0 = 1\n\n0 ^ x = x\nx ^ x = 0\n\n\n[1, 2, 3, 2, 4, 3]\nXOR everything: 1 ^ 4 = 101 (identifier)\ngroup1: [5, 2, 3, 2, 3,0] => 1\ngroup2: [4] => 4\n\n\"\"\"\n\nimport operator\nimport functools\n\n\ndef single_number_map(nums):\n counts = {}\n for n in nums:\n if n not in counts:\n counts[n] = 0\n else:\n counts[n] += 1\n for num, count in counts.iteritems():\n if count == 1:\n return num\n\n\ndef single_number_set(nums):\n appeared = set()\n for n in nums:\n try:\n appeared.pop(n)\n except KeyError:\n appeared.add(n)\n return appeared.pop()\n\ndef single_number_sort(nums):\n nums_sorted = sorted(nums)\n for i in xrange(1, len(nums)):\n if nums[i] == nums[i-1]:\n continue\n elif i < len(nums) - 1 and nums[i] == nums[i+1] :\n return nums[i-1]\n else:\n nums[i]\n\n\ndef single_number_bit(nums):\n return functools.reduce(operator.xor, nums)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"} {"blob_id": "0fc04b15e79246ecd05ac943ad21fd6077c9ec7f", "repo_name": "Qinpeng96/leetcode", "path": "/5471. \u548c\u4e3a\u76ee\u6807\u503c\u7684\u6700\u5927\u6570\u76ee\u4e0d\u91cd\u53e0\u975e\u7a7a\u5b50\u6570\u7ec4\u6570\u76ee.py", "length_bytes": 3283, "score": 3.84375, "int_score": 4, "content": "\"\"\"\n[5471. \u548c\u4e3a\u76ee\u6807\u503c\u7684\u6700\u5927\u6570\u76ee\u4e0d\u91cd\u53e0\u975e\u7a7a\u5b50\u6570\u7ec4\u6570\u76ee](https://leetcode-cn.com/problems/maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/)\n\u7ed9\u4f60\u4e00\u4e2a\u6570\u7ec4 nums \u548c\u4e00\u4e2a\u6574\u6570 target \u3002\n\n\u8bf7\u4f60\u8fd4\u56de \u975e\u7a7a\u4e0d\u91cd\u53e0 \u5b50\u6570\u7ec4\u7684\u6700\u5927\u6570\u76ee\uff0c\u4e14\u6bcf\u4e2a\u5b50\u6570\u7ec4\u4e2d\u6570\u5b57\u548c\u90fd\u4e3a target \u3002\n\n \n\u793a\u4f8b 1\uff1a\n\n\u8f93\u5165\uff1anums = [1,1,1,1,1], target = 2\n\u8f93\u51fa\uff1a2\n\u89e3\u91ca\uff1a\u603b\u5171\u6709 2 \u4e2a\u4e0d\u91cd\u53e0\u5b50\u6570\u7ec4\uff08\u52a0\u7c97\u6570\u5b57\u8868\u793a\uff09 [1,1,1,1,1] \uff0c\u5b83\u4eec\u7684\u548c\u4e3a\u76ee\u6807\u503c 2 \u3002\n\u793a\u4f8b 2\uff1a\n\n\u8f93\u5165\uff1anums = [-1,3,5,1,4,2,-9], target = 6\n\u8f93\u51fa\uff1a2\n\u89e3\u91ca\uff1a\u603b\u5171\u6709 3 \u4e2a\u5b50\u6570\u7ec4\u548c\u4e3a 6 \u3002\n([5,1], [4,2], [3,5,1,4,2,-9]) \u4f46\u53ea\u6709\u524d 2 \u4e2a\u662f\u4e0d\u91cd\u53e0\u7684\u3002\n\u793a\u4f8b 3\uff1a\n\n\u8f93\u5165\uff1anums = [-2,6,6,3,5,4,1,2,8], target = 10\n\u8f93\u51fa\uff1a3\n\u793a\u4f8b 4\uff1a\n\n\u8f93\u5165\uff1anums = [0,0,0], target = 0\n\u8f93\u51fa\uff1a3\n \n\n\u63d0\u793a\uff1a\n\n1 <= nums.length <= 10^5\n-10^4 <= nums[i] <= 10^4\n0 <= target <= 10^6\n***\n\n\u5f00\u59cb\u7684\u601d\u8def\uff1a\u5229\u7528\u524d\u7f00\u548c\uff0c\u5229\u7528\u53cc\u6307\u9488\uff0c\u53f3\u6307\u9488\u53f3\u79fb\uff0c\u5de6\u6307\u9488\u4ece\u5934\u904d\u5386\u3002\u627e\u5230\u76ee\u6807\u503c\u3002\u5de6\u6307\u9488\u79fb\u52a8\u5230\u53f3\u6307\u9488\u4f4d\u7f6e\uff0c\u53f3\u6307\u9488\u53f3\u79fb\u4e00\u4f4d\u3002\u7ed3\u679c\u8d85\u65f6\u4e86\uff0c\u60ed\u6127\u554a\u3002\n\"\"\"\n```python\nclass Solution:\n def maxNonOverlapping(self, nums: List[int], target: int) -> int:\n if not nums: return 0\n n = len(nums)\n out = 0\n num = [0]*(n+1)\n for i in range(1,n+1):#\u8ba1\u7b97\u524d\u7f00\n num[i] += num[i-1] + nums[i-1]\n \n i, j = 0, 1\n Flag = 0\n pre = 0\n while j <= n:#\u904d\u5386\u67e5\u627e\uff0c\u6bcf\u67e5\u5230\u4e00\u6b21\uff0c\u5c31\u6574\u4f53\u540e\u79fb\n if Flag:\n i = pre\n else:\n i = 0\n \n while i < j:\n if num[j]-num[i] == target:\n out += 1\n pre = j\n Flag = 1\n break\n else:\n i += 1\n j += 1\n return out\n```\n\"\"\"\n\u5927\u4f6c\u4eec\u4e5f\u662f\u4f7f\u7528\u7684\u524d\u7f00\u548c\uff0c\u53ea\u4e0d\u8fc7\u8fd9\u91cc\u5e76\u6ca1\u6709\u8981\u6c42\u6211\u4eec\u8fd4\u56de\u5177\u4f53\u7684\u4e0b\u6807\uff0c\u53ea\u53eb\u6211\u4eec\u8fd4\u56de\u7b26\u5408\u6761\u4ef6\u7684\u4e2a\u6570\u3002\u6240\u4ee5\u6211\u4eec\u7528\u4e0d\u7740\u6bcf\u6b21\u90fd\u904d\u5386\u4e00\u6b21\u3002\n\u76f4\u63a5\u628a\u524d\u7f00\u548c\u52a0\u5165\u5230\u4e00\u4e2a\u96c6\u5408\u5185\uff0c\u540e\u9762\u7684 **(\u524d\u7f00\u548c - \u76ee\u6807\u503c)** \u5982\u679c\u5728\u96c6\u5408\u5185,\u90a3\u4e48\u8f93\u51fa\u52a0\u4e00\u3002\n\n\u6ce8\u610f\uff1a\u8fd9\u4e2a\u65f6\u5019\u6211\u4eec\u9700\u8981\u505a\u4e09\u4ef6\u4e8b\uff1a\n- \u6e05\u695a\u96c6\u5408\u5185\u90e8\u7684\u5143\u6570\uff0c\u56e0\u4e3a\u6211\u4eec\u8fd9\u91cc\u4e0d\u80fd\u5305\u542b\u4e4b\u524d\u7684\u5143\u6570\u3002\u5e76\u4e14\u628a0\u52a0\u5165\u5230\u96c6\u5408\n- \u6e05\u695a\u524d\u7f00\u548c\u7684\u503c\uff0c\u6211\u4eec\u4ece\u65b0\u5f00\u59cb\u8ba1\u7b97\n- \u96c6\u5408\u52a00\u662f\u4e3a\u4e86\u5f53\u67d0\u4e00\u4e2a\u521a\u597d\u5c31\u7b49\u4e8e\u76ee\u6807\u503c\uff0c\u4e00\u76f8\u51cf\uff0c\u503c\u7b49\u4e8e0\uff0c\u4f46\u662f0\u5143\u7d20\u4e0d\u662f\u4e4b\u524d\u7684\u524d\u7f00\u548c\uff0c\u6211\u4eec\u6240\u4ee5\u9700\u8981\u52a0\u5165\u4e00\u4e2a0\u5728\u96c6\u5408\uff0c\u8868\u793a[0\uff1ai]\u4e00\u6bb5\u90fd\u662f\u6ee1\u8db3\u6761\u4ef6\u7684\uff0c\u4e0d\u9700\u8981\u4e24\u4e2a\u524d\u7f00\u548c\u4e4b\u95f4\u76f8\u51cf\u3002\n\"\"\"\n```python\nclass Solution:\n def maxNonOverlapping(self, nums: List[int], target: int) -> int:\n if not nums: return 0\n out = 0\n res = set()\n res.add(0)\n presum = 0\n for num in nums:\n presum += num\n if (presum - target) in res:#\u67e5\u627e\u5dee\u503c\u662f\u5426\u5728\u524d\u7f00\u548c\u7684\u96c6\u5408\u5185\n out += 1\n res.clear() #\u5f97\u5230\u4e4b\u540e\u5c31\u8981\u6e05\u695a\u524d\u7f00\u548c\u7684\u96c6\u5408\n res.add(0)\n presum = 0 #\u5f97\u5230\u4e4b\u540e\u5c31\u8981\u6e05\u695a\u524d\u7f00\u548c\n else:\n res.add(presum)\n return out\n\n```\n"} {"blob_id": "e1dfe1da69c7b31021a888c5ac47707603f0ef43", "repo_name": "wilbertgeng/LintCode_exercise", "path": "/Data_Structure_related/4.py", "length_bytes": 862, "score": 3.75, "int_score": 4, "content": "\"\"\"4. Ugly Number II\n\"\"\"\nclass Solution:\n \"\"\"\n @param n: An integer\n @return: return a integer as description.\n \"\"\"\n def nthUglyNumber(self, n):\n # write your code here\n import heapq\n heap = [1]\n visited = set()\n for i in range(n):\n val = heapq.heappop(heap)\n for factor in [2, 3, 5]:\n if val * factor not in visited:\n visited.add(val * factor)\n heapq.heappush(heap, factor * val)\n\n return val\n\n\n\n\n\n ###\n heap = [1]\n visited = set([1])\n\n for i in range(n):\n val = heapq.heappop(heap)\n for factor in [2, 3, 5]:\n if val * factor not in visited:\n visited.add(val * factor)\n heapq.heappush(heap, val * factor)\n\n return val\n"} {"blob_id": "a02274d5609240f91352d2ba5085b4d099720e1d", "repo_name": "mwiatrowski/advent_of_code_2020", "path": "/21/21b.py", "length_bytes": 1226, "score": 3.59375, "int_score": 4, "content": "import re\nimport sys\n\n\nall_ingredients = {}\npossible_ingredients = {}\n\n\nfor line in sys.stdin:\n ingredients, allergens = line.split('(')\n ingredients = ingredients.split()\n allergens = re.findall(r\"(\\w+)\", allergens)[1:]\n\n for ingredient in ingredients:\n all_ingredients[ingredient] = all_ingredients.get(ingredient, 0) + 1\n\n for allergen in allergens:\n if allergen not in possible_ingredients:\n possible_ingredients[allergen] = set(ingredients)\n else:\n possible_ingredients[allergen] = possible_ingredients[allergen] & set(ingredients)\n\n\nall_allergens = list(possible_ingredients.keys())\nsolution = { allergen: None for allergen in all_allergens }\ndef find_solution(allergens):\n global solution\n if len(allergens) == 0:\n return True\n\n allergen = allergens[0]\n for ingredient in possible_ingredients[allergen]:\n if ingredient in solution.values():\n continue\n solution[allergen] = ingredient\n if find_solution(allergens[1:]):\n return True\n solution[allergen] = None\n\n return False\n\nfind_solution(all_allergens)\n\nprint(','.join([ingredient for (allergen, ingredient) in sorted(solution.items())]))\n"} {"blob_id": "5d3ff300a8a30b19a96078a0d7fa423af56e8574", "repo_name": "hemangandhi/derpspace", "path": "/pythons/emoji-chess.py", "length_bytes": 7096, "score": 3.578125, "int_score": 4, "content": "#! /usr/bin/env python3\n\nclass Emotes:\n def __init__(self, blank, pawn, rook, knight, bishop, king, queen):\n self.blank = blank\n self.pawn = pawn\n self.rook = rook\n self.knight = knight\n self.bishop = bishop\n self.king = king\n self.queen = queen\n\ndef validated_input(prompt, get_error=lambda x: None, converter=lambda x: x):\n p = input(prompt)\n v = validator(p)\n while v is not None:\n print(v)\n p = input(prompt)\n v = validator(p)\n return converter(p)\n\nclass InputModule:\n def get_move(self, color, board):\n print(\"Enter the piece and then the x and y coordinate of a possible move\")\n pieces = [p for r in board for p in r if p and p.black == color]\n moves = {piece: [(idx, x, y) for x, y in piece.get_moves(board)]\\\n for idx, piece in enumerate(pieces)}\n for piece, move in moves:\n print(\"Move {}: \" +\\\n \" or \".join(\"{},{},{}\".format(*move) for move in sorted(moves)))\n options = set(moves.values())\n tpl = lambda p: tuple(map(int, p.split(\",\")))\n user_move = validated_input(prompt,\n lambda p: {\n True: None,\n False: \"Enter one of the options above\"\n }[all(q.is_digit() for q in p) and tpl(p) in options],\n tpl)\n return pieces[user_move[0]], user_move[1:]\n def print_board(self, board):\n print(\" \" * 4 + (\" \" * 3).join(map(str, range(8))))\n for idx, row in enumerate(board):\n print(36 * \"-\") # TODO: tune hyperparameter\n print(idx, \"|\", \" | \".join(map(str, row)), \"|\")\n def prompt_for_promotion(self):\n print(\"It seems you can promote a pawn!\")\n return validated_input(\n \"Choose between (Q)ueen, (R)ook, (B)ishop, or (K)night\",\n lambda p: p.strip().lower() in \"qrbk\",\n lambda p: p.strip().lower())\n\n# TODO: interface for castling and promotions\ndef game_factory(emotes, input_module):\n\n class Space:\n def __init__(self, x, y):\n self.coord = (x, y)\n def __eq__(self, other):\n return self.coord == other.coord\n def __str__(self):\n return emotes.blank[self.coords[0] % 2 != self.coords[1] % 2]\n def __bool__(self):\n return False\n def __hash__(self):\n return hash(self.coord)\n\n class Piece(Space):\n def __init__(self, x, y, is_white):\n self.black = not is_white\n self.moved = False\n Space.__init__(self, x, y)\n def __eq__(self, other):\n return self.coord == other.coord and self.black == other.black and self.moved == other.moved\n def __bool__(self):\n return True\n def moves(self, board):\n raise NotImplemented(\"swubcwass me pwease UwU\")\n def move(self, board, new_coords):\n if new_coords not in set(self.moves(board)):\n raise ValueError(\"Cannot make this move!\")\n board[self.coords[0]][self.coords[1]] = Space(self.coords[0], self.coords[1])\n board[new_coords[0]][new_coords[1]] = self\n self.coords = new_coords\n self.moved = True\n\n def follow_vector(source, vector, board, color):\n for scalar in range(1, 8):\n move = (s + scalar * d for (s, d) in zip(source, vector))\n if (not all(0 <= c < 8 for c in move)) or\\\n (board[move[0]][move[1]] and board[move[0]][move[1]].black == color):\n break\n yield move\n if board[move[0]][move[1]]:\n break\n\n class Rook(Piece):\n def __str__(self):\n return emotes.rook[self.black]\n def moves(self, board):\n yield from follow_vector(self.coord, (0, 1), board)\n yield from follow_vector(self.coord, (0, -1), board)\n yield from follow_vector(self.coord, (1, 0), board)\n yield from follow_vector(self.coord, (-1, 0), board)\n\n class Bishop(Piece):\n def __str__(self):\n return emotes.bishop[self.black]\n def moves(self, board):\n yield from follow_vector(self.coord, (1, 1), board)\n yield from follow_vector(self.coord, (1, -1), board)\n yield from follow_vector(self.coord, (-1, 1), board)\n yield from follow_vector(self.coord, (-1, -1), board)\n\n class Queen(Piece):\n def __str__(self):\n return emotes.queen[self.black]\n def moves(self, board):\n yield from Rook.moves(board)\n yield from Bishop.moves(board)\n\n class King(Piece):\n def __str__(self):\n return emotes.king[self.black]\n def moves(self, board):\n for i in [-1, 0, 1]:\n for j in [-1, 0, 1]:\n if i == j and j == 0:\n continue\n if 0 <= self.coords[0] + i < 8 and 0 <= self.coords[1] + j < 8:\n yield (self.coords[0] + i, self.coords[1] + j)\n if not self.moved and\\\n self.board[self.coords[0]][7] and\\\n not self.board[self.coords[0]][7].moved and\\\n self.board[self.coord[0]][5] and\\\n self.board[self.coord[0]][6]:\n yield (self.coord[0], 6)\n def move(self, board, new_coord):\n old = self.coord\n Piece.move(self, board, new_coord)\n if new_coord == (old[0], 6) and old[1] - new_coord[1] == 2:\n board[old[0]][5], board[old[0]][7] = board[old[0]][7], Space(old[0], 7)\n board[old[0]][5].coords = (old[0], 5)\n board[old[0]][5].moved = True\n\n class Pawn(Piece):\n def __str__(self):\n return emotes.pawn[self.black]\n def moves(self, board):\n direction = 1 if self.black else -1\n if 0 <= self.coords[0] + direction < 8:\n for i in [-1, 0, 1]:\n if i == 0 or board[self.coords[0] + direction][self.coords[1] + i]:\n yield (self.coords[0] + direction, self.coords[1] + i)\n def move(self, board, new_coord):\n Piece.move(self, board, new_coord)\n if new_coord[0] in (0, 7):\n board[new_coord[0]][new_coord[1]] = {\n 'q': Queen(*new_coord, not self.black),\n 'r': Rook(*new_coord, not self.black),\n 'b': Bishop(*new_coord, not self.black),\n 'k': Knight(*new_coord, not self.black),\n }[input_module.prompt_for_promotion()]\n\n class Knight(Piece):\n def __str__(self):\n return emotes.knight[self.black]\n def moves(self, board):\n directions = [(2, 1), (1, 2), (-1, 2), (-1, -2), (1, -2), (-2, 1), (-2, -1), (2, -1)]\n moves = map(lambda direction: tuple(c + d for (c, d) in zip(self.coords, direction)), directions)\n yield from filter(lambda m: all(0 <= i < 8 for i in m), moves)\n"} {"blob_id": "7f3d745f24ee1fceb8e9887d833f5b8ed991c39c", "repo_name": "akotter2/Adam-Kotter-Code", "path": "/School_Projects/chess_knight.py", "length_bytes": 4687, "score": 3.9375, "int_score": 4, "content": "#chess_knight.py\n\n\"\"\"A program designed to help determine the average number of moves it takes for a \nknight starting in a corner and moving randomly to return to its starting corner. \nUses Markov chains as the primary theoretical basis.\"\"\"\n\nimport numpy as np\nfrom scipy import linalg as la\n\n\"\"\"The expected number of moves to get to the knight's original starting space from a \ngiven space is 1 plus the expected number of moves from the valid next spaces divided \nby the number of valid next spaces. Mathematically, we can write this as \n E(i,j) = 1 + (sum(E(valid)))/N(valid).\nThe strategy is to write the expectation values as a system of equations, then solve \nfor the expectation values of the various spaces using linear algebra.\"\"\"\n\ndef matrix_maker():\n \"\"\"Make a matrix representation of the system of equations, setting each equation \n equal to -1. We use the convention that the knight's original corner is (1,1), \n with other spaces ranging up to (8,8). The board is diagonally symmetric from the \n knight's first space, so we only include rows for the upper half of the board (36 \n spaces total). Row 0 corresponds to (1,1), and we fill subsequent rows by \n traversing the board row-wise.\"\"\"\n #Initialize the matrix\n M = -np.eye(36)\n #(1,1)\n M[0,9] = 1\n #(1,2)\n M[1,[2,15,10]] = 1/3\n #(1,3)\n M[2,[1,9,11,16]] = 1/4\n #(1,4) to (1,6)\n indices = np.array([8, 12, 15, 17])\n for i, index in enumerate([3,4,5]):\n M[index,indices+i] = 1/4\n #(1,7)\n M[6,[11,18,20]] = 1/3\n #(1,8)\n M[7,[12,19]] = 1/2\n #(2,2)\n M[8,[3,16]] = 1/2\n #(2,3)\n M[9,[2,4,10,17,21]] = 1/6\n #(2,4)\n M[10,[1,5,9,16,18,22]] = 1/6\n #(2,5) and (2,6)\n indices = np.array([2, 6, 15, 19, 21, 23])\n for i, index in enumerate([11, 12]):\n M[index,indices+i] = 1/6\n #(2,7)\n M[13,[4,17,23,25]] = 1/4\n #(2,8)\n M[14,[5,24]] = 1/2\n #(3,3)\n M[15,[11,22]] = 1/2\n #(3,4)\n M[16,[2,4,8,10,12,17,23,26]] = 1/8\n #(3,5)\n M[17,[3,5,9,13,16,22,24,27]] = 1/8\n #(3,6)\n M[18,[4,6,10,14,21,25,26,28]] = 1/8\n #(3,7)\n M[19,[5,7,11,22,27,29]] = 1/6\n #(3,8)\n M[20,[6,12,23,28]] = 1/4\n #(4,4)\n M[21,[9,11,18,27]] = 1/4\n #(4,5)\n M[22,[10,12,15,17,19,23,28,30]] = 1/8\n #(4,6)\n M[23,[11,13,16,20,22,27,29,31]] = 1/8\n #(4,7)\n M[24,[12,14,17,26,30,32]] = 1/6\n #(4,8)\n M[25,[13,18,27,31]] = 1/4\n #(5,5)\n M[26,[16,18,24,31]] = 1/4\n #(5,6)\n M[27,[17,19,21,23,25,28,32,33]] = 1/8\n #(5,7)\n M[28,[18,20,22,27,31,34]] = 1/6\n #(5,8)\n M[29,[19,23,30,33]] = 1/4\n #(6,6)\n M[30,[22,24,29,34]] = 1/4\n #(6,7)\n M[31,[23,25,26,28,32,35]] = 1/6\n #(6,8)\n M[32,[24,27,31,34]] = 1/4\n #(7,7)\n M[33,[27,29]] = 1/2\n #(7,8)\n M[34,[28,30,32]] = 1/3\n #(8,8)\n M[35,31] = 1\n #Return the matrix\n return M\n\ndef experiment(iters=1000):\n \"\"\"Experimentally determines the expected number of moves for the knight to \n return to its starting corner. The knight can go into any valid state each move, \n and the number of moves is saved after it returns to its corner.\"\"\"\n #Initialize trackers\n current_move = 0\n all_moves = []\n #Repeat a statistically significant number of times\n for k in range(iters):\n #Track which iteration we're in\n #print(k)\n #Initialize knight position\n knight = [1,1]\n #Make the first move\n i = np.random.choice([1,2])\n j = 3 - i\n knight = [1+i,1+j]\n #print(knight)\n current_move = 1\n #Repeat until the knight returns to [1,1]\n while knight != [1,1]:\n #Choose a valid move\n moved = False\n while not moved:\n i = np.random.choice([-2,-1,1,2])\n j = np.random.choice([3-np.abs(i),-3+np.abs(i)])\n #print(\"Position: \" + str(knight))\n #print(\"i: \" + str(i))\n #print(\"j: \" + str(j))\n #print(\"Current move: \" + str(current_move))\n if knight[0]+i > 0 and knight[0]+i < 9 and knight[1]+j > 0 and knight[1]+j < 9:\n moved = True\n knight[0] += i\n knight[1] += j\n current_move += 1\n #Save the results\n all_moves.append(current_move)\n #Return the average number of moves\n return np.average(all_moves)\n \n \n \n \n\nif __name__ == \"__main__\":\n #Find the inverse of the matrix, then solve for the expected number of moves\n inverse = la.inv(matrix_maker())\n constant = -np.ones(36)\n expectations = inverse@constant\n print(expectations)\n\n"} {"blob_id": "b0c8393ac62bfa47b1862bd37a12968e6827f96b", "repo_name": "jslee6091/SW_Algorithm", "path": "/sw expert academy/Intermediate/Stack2/3_Calculator3/Calculator3.py", "length_bytes": 2281, "score": 3.609375, "int_score": 4, "content": "import sys\nsys.stdin = open(\"Calculator3_inputs.txt\", 'r')\n\n# \uad04\ud638\uc640 \ub367\uc148, \uacf1\uc148 \uc5f0\uc0b0\uc774 \ud3ec\ud568\ub41c \uacc4\uc0b0\uc2dd\uc758 \ud6c4\uc704\ud45c\uae30\ubc95 \uc5f0\uc0b0\nfor test_case in range(1, 11):\n length = int(input())\n expression = input()\n\n # \ud6c4\uc704\ud45c\uae30\ubc95 \uc218\uc2dd\n postfix = []\n\n # \uc5f0\uc0b0\uc790 \uc800\uc7a5\n operator = []\n\n # \ud6c4\uc704\ud45c\uae30\ubc95 \uc5f0\uc0b0\n calculator = []\n\n # \ud6c4\uc704\ud45c\uae30\ubc95 \ubcc0\ud658\n for ch in expression:\n # '(' \uc77c\ub54c\ub294 \ubb34\uc870\uac74 operator \uc5d0 \uc0bd\uc785\n if ch == '(':\n operator.append(ch)\n\n # '+' \uc77c\ub54c\ub294 '('\uc778 \uacbd\uc6b0\ub97c \uc81c\uc678\ud558\uace0 \ubb34\uc870\uac74 postfix \uc5d0 \uc62e\uae30\uace0 operator \uc5d0 \uc0bd\uc785\n elif ch == '+':\n while True:\n check1 = operator.pop()\n if check1 != '(':\n postfix.append(check1)\n else:\n operator.append(check1)\n break\n operator.append(ch)\n\n # '*' \uc77c\ub54c\ub294 \uac19\uc740 \uc5f0\uc0b0\uc790\uc778 \uacbd\uc6b0\ub97c \uc81c\uc678\ud558\uace0 operator \uc5d0 \ubb34\uc870\uac74 \uc0bd\uc785\n elif ch == '*':\n while True:\n check2 = operator.pop()\n if check2 == '*':\n postfix.append(check2)\n else:\n operator.append(check2)\n break\n operator.append(ch)\n\n # ')' \uc77c\ub54c\ub294 '('\uac00 \ub098\uc62c\ub54c\uae4c\uc9c0 \ubb34\uc870\uac74 \ube7c\uc11c postfix \uc5d0 \uc0bd\uc785 \ud6c4 \uad04\ud638\uc5f0\uc0b0\uc790\ub294 \uc81c\uac70\n elif ch == ')':\n while True:\n check3 = operator.pop()\n if check3 == '(':\n break\n else:\n postfix.append(check3)\n\n # \uc815\uc218\uc778 \uacbd\uc6b0\ub294 postfix \uc5d0 \uc815\uc218\ud615 \ubcc0\ud658 \ud6c4 \uc0bd\uc785\n else:\n postfix.append(int(ch))\n\n # \ub0a8\uc740 \uc5f0\uc0b0\uc790\ub4e4 postfix \uc5d0 \uc0bd\uc785\n while len(operator) != 0:\n postfix.append(operator.pop())\n\n # \ud6c4\uc704\ud45c\uae30\uc2dd \uc5f0\uc0b0 - \uad04\ud638\ub294 \ubaa8\ub450 \uc81c\uac70\ub418\uc5c8\uc73c\ubbc0\ub85c \uc5c6\ub294 \uacbd\uc6b0\uc640 \ub611\uac19\uc774 \uacc4\uc0b0\n for var in postfix:\n if var == '*':\n calculator.append(calculator.pop() * calculator.pop())\n elif var == '+':\n calculator.append(calculator.pop() + calculator.pop())\n else:\n calculator.append(var)\n\n print(f'#{test_case} {calculator.pop()}')\n"} {"blob_id": "a562d08ed2d760aad2479cf7f38b28a3c63d9e05", "repo_name": "s-surineni/atice", "path": "/leet_code/word_search_2.py", "length_bytes": 1484, "score": 3.734375, "int_score": 4, "content": "class TrieNode:\n def __init__(self):\n self._next = [None] * 26\n self._word = None\n\n\ndef build_trie(word_list):\n root = TrieNode()\n for a_word in word_list:\n node = root\n for ch in a_word:\n ch_idx = ord(ch) - ord(\"a\")\n if not node._next[ch_idx]:\n node._next[ch_idx] = TrieNode()\n node = node._next[ch_idx]\n node._word = a_word # [Note] special treatment\n return root\n\n\ndef dfs(row, col, cross_word, root, res):\n ch_idx = ord(cross_word[row][col]) - ord(\"a\")\n if cross_word[row][col] == \"#\" or not root._next[ch_idx]:\n return\n root = root._next[ch_idx]\n\n if root._word:\n res.append(root._word)\n root._word = None\n\n cross_word[row][col] = \"#\"\n for ri, ci in ((row + 1, col), (row - 1, col), (row, col + 1), (row, col - 1)):\n if 0 <= ri < len(cross_word) and 0 <= ci < len(cross_word[0]):\n dfs(ri, ci, cross_word, root, res)\n cross_word[row][col] = chr(ch_idx + ord(\"a\"))\n\n\ndef search_words(cross_word, word_list):\n root = build_trie(word_list)\n res = []\n for row in range(len(cross_word)):\n for col in range(len(cross_word[0])):\n dfs(row, col, cross_word, root, res)\n return res\n\n\nboard = [\n [\"o\", \"a\", \"a\", \"n\"],\n [\"e\", \"t\", \"a\", \"e\"],\n [\"i\", \"h\", \"k\", \"r\"],\n [\"i\", \"f\", \"l\", \"v\"],\n]\nwords = [\"oath\", \"pea\", \"eat\", \"rain\"]\n\nboard = [[\"a\"]]\nwords = [\"a\"]\nprint(search_words(board, words))\n"} {"blob_id": "cdd26d6dff50c7dc07d77ed7dab0d2688285f125", "repo_name": "drewsb/PolymerWalk", "path": "/polymerWalkGraph.py", "length_bytes": 10435, "score": 4.03125, "int_score": 4, "content": "#Drew Boyette\r\n#Computational Physics\r\n#5/27/15\r\n#polymerWalkGraph.py\r\n\r\nfrom random import randrange\r\nfrom pylab import *\r\n\r\n###NOTE: THIS MUST BE RUN IN CANOPY\r\n\r\n#This program will generate graphs for a random walk simulation in either 2D or 3D\r\n#or both. The user has the option to either generate a histogram of a single \r\n#grid size for a certain sample size, or a scatter plot of of many grid sizes for a certain sample\r\n#size. \r\n\r\ndimension = raw_input(\"2D or 3D or both?: \") #User can choose either 2D, 3D, or both.\r\nwhile dimension != \"2D\" and dimension !=\"3D\" and dimension != \"both\" :\r\n print 'Invalid Input. Try Again.'\r\n if dimension == '' :\r\n break\r\n dimension = raw_input(\"2D or 3D or both?: \")\r\n\r\nplotting = int(input(\"Plot a specific grid size,or a range of grid sizes? (0 or 1): \")) #User can choose to either graph one grid size, or multiple\r\nwhile plotting!= 0 and 1 :\r\n print 'Invalid Input. Try Again.'\r\n plotting = int(input(\"Plot a specific grid size,or a range of grid sizes? (0 or 1): \"))\r\n\r\nn = int(input(\"Sample Size?: \"))\r\nwhile n<=1:\r\n print 'Invalid Input. Try Again.'\r\n n = int(input(\"Sample Size?: \"))\r\nif plotting == 0:\r\n size = int(input(\"Grid size?: \"))\r\n while size<=1:\r\n print 'Invalid Input. Try Again.'\r\n size = int(input(\"Grid size?: \"))\r\n\r\n#This function is essentially the polymer walk program in 2D without the visual aspect. \r\ndef polymerWalk2D(sizeGrid) : \r\n pointsArray = []\r\n usedList = []\r\n stuck = False\r\n for i in range(sizeGrid) :\r\n for j in range(sizeGrid):\r\n pointsArray.append([i-sizeGrid/2,j-sizeGrid/2])\r\n \r\n usedList.append([0,0])\r\n\r\n def adjacentPoints(coord) :\r\n result=[]\r\n if sizeGrid%2==0 :\r\n b=sizeGrid/2\r\n if coord[0]!=b-1 and [coord[0]+1,coord[1]] not in usedList :\r\n result.append([coord[0]+1,coord[1]])\r\n if coord[0]!=-b and [coord[0]-1,coord[1]] not in usedList:\r\n result.append([coord[0]-1,coord[1]])\r\n if coord[1]!=b-1 and [coord[0],coord[1]+1] not in usedList:\r\n result.append([coord[0],coord[1]+1])\r\n if coord[1]!=-b and [coord[0],coord[1]-1] not in usedList:\r\n result.append([coord[0],coord[1]-1])\r\n else :\r\n b=(sizeGrid-1)/2\r\n if coord[0]!=b and [coord[0]+1,coord[1]] not in usedList :\r\n result.append([coord[0]+1,coord[1]])\r\n if coord[0]!=-b and [coord[0]-1,coord[1]] not in usedList:\r\n result.append([coord[0]-1,coord[1]])\r\n if coord[1]!=b and [coord[0],coord[1]+1] not in usedList:\r\n result.append([coord[0],coord[1]+1])\r\n if coord[1]!=-b and [coord[0],coord[1]-1] not in usedList:\r\n result.append([coord[0],coord[1]-1])\r\n return result\r\n\r\n\r\n i=0\r\n while stuck==False :\r\n adjacent=adjacentPoints(usedList[i])\r\n num=len(adjacent)\r\n if num == 0:\r\n stuck=True\r\n else :\r\n path=int(randrange(0,num))\r\n usedList.append(adjacent[path])\r\n i+=1\r\n return i\r\n\r\n#This function is essentially the polymer walk program in 3D without the visual aspect. \r\ndef polymerWalk3D(sizeGrid) :\r\n pointsArray = []\r\n usedList = []\r\n stuck = False\r\n for i in range(sizeGrid) :\r\n for j in range(sizeGrid) :\r\n for h in range(sizeGrid) :\r\n pointsArray.append([i-sizeGrid/2,j-sizeGrid/2, h-sizeGrid/2])\r\n \r\n usedList.append([0,0,0])\r\n\r\n def adjacentPoints(coord) :\r\n result=[]\r\n if sizeGrid%2==0:\r\n b=sizeGrid/2\r\n if coord[0]!=b-1 and [coord[0]+1,coord[1], coord[2]] not in usedList :\r\n result.append([coord[0]+1,coord[1], coord[2]])\r\n if coord[0]!=-b and [coord[0]-1,coord[1], coord[2]] not in usedList:\r\n result.append([coord[0]-1,coord[1], coord[2]])\r\n if coord[1]!=b-1 and [coord[0],coord[1]+1, coord[2]] not in usedList:\r\n result.append([coord[0],coord[1]+1, coord[2]])\r\n if coord[1]!=-b and [coord[0],coord[1]-1, coord[2]] not in usedList:\r\n result.append([coord[0],coord[1]-1, coord[2]])\r\n if coord[2]!=b-1 and [coord[0],coord[1], coord[2]+1] not in usedList:\r\n result.append([coord[0],coord[1], coord[2]+1])\r\n if coord[2]!=-b and [coord[0],coord[1], coord[2]-1] not in usedList:\r\n result.append([coord[0],coord[1], coord[2]-1])\r\n else :\r\n b=(sizeGrid-1)/2\r\n if coord[0]!=b and [coord[0]+1,coord[1], coord[2]] not in usedList :\r\n result.append([coord[0]+1,coord[1], coord[2]])\r\n if coord[0]!=-b and [coord[0]-1,coord[1], coord[2]] not in usedList:\r\n result.append([coord[0]-1,coord[1], coord[2]])\r\n if coord[1]!=b and [coord[0],coord[1]+1, coord[2]] not in usedList:\r\n result.append([coord[0],coord[1]+1, coord[2]])\r\n if coord[1]!=-b and [coord[0],coord[1]-1, coord[2]] not in usedList:\r\n result.append([coord[0],coord[1]-1, coord[2]])\r\n if coord[2]!=b and [coord[0],coord[1], coord[2]+1] not in usedList:\r\n result.append([coord[0],coord[1], coord[2]+1])\r\n if coord[2]!=-b and [coord[0],coord[1], coord[2]-1] not in usedList:\r\n result.append([coord[0],coord[1], coord[2]-1])\r\n return result\r\n\r\n i=0\r\n while stuck==False :\r\n adjacent=adjacentPoints(usedList[i])\r\n num=len(adjacent)\r\n if num == 0:\r\n stuck=True\r\n else :\r\n path=int(randrange(0,num))\r\n usedList.append(adjacent[path])\r\n i+=1\r\n return i\r\n\r\nif plotting == 0:\r\n resultList2D = [] #This list will hold values taken from many iterations of random walks in 2D\r\n resultList3D = []\r\n for i in range(n) :\r\n if dimension != '3D' : #If the dimension variable is either '2D' or 'both', a random walk in 2D will run and its N steps will be appended to the list\r\n resultList2D.append(polymerWalk2D(size))\r\n if dimension !='2D' : #If the dimension variable is either '3D' or 'both', a random walk in 3D will run and its N steps will be appended to the list\r\n resultList3D.append(polymerWalk3D(size)) \r\n if dimension == '2D' :\r\n hist(resultList2D) #Creates a histogram of the distribution of polymer chain lengths in 2D\r\n title(\"Distribution of Polymer Chain Length in 2D (Grid Size: %d, Sample Size: %d)\" % (size,n), loc='center') \r\n xlabel(\"Monomers\"); plt.ylabel(\"Frequency\") \r\n show()\r\n if dimension == '3D' :\r\n hist(resultList3D) #Creates a histogram of the distribution of polymer chain lengths in 3D\r\n title(\"Distribution of Polymer Chain Length in 3D (Grid Size: %d, Sample Size: %d)\" % (size,n), loc='center') \r\n xlabel(\"Monomers\"); plt.ylabel(\"Frequency\") \r\n show()\r\n if dimension == 'both' :\r\n subplot(2,1,1)\r\n hist(resultList2D) \r\n title(\"Distribution of Polymer Chain Length in 2D (Grid Size: %d, Sample Size: %d)\" % (size,n), loc='center') \r\n xlabel(\"Monomers\"); plt.ylabel(\"Frequency\") \r\n tight_layout()\r\n subplot(2,1,2)\r\n hist(resultList3D) \r\n title(\"Distribution of Polymer Chain Length in 3D\", loc='center') \r\n xlabel(\"Monomers\"); plt.ylabel(\"Frequency\") \r\n tight_layout()\r\n show()\r\n \r\nif plotting == 1: \r\n gridList = [ 6, 8, 10, 12, 16, 20, 25, 30, 35, 40, 50, 60, 80, 100] #This is the list of grid sizes that will run\r\n stepList2D = []\r\n stepList3D = []\r\n resultList2D = []\r\n resultList3D = []\r\n datax=[]\r\n datay=[]\r\n datax2D=[]\r\n datay2D=[]\r\n datax3D=[]\r\n datay3D=[]\r\n \r\n for each in gridList :\r\n for i in range(n):\r\n if dimension != '3D' :\r\n stepList2D.append(polymerWalk2D(each)) #Runs the simulation for a certain amount of times and records the number of steps taken for each\r\n if dimension != '2D' :\r\n stepList3D.append(polymerWalk3D(each)) \r\n if dimension != '3D' : #If the dimension is either '2D' or both '2D' and '3D'\r\n avg2D=float(sum(stepList2D))/len(stepList2D) #Average number of steps for a certain grid size\r\n resultList2D.append([each,avg2D]) #The average value is stored in a list\r\n if dimension != '2D' :\r\n avg3D=float(sum(stepList3D))/len(stepList3D)\r\n resultList3D.append([each,avg3D])\r\n print(each)\r\n if dimension == '2D' :\r\n for each in resultList2D: #Sorts the grid sizes and lattice sites visited into their respective lists\r\n datax.append(each[0])\r\n datay.append(each[1])\r\n scatter(datax, datay) #Graphs a scatter plot of the grid size and the average number of steps taken for that grid size\r\n title(\"Scatter Plot of N Steps for Various Grid Sizes in 2D (Sample Size: %d)\" % (n), loc='center') \r\n xlabel(\"Grid Size\"); plt.ylabel(\"Lattice Sites Visited\") \r\n show()\r\n if dimension == '3D' :\r\n for each in resultList3D:\r\n datax.append(each[0])\r\n datay.append(each[1])\r\n scatter(datax,datay) \r\n title(\"Scatter Plot of N Steps for Various Grid Sizes in 3D (Sample Size: %d)\" % (n), loc='center') \r\n xlabel(\"Grid Size\"); plt.ylabel(\"Lattice Sites Visited\")\r\n show()\r\n if dimension == 'both' :\r\n for each in resultList2D:\r\n datax2D.append(each[0])\r\n datay2D.append(each[1])\r\n for each in resultList3D:\r\n datax3D.append(each[0])\r\n datay3D.append(each[1])\r\n subplot(2,1,1) #Creates a subplot for this scatter plot\r\n scatter(datax2D, datay2D) \r\n title(\"Scatter Plot of N Steps for Various Grid Sizes in 2D (Sample Size: %d)\" % (n), loc='center') \r\n xlabel(\"Grid Size\"); plt.ylabel(\"Lattice Sites Visited\") \r\n tight_layout()\r\n subplot(2,1,2)\r\n scatter(datax3D, datay3D) \r\n title(\"Scatter Plot of N Steps for Various Grid Sizes in 3D (Sample Size: %d)\" % (n), loc='center') \r\n xlabel(\"Grid Size\"); plt.ylabel(\"Lattice Sites Visited\") \r\n tight_layout()\r\n show()\r\n print(resultList2D)\r\n print(resultList3D)\r\n\r\n \r\n \r\n"} {"blob_id": "a4270005d0928d599e42254f12eb02a0a6b2ebe8", "repo_name": "codepals-org/poker", "path": "/backend/src/dealer/helpers/result.py", "length_bytes": 6372, "score": 3.53125, "int_score": 4, "content": "\"\"\" This module comes with functions to decide which poker player out \nof all players has the best cards. \n\"\"\"\nimport itertools\n# full_list in [('A','A'),('B','B')...,('F','F')]\n\ndef results(full_list, public_card):\n \"\"\" The results function takes a list of player cards and \n the community cards (in the middle of the table) and calculates\n who of the players has the wining hand. \"\"\"\n\n #public_card = ['6H', '6D', '5S', '4S', '8S']\n #full_list = [['9C', 'AS'], ['9H', '5C'], ['4D', '2S'], ['KC', '2D'], ['9D', '10C']]\n\n high_comb_rank = []\n high_type_rank = []\n high_point_rank = []\n public_card_temp = []\n winner_card_type = []\n public_card_temp.extend(list(public_card))\n total_players = len(full_list)\n\n for player_card_check in full_list:\n player_card_check += public_card\n card_combinations = list(itertools.combinations(player_card_check, 5))\n\n color_all = []\n size_all = []\n\n for card_combination in card_combinations:\n color_current = []\n for card in card_combination:\n color_current.append(str(card[-1]))\n color_all.append(color_current)\n\n size_current = []\n for card in card_combination:\n if card[-2].isdigit():\n size5 = int(card[-2])\n if size5 == 0:\n size5 = 10\n else:\n if card[-2] == \"J\":\n size5 = 11\n elif card[-2] == \"Q\":\n size5 = 12\n elif card[-2] == \"K\":\n size5 = 13\n elif card[-2] == \"A\":\n size5 = 14\n size_current.append(size5)\n size_all.append(size_current)\n card_type_all = []\n type_score_all = []\n high_card_all = []\n win_point = []\n for i, card_combination in enumerate(card_combinations):\n color = color_all[i]\n size = size_all[i]\n high_card = []\n card_type = []\n size_set = list(set(size))\n while len(set(color)) == 1:\n if max(size) - min(size) == 4:\n card_type = 'Straight flush'\n high_card = max(size)\n break\n else:\n card_type = 'Flush'\n high_card = sum(size)\n break\n else:\n if len(set(size)) == 5:\n if max(size) - min(size) == 4:\n if sorted(size)[2] == sum(size) / len(size):\n card_type = 'Straight'\n high_card = max(size)\n elif max(size) - min(size) == 12:\n if sum(size) == 28:\n card_type = 'Straight'\n high_card = 5\n else:\n card_type = 'High card'\n high_card = sum(size)\n else:\n card_type = 'High card'\n high_card = sum(size)\n\n elif len(size) - 1 == len(set(size)):\n card_type = 'One pair'\n high_card = max([x for n, x in enumerate(size) if x in size[:n]])\n\n elif len(size) - 2 == len(set(size)):\n size_temp = []\n size_temp.extend(size)\n for a in range(0, 5):\n for b in range(0, 3):\n if size[a] == size_set[b]:\n size[a] = 0\n size_set[b] = 0\n last = [x for x in size if x != 0]\n size = []\n size.extend(size_temp)\n if last[0] == last[1]:\n card_type = 'Three of a kind'\n high_card = max([x for n, x in enumerate(size) if x in size[:n]])\n\n else:\n card_type = 'Two pairs'\n high_card = sum([x for n, x in enumerate(size) if x in size[:n]])\n\n elif len(size) - 3 == len(set(size)):\n for a in range(0, 5):\n for b in range(0, 2):\n if size[a] == size[b]:\n size[a] = 0\n size_set[b] = 0\n last = [x for x in size if x != 0]\n\n if last[0] == last[1] == last[2]:\n card_type = 'Four of a kind'\n high_card = max([x for n, x in enumerate(size) if x in size[:n]])\n\n else:\n card_type = 'Full house'\n high_card = max([x for n, x in enumerate(size) if x in size[:n]])\n type_score = []\n if card_type == 'Straight flush':\n type_score = 9\n elif card_type == 'Four of a kind':\n type_score = 8\n elif card_type == 'Full house':\n type_score = 7\n elif card_type == 'Flush':\n type_score = 6\n elif card_type == 'Straight':\n type_score = 5\n elif card_type == 'Three of a kind':\n type_score = 4\n elif card_type == 'Two pairs':\n type_score = 3\n elif card_type == 'One pair':\n type_score = 2\n elif card_type == 'High card':\n type_score = 1\n card_type_all.append(card_type)\n high_card_all.append(high_card)\n win_point.append(type_score * int(100) + high_card)\n\n high_point = max(win_point)\n locate = win_point.index(max(win_point))\n high_comb = card_combinations[locate]\n high_type = card_type_all[locate]\n high_point_rank.append(high_point)\n high_comb_rank.append(high_comb)\n high_type_rank.append(high_type)\n winner = ()\n for i in range(len(high_point_rank)):\n if high_point_rank[i] == max(high_point_rank):\n winner += (i,)\n for i in winner:\n a = int(i)\n b = high_type_rank[a]\n winner_card_type.append(b)\n\n return (winner, winner_card_type)\n"} {"blob_id": "7c0a5611994ff80b6e1f804f802b16eed0941e4c", "repo_name": "bhavyaagg/python-test", "path": "/algs4/searching/bst.py", "length_bytes": 8552, "score": 4.0625, "int_score": 4, "content": "# Created for BADS 2018\n# see README.md for details\n# Python 3\n\n\n\"\"\"\nThe BST class represents an ordered symbol table of generic\nkey-value pairs.\n\nThis implementation uses an unbalanced, binary search tree.\n\nFor additional details and documentation, see Section 3.2 of Algorithms,\n4th Edition by Robert Sedgewick and Kevin Wayne.\n\n:original author: Robert Sedgewick and Kevin Wayne\n:original java code: https://algs4.cs.princeton.edu/32bst/BST.java.html\n\n\"\"\"\n\n# Missing methods:\n# ceiling, select, rank, size (or rather, range_size)\n\nclass BST:\n def __init__(self):\n \"\"\"\n Initialises empty symbol table\n \"\"\"\n self._root = None # root of BST\n\n class Node:\n def __init__(self, key, value, size):\n self.left = None # root of left subtree\n self.right = None # root of right subtree\n self.key = key # sorted by key\n self.value = value # associated data\n self.size = size # number of nodes in subtree\n\n def is_empty(self):\n \"\"\"\n Returns true if this symbol table is empty\n \"\"\"\n return self.size() == 0\n\n def contains(self, key):\n \"\"\"\n Does this symbol table contain the given key?\n :param key: the key to search for\n :return boolean: true if symbol table contains key, false otherwise\n \"\"\"\n return self.get(key) != None\n\n def size(self):\n \"\"\"\n Returns the number of key-value pairs in this symbol table\n \"\"\"\n return self._size(self._root)\n \n def __len__(self):\n return self.size()\n\n def _size(self, node):\n \"\"\"\n Returns the number of key-value pairs in BST rooted at node\n\n :param node: The node which act as root\n \"\"\"\n if node == None:\n return 0\n return node.size\n\n def get(self, key):\n \"\"\"\n Returns the value associated with the given key\n\n :param key: The key whose value is returned\n :return: the value associated with the given key if the key\n is in the symbol table, None otherwise\n \"\"\"\n return self._get(self._root, key)\n\n def _get(self, node, key):\n if node == None:\n return None\n if key < (node.key):\n return self._get(node.left, key)\n elif key > (node.key):\n return self._get(node.right, key)\n else:\n return node.value\n\n def put(self, key, value):\n \"\"\"\n Inserts the specified key-value pair into the symbol table,\n overwriting the old value with the new value if the symbol table\n already contains the specified key. Deletes the specified key (and\n its associated value) from this symbol table if the specified value\n is None.\n\n :param key, value: the key-value pair to be inserted\n \"\"\"\n if value == None:\n self.delete(key)\n return\n self._root = self._put(self._root, key, value)\n\n def _put(self, node, key, value):\n if node == None:\n return self.Node(key, value, 1)\n if key < (node.key):\n node.left = self._put(node.left, key, value)\n elif key > (node.key):\n node.right = self._put(node.right, key, value)\n else:\n node.value = value\n node.size = 1 + self._size(node.left) + self._size(node.right)\n return node\n\n def delete_min(self):\n \"\"\"\n Removes the smalles key and associated value from the symbol table\n \"\"\"\n self._root = self._delete_min(self._root)\n\n def _delete_min(self, node):\n if node.left == None:\n return node.right\n node.left = self._delete_min(node.left)\n node.size = self._size(node.left) + self._size(node.right) + 1\n return node\n\n def delete_max(self):\n \"\"\"\n Removes the largest key and associated value from the symbol table\n \"\"\"\n self._root = delete_max(self._root)\n\n def _delete_max(self, node):\n if node.right == None:\n return node.left\n node.right = self._delete_max(node.right)\n node.size = self._size(node.left) + self._size(node.right) + 1\n return node\n\n\n def delete(self, key):\n \"\"\"\n Removes the specified key and its associated value from this symbol table\n (if the key is in this symbol table)\n \"\"\"\n self._root = self._delete(self._root, key)\n\n def _delete(self, node, key):\n if node == None:\n return None\n if key.__lt__(node.key):\n node.left = self._delete(node.left, key)\n elif key.__gt__(nodet.key):\n node.right = self._delete(node.right, key)\n else:\n if node.right == None:\n return node.left\n if node.left == None:\n return node.right\n temp_node = node\n node = self._min(temp_node.right)\n node.right = self._delete_min(temp_node.right)\n node.left = temp_node.left\n\n node.size = self._size(node.left) + self._size(node.right) + 1\n return node\n\n def min(self):\n \"\"\"\n Returns the smallest key in the BST\n \"\"\"\n return self._min(self._root).key\n\n def _min(self, node):\n if node.left == None:\n return node\n return self._min(node.left)\n\n def max(self):\n \"\"\"\n Returns the larget key in the symbol table\n \"\"\"\n return self._max(self._root).key\n\n def _max(self, node):\n if node.right == None:\n return node\n return self._max(node.right)\n\n def floor(self, key):\n \"\"\"\n Returns the largest key in the symbol table less than or equal to key\n \"\"\"\n node = self._floor(self._root, key)\n if node == None:\n return None\n return none.key\n\n def _floor(self, node, key):\n if node == None:\n return None\n if key == node.key:\n return node\n if key < node.key:\n return self._floor(node.left, key)\n temp_node = self._floor(node.right, key)\n if not temp_node == None:\n return temp_node\n return node\n\n def keys(self):\n \"\"\"\n Returns all keys in the symbol table as a list.\n \"\"\"\n if self.is_empty():\n return []\n return self.range_keys(self.min(), self.max())\n\n def range_keys(self, lo, hi):\n \"\"\"\n Returns all keys in the symbol table in the given range as a list\n\n :param lo: minimum endpoint\n :param hi: maximum endpoint\n :return: all keys in symbol table between lo (inclusive) and hi (inclusive)\n \"\"\"\n queue = []\n self._range_keys(self._root, queue, lo, hi)\n return queue\n\n def _range_keys(self, node, queue, lo, hi):\n if node == None:\n return\n if lo < node.key:\n self._range_keys(node.left, queue, lo, hi)\n if lo <= node.key and hi >= node.key:\n queue.append(node.key)\n if hi > node.key:\n self._range_keys(node.right, queue, lo, hi)\n\n\n\n def height(self):\n \"\"\"\n Returns the height of the BST (for debugging)\n \"\"\"\n return self._height(self._root)\n\n def _height(self, node):\n if node == None:\n return -1\n return 1 + max(self._height(node.left), self._height(node.right))\n\n def level_order(self):\n \"\"\"\n Returns the keys in the BST in level order (for debugging)\n \"\"\"\n queue, keys = [], []\n queue.append(self._root)\n while len(queue) > 0:\n node = queue.pop(0)\n if node == None:\n continue\n keys.append(node.key)\n queue.append(node.left)\n queue.append(node.right)\n return keys\n\n\n# This is ugly but necessary to use stdlib\n# Need to find a better way of doing it\nimport sys\nsys.path.append(\"..\")\nfrom algs4.stdlib import stdio\n\nif __name__ == \"__main__\":\n if len(sys.argv) > 1:\n try:\n sys.stdin = open(sys.argv[1])\n except IOError:\n print(\"File not found, using standard input instead\")\n\n data = stdio.readAllStrings()\n st = BST()\n i = 0\n for key in data:\n st.put(key, i)\n i += 1\n\n print(\"LEVELORDER:\")\n for key in st.level_order():\n print(str(key) + \" \" + str(st.get(key)))\n\n print()\n\n print(\"KEYS:\")\n for key in st.keys():\n print(str(key) + \" \" + str(st.get(key)))\n\n\n\n\n\n\n"} {"blob_id": "4b5568fc9d69546660e1a932e31ba7347ab61d04", "repo_name": "alessandrozito98/Criptografia-y-Computacion", "path": "/Pr\u00e1cticas/Pr\u00e1ctica 1/Practica1.py", "length_bytes": 9401, "score": 3.96875, "int_score": 4, "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nC\u00f3digo asociado a la primera Pr\u00e1ctica de Criptograf\u00eda y Computaci\u00f3n.\n\n@author: Carlos N\u00fa\u00f1ez Molina\n\"\"\"\n\nfrom random import randint\n\n# Calcula a^b mod m de forma naive\n# Es O(b)\ndef potencia_modular_naive(a, b, m):\n\tres = 1\n\n\tfor i in range(b):\n\t\tres *= a\n\n\t\tres = res % m\n\t\n\treturn res;\n\n# Hace lo mismo que la funci\u00f3n anterior pero de forma eficiente.\n# Ej.: si es 7^100 mod m, 7^100 es 7^64 * 7^32 * 7^4. Lo hago as\u00ed\n# para ahorrar multiplicaciones (esa descomposici\u00f3n viene dada\n# por las cifras donde el n\u00famero en binario vale 1)\n# Es O(log(b))\ndef potencia_modular(a, b, m):\n p = 1\n \n while b > 0:\n \n # Veo si la \u00faltima cifra del n\u00famero en binario vale 1\n if b % 2 == 1:\n p = (p*a) % m # \"Cojo\" esa potencia\n \n b = b >> 1 # Desplazo un bit (cifra en binario)\n \n a = (a*a) % m # Siguiente potencia\n \n return p\n\n# Test de Fermat eligiendo solo \"a\" como testigo\ndef test_fermat(p, a): \n res = potencia_modular(a, p-1, p)\n \n if res == 1:\n return True\n else:\n return False\n \n \n# Test de Fermat\n# Es p primo?\n# 1. Elegimos a tq. 2 <= a <= p-2\n# 2. b = a^p-1 mod p\n# 3. Si b != 1, p no es primo. Si b = 1, p es primo.\ndef test_fermat_repetido(p):\n num_rep = 100\n \n for i in range(num_rep):\n a = randint(2, p-2) # Elegimos aleatoriamente la base del exponente\n \n print(potencia_modular(a, p-1, p))\n \n \n# Funci\u00f3n que obtiene las soluciones de la ecuaci\u00f3n x^2 mod p = 1\n# Si para p esta ecuaci\u00f3n tiene m\u00e1s de dos soluciones p no es primo.\n# Si solo tiene dos soluciones, p puede ser primo\n# Como m\u00ednimo, siempre son soluciones de la ecuaci\u00f3n (ra\u00edces): 1 y p-1\n# Por esto, ver si la ecuaci\u00f3n tiene m\u00e1s de dos ra\u00edces se reduce a ver\n# si hay alg\u00fan otro n\u00famero distinto de 1 y n-1 que sea soluci\u00f3n\ndef raicesuno(p):\n l = []\n \n for i in range(1, p):\n if (i*i) % p == 1:\n l.append(i)\n \n return l\n\n# Calcula las soluciones de la ecuaci\u00f3n x^2 mod p = 1 para los n\u00fameros\n# entre 2 y 99\ndef raicesunorep():\n \n for j in range(2, 100):\n print(j, raicesuno(j))\n\n# Si p es primo\n# a^(p-1) = 1 mod p\n# x\u00b2 - 1 = 0 mod p tiene dos soluciones\n# El test de Miller-Rabin usa estas dos ideas para comprobar si un n\u00famero es primo\n \n# Tenemos n que queremos ver si es primo y a es un testigo (2<=a<=n-2)\n# 1. Descomponemos n-1 como 2^u*s (s impar)\n# 2. Calculamos a = a^s mod n\n# 3. Si a = 1 o a = n-1 -> n es probable primo (Si a=1, al ir iterando y calculando a, siempre va a valer a y de forma parecida pasa cuando vale n-1)\n# 4. Desde i=1 hasta u-1\n# a = a^2 mod n\n# si a = 1 -> n no es primo\n# si a = n-1 -> n es probable primo\n\n# El n\u00famero de testigos falsos es como mucho un cuarto del n\u00famero\n# total de testigos -> Este test falla (da resultado de probable\n# primo cuando no lo es), como mucho un 25% de las veces\n\n# Implementa el paso 1 del test de Miller-Rabin\ndef descomponer_2us(n_m1):\n a = n_m1\n u = 0\n \n while a % 2 == 0:\n a = a // 2\n u += 1\n \n return u, a\n\n# Ejecuta el test de Miller Rabin con el testigo a\n# Devuelve True si n es probable primo y False si es compuesto\ndef test_MillerRabin_unavez(n, a):\n # Paso 1\n u, s = descomponer_2us(n-1)\n \n # Paso 2\n a = potencia_modular(a, s, n)\n \n # Paso 3\n if a == 1 or a == n-1:\n return True\n else:\n for i in range(1, u): # El \u00faltimo caso se corresponde siempre con el Test de Fermat\n a = a*a % n # Igual que potencia_modular(a,2,n)\n \n if a == 1:\n return False\n \n # Si a vale n-1, eso en m\u00f3dulo n es igual a -1\n # As\u00ed, al elevarlo al cuadrado siempre me dar\u00e1 1\n # De esta forma, solo me salen como soluci\u00f3n de la ecuaci\u00f3n\n # 1 y n-1, con lo que n es probable primo\n if a == n-1:\n return True\n\n return False\n\n# Igual que el anterior, pero recibe ya la descomposici\u00f3n de n-1 como 2^u*s\ndef test_MillerRabin_unavez_ya_descompuesto(n, u, s, a):\n # Paso 2\n a = potencia_modular(a, s, n)\n \n # Paso 3\n if a == 1 or a == n-1:\n return True\n else:\n for i in range(1, u): # El \u00faltimo caso se corresponde siempre con el Test de Fermat\n a = a*a % n # Igual que potencia_modular(a,2,n)\n \n if a == 1:\n return False\n \n # Si a vale n-1, eso en m\u00f3dulo n es igual a -1\n # As\u00ed, al elevarlo al cuadrado siempre me dar\u00e1 1\n # De esta forma, solo me salen como soluci\u00f3n de la ecuaci\u00f3n\n # 1 y n-1, con lo que n es probable primo\n if a == n-1:\n return True\n\n return False\n\n# Calcula todos los testigos falsos del n\u00famero compuesto n\n# El test falla para un testigo a si devuelve que n es posible primo pero el\n# el n\u00famero es compuesto\ndef falsos_testigos_test_MillerRabin(n):\n # Guardo la descomposici\u00f3n de n-1 como 2^u*s\n u, s = descomponer_2us(n-1)\n \n # Voy probando todos los testigos desde (2 hasta n-2)\n for i in range(2, n-1):\n res = test_MillerRabin_unavez_ya_descompuesto(n, u, s, i)\n \n if res: # Ha salido que es probable primo -> i es un testigo falso para n\n print(i)\n\n# Igual que la funci\u00f3n anterior, pero en vez de devolver todos los falsos\n# testigos solo prueba con num_testigos\ndef falsos_testigos_test_MillerRabin_algunos(n, num_testigos):\n # Guardo la descomposici\u00f3n de n-1 como 2^u*s\n u, s = descomponer_2us(n-1)\n \n # Voy probando todos los testigos\n for i in range(num_testigos):\n a = randint(2, n-2)\n \n res = test_MillerRabin_unavez_ya_descompuesto(n, u, s, a)\n \n if res: # Ha salido que es probable primo -> a es un testigo falso para n\n print(a, end=\", \")\n\n# Igual que la funci\u00f3n anterior, pero para cada testigo ve si es falso\n# con el test de Fermat y de MillerRabin\ndef falsos_testigos_test_MillerRabin_y_fermat_algunos(n, num_testigos):\n falsos_fermat = []\n falsos_milrab = []\n \n # Guardo la descomposici\u00f3n de n-1 como 2^u*s\n u, s = descomponer_2us(n-1)\n \n # Voy probando todos los testigos\n for i in range(num_testigos):\n a = randint(2, n-2)\n \n res_fermat = test_fermat(n, a) \n res_milrab = test_MillerRabin_unavez_ya_descompuesto(n, u, s, a)\n \n # Compruebo si son falsos testigos\n if res_fermat:\n falsos_fermat.append(a)\n \n if res_milrab:\n falsos_milrab.append(a)\n \n # Imprimo los resultados\n print(\"Fermat ({}): {}\".format(len(falsos_fermat), falsos_fermat))\n print(\"Miller-Rabin ({}): {}\".format(len(falsos_milrab), falsos_milrab))\n\n# Ejecuta el test de Miller Rabin con m testigos elegidos aleatoriamente\ndef test_MillerRabin(n, m):\n # Guardo la descomposici\u00f3n de n-1 como 2^u*s\n u, s = descomponer_2us(n-1)\n \n for i in range(m):\n a = randint(2, n-2) # Testigo\n \n res = test_MillerRabin_unavez_ya_descompuesto(n, u, s, a)\n \n if not res:\n return False # Ya s\u00e9 que no es primo\n \n return True\n\n# Dado n, elige el primer primo p>=n\ndef primer_primo_mayor(n):\n num_rep = 20 # Probabilidad menor a 1 entre un bill\u00f3n\n \n if n % 2 == 0:\n n += 1\n \n es_pos_primo = False\n \n n = n-2\n while not es_pos_primo:\n n += 2 # voy sumandole dos hasta encontrar un probable primo)\n es_pos_primo = test_MillerRabin(n, num_rep)\n \n return n\n\n# Dado n, elige el primer primo fuerte p>=n\n# Primo fuerte: si tanto p como (p-1)/2 es primo\ndef primer_primo_fuerte_mayor(n):\n num_rep = 20 # Probabilidad menor a 1 entre un bill\u00f3n\n \n n += 1 - (n % 2) # Hago que n sea impar\n \n # n tiene que ser impar y congruente con 3 m\u00f3dulo 4\n n += 3 - (n % 4)\n \n es_pos_primo_fuerte = False\n \n # Voy dando saltos de 4 en cuatro (el doble que para ver si el n\u00famero es primo)\n n = n-4\n while not es_pos_primo_fuerte:\n n += 4\n es_pos_primo = test_MillerRabin(n, num_rep)\n \n # Si es posible primo, veo si (p-1)/2 tambi\u00e9n lo es\n if es_pos_primo:\n es_pos_primo_fuerte = test_MillerRabin((n-1)//2, num_rep)\n \n return n\n \n# Dado n, devuelve un primo de n bits\n# p debe estar entre 2^n-1 y 2^n -> Se elige un n\u00famero aleatorio en ese rango\n# y se calcula el siguiente primo\ndef primo_de_longitud_n(n):\n # Elijo un random int entre 2^n-1 y 2^n\n ini = randint(2**(n-1), 2**n)\n \n # Calculo el siguiente primo al n\u00famero elegido\n p = primer_primo_mayor(ini)\n \n return p\n\n# Dado n, devuelve un primo fuerte de n bits\ndef primo_fuerte_de_longitud_n(n):\n # Elijo un random int entre 2^n-1 y 2^n\n ini = randint(2**(n-1), 2**n)\n \n # Calculo el siguiente primo fuerte\n p = primer_primo_fuerte_mayor(ini)\n \n return p\n\n\n\n# En la memoria no hay que escribir mucho, solo hay que poner los resultados:\n# Ej: n no es primo porque es producto de a*b*c y me han salido en esta funci\u00f3n tantos testigos falsos\n\n# Primo grande -> 10 cifras por ejemplo (elegido con nuestra funci\u00f3n de siguiente primo)\n\n# No es necesario hacer main\n"} {"blob_id": "5ce84b611b200b5b8d024122aa6506e3f1eee8c9", "repo_name": "guojia60180/algorithm", "path": "/\u7b97\u6cd5\u9898\u76ee/\u7b97\u6cd5\u9898\u76ee/LeetCode5\u6700\u957f\u56de\u6587\u5b50\u5e8f\u5217.py", "length_bytes": 527, "score": 3.578125, "int_score": 4, "content": "#Author guo\nclass Solution:\n def longestPalindrome(self, s: str) -> str:\n result=''\n for i in range(len(s)):\n tmp=self.palindrome(s,i,i)\n if len(tmp)>len(result):\n result=tmp\n\n tmp=self.palindrome(s,i,i+1)\n if len(tmp)>len(result):\n result=tmp\n return result\n\n#\u5224\u65ad\u662f\u5426\u662f\u56de\u6587\u5e8f\u5217\n def palindrome(self,s,l,r):\n while l>=0 and r<=len(s) and s[l]==s[r]:\n l=l-1\n r=r+1\n return s[l+1:r]"} {"blob_id": "2c107d79b0c138d69d3ef9d14a67d1c677e987a6", "repo_name": "Jsonghh/leetcode", "path": "/200119/Interleaving_String.py", "length_bytes": 930, "score": 3.71875, "int_score": 4, "content": "class Solution:\n \n def isInterleave(self, s1: str, s2: str, s3: str) -> bool:\n memo = {}\n self.helper(s1, s2, s3, memo)\n return memo[(s1, s2)]\n \n \n def helper(self, s1, s2, s3, memo):\n if (s1, s2) in memo:\n return memo[ (s1, s2)]\n \n if len(s1) + len(s2) != len(s3):\n memo[(s1, s2)] = False\n return memo[(s1, s2)]\n \n if not s1:\n memo[(s1, s2)] = s2 == s3\n return memo[(s1, s2)]\n \n if not s2:\n memo[(s1, s2)] = s1 == s3\n return memo[(s1, s2)]\n \n check1, check2 = False, False\n if s1[0] == s3[0]:\n check1 = self.isInterleave(s1[1:], s2, s3[1:])\n \n if s2[0] == s3[0]:\n check2 = self.isInterleave(s1, s2[1:], s3[1:])\n \n memo[(s1, s2)] = check1 or check2\n \n return memo[(s1, s2)]"} {"blob_id": "aab15bb20c8a9f4bc911c56e3ebdd25e76fd3953", "repo_name": "DaveDuck321/FourierTrace", "path": "/render.py", "length_bytes": 6002, "score": 3.890625, "int_score": 4, "content": "\"\"\"\nRenders a path to the screen using pygame\n\"\"\"\n\nfrom fourier import fourier_series, fourier_sum\nfrom camera import Camera, Circle, Line\nimport extrapolate\n\nfrom functools import partial\nfrom itertools import islice, accumulate, count, tee\n\nimport math\nimport time\nimport sys\nimport pickle\n\nimport pygame\n\nRENDER_RADIUS = 512\n\n\ndef timer():\n start = time.time()\n return lambda: time.time()-start\n\n\ndef argand_transform(t, z):\n \"\"\"Returns an argand point representing a complex polar coordinate at angle t\n \"\"\"\n return (\n complex(\n z.real * math.cos(t) + z.imag * math.sin(t),\n z.real * math.sin(t) - z.imag * math.cos(t),\n )\n )\n\n\ndef gen_draw_pendulum(lifetime=1):\n \"\"\"Returns a function that plots the array of pendulums and a point trail\n \"\"\"\n trail = []\n\n def draw_pendulum(camera, accumulation, focus):\n \"\"\"Plots the pendulums representing the current fourier accumulation\n \"\"\"\n for index, (p, c) in enumerate(zip(accumulation, accumulation[1:])):\n circle_color = (0, 50, 255, max(255-abs(index-focus)**2, 30))\n line_color = (255, 255, 255, 50)\n\n if index == focus:\n circle_color = (0, 255, 0)\n line_color = (255, 255, 255)\n\n if index != 0:\n camera.add_shape(Circle(circle_color, p, abs(p-c)))\n camera.add_shape(Line(line_color, p, c))\n\n current_t = time.time()\n trail.append((current_t, accumulation[-1]))\n\n for i in range(len(trail))[::-1]:\n if current_t - trail[i][0] > lifetime:\n trail.pop(i)\n\n for (created, p1), (_, p2) in zip(trail, trail[1:]):\n intensity = 255 - int(255*(current_t-created) / lifetime)\n camera.add_shape(Line((intensity, 0, 0), p1, p2), -created)\n\n return draw_pendulum\n\n\ndef gen_radial_accumulation(POINTS, n=1000):\n \"\"\"Calculates fourier coefficients and returns an expansion function\n This generate a fourier accumulation at a given angle with 'n' terms\n \"\"\"\n PERIOD = 2*math.pi * (max(POINTS)[0]//(2*math.pi) + 1)\n\n PATH = extrapolate.linear_extrapolater(POINTS)\n\n series = fourier_series(PATH, PERIOD)\n terminating = list(islice(series, n))\n\n def radial_accumulation(t):\n return [0]+list(map(\n partial(argand_transform, t),\n accumulate(fourier_sum(terminating, t))\n ))\n\n return radial_accumulation\n\n\ndef get_focal_points(accumulation):\n \"\"\"Returns a list of coefficient indexes and their outer_radius.\n These significantly contribute to the overall shape.\n \"\"\"\n global_radii = [0]+list(accumulate(\n map(\n lambda p: abs(p[0]-p[1]),\n zip(accumulation, accumulation[1:])\n )\n ))\n\n # A pair of iterators representing the radius of the expansion at each term\n outer_radii = tee(map(\n lambda radii: (global_radii[-1] - radii)/2,\n global_radii\n ))\n # Skip the first term, so zip() can alternate values\n next(outer_radii[1])\n\n # Returns a list of the index and outer radius of each term\n # Filter removes terms that dont make a significant contribution to radius\n return list(\n filter(\n lambda val: val[1]*0.99 > val[2],\n zip(count(), *outer_radii)\n )\n )\n\n\ndef is_key_held(keys_down, key, hold_delay=0.2):\n \"\"\"Return True if 'key' is currently held down.\n There is a delay of 'hold_delay' seconds after a key is initially pressed\n \"\"\"\n return key in keys_down and time.time() - keys_down[key] > hold_delay\n\n\ndef update_focus(camera, focal_points, focus, direction):\n \"\"\"Returns the new focus index and updates the camera's focus.\n Diection is a signed integer representing the sign of this change\n \"\"\"\n focus = max(0, min(focus+direction, len(focal_points)-1))\n camera.animate_radius(focal_points[focus][1])\n return focus\n\n\ndef main(path):\n # Init\n pygame.init()\n screen = pygame.display.set_mode((RENDER_RADIUS*2, RENDER_RADIUS*2))\n camera = Camera(screen, RENDER_RADIUS, 2)\n\n draw_pendulum = gen_draw_pendulum(60)\n radial_accumulation = gen_radial_accumulation(path)\n\n # Gameloop\n d_time = 1/60\n running = True\n keys_down = {}\n\n focus = 0\n focal_points = get_focal_points(radial_accumulation(0))\n\n rotation = 0\n while running:\n # Frame logic\n t = timer()\n # Dilate time while zoomed in -- match rotation speed\n rotation += d_time / ((focus+3)//2)\n accumulation = radial_accumulation(rotation)\n\n # Drawing\n screen.fill((0, 0, 0))\n draw_pendulum(camera, accumulation, focal_points[focus][0])\n\n camera.center = accumulation[focal_points[focus][0]]\n\n camera.tick(d_time)\n camera.flush()\n pygame.display.flip()\n\n # Timing\n d_time = t()\n\n if is_key_held(keys_down, pygame.K_RIGHT, 0.2):\n keys_down[pygame.K_RIGHT] = time.time()-0.15\n focus = update_focus(camera, focal_points, focus, 1)\n if is_key_held(keys_down, pygame.K_LEFT, 0.2):\n keys_down[pygame.K_LEFT] = time.time()-0.15\n focus = update_focus(camera, focal_points, focus, -1)\n\n # Events\n for event in pygame.event.get():\n if event.type == pygame.KEYUP:\n if event.key in keys_down:\n del keys_down[event.key]\n if event.type == pygame.KEYDOWN:\n # Log keypress times\n keys_down[event.key] = time.time()\n\n if event.key == pygame.K_RIGHT:\n focus = update_focus(camera, focal_points, focus, 1)\n if event.key == pygame.K_LEFT:\n focus = update_focus(camera, focal_points, focus, -1)\n if event.type == pygame.QUIT:\n running = False\n\n\nif __name__ == \"__main__\":\n with open(sys.argv[1], 'rb') as file:\n path = pickle.load(file)\n main(path)\n"} {"blob_id": "d6efea7ce3fb82466a31c126fcd73b9284e4fb70", "repo_name": "ZheyuWalker/Leetcode-in-python", "path": "/DP/P1657_closeStrings.py", "length_bytes": 1388, "score": 3.6875, "int_score": 4, "content": "# Two strings are considered close if you can attain one from the other using the following operations:\n#\n# Operation 1: Swap any two existing characters.\n# For example, abcde -> aecdb\n# Operation 2: Transform every occurrence of one existing character into another existing character, and do the same with the other character.\n# For example, aacabb -> bbcbaa (all a's turn into b's, and all b's turn into a's)\n# You can use the operations on either Hash as many times as necessary.\n#\n# Given two strings, word1 and word2, return true if word1 and word2 are close, and false otherwise.\n\n\nclass Solution:\n def closeStrings(self, word1: str, word2: str) -> bool:\n def cnt_alpha(s):\n d = dict()\n for i in range(ord('a'), ord('z') + 1):\n n = s.count(chr(i))\n if n in d:\n d[n].append(chr(i))\n else:\n d[n] = [chr(i)]\n return d\n\n if len(word1) != len(word2):\n return False\n for c in word2:\n if c not in word1:\n return False\n\n d1 = cnt_alpha(word1)\n d2 = cnt_alpha(word2)\n\n if len(d1) != len(d2):\n return False\n\n for k in d1.keys():\n if k not in d2:\n return False\n if len(d1[k]) != len(d2[k]):\n return False\n\n return True"} {"blob_id": "1d99b52dace5560942283cdec2687473ca6b95dd", "repo_name": "creageng/lc2016", "path": "/137_Single_Number_II.py", "length_bytes": 953, "score": 3.84375, "int_score": 4, "content": "# Given an array of integers, every element appears three times except for one. Find that single one.\n\n# Note:\n# Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?\n\n\n\n\n\nclass Solution(object):\n def singleNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n ones, twos = 0, 0\n for num in nums:\n ones = ones ^ num & ~twos\n twos = twos ^ num & ~ones\n return ones\n\n\nclass Solution:\n# @param A, a list of integer\n# @return an integer\n\n def singleNumber(self, nums):\n res = 0\n for i in range(0, 32):\n count = 0 \n for num in nums:\n if ((nums >> i) & 1):\n count += 1\n res != ((count % 3) << i)\n return self.covert(res)\n\n def convert(self,x):\n if x >= 2**31:\n x -= 2**32\n return x\n\n\n"} {"blob_id": "db08c747f6afefb7857b20b42862dcce70613de8", "repo_name": "amararias/CodeFights", "path": "/arcade/05_IslandOfKnowledge/CF22_avoidObstacles.py", "length_bytes": 886, "score": 3.9375, "int_score": 4, "content": "# You are given an array of integers representing coordinates of obstacles situated on a straight line.\n\n# Assume that you are jumping from the point with coordinate 0 to the right. You are allowed only to make jumps of the same length represented by some integer.\n\n# Find the minimal length of the jump enough to avoid all the obstacles.\n\n# Example\n\n# For inputArray = [5, 3, 6, 7, 9], the output should be\n# avoidObstacles(inputArray) = 4.\n\n# Check out the image below for better understanding:\ndef checkValid(s, divisor):\n signal = True\n for num in s:\n if num % divisor == 0:\n signal = False\n break\n return signal\n \ndef avoidObstacles(s):\n l = []\n for i in range(2, max(s)+2):\n print(i)\n if checkValid(s, i):\n l.append(i)\n return min(l)\n\ninputArray = [5, 3, 6, 7, 9]\nprint(avoidObstacles(inputArray))"} {"blob_id": "c6d516ea37426b97d3b96089bdffa0675a6bffcf", "repo_name": "sandeepyadav10011995/Data-Structures", "path": "/Pattern-Sliding Window/3. Longest Substring With K Distinct Characters.py", "length_bytes": 3689, "score": 3.53125, "int_score": 4, "content": "\"\"\"\r\n------------------------------------------------ SLIDING WINDOW --------------------------------------------------------\r\nTypes of Sliding Window -:\r\n1. Fixed Length : When k, i.e. sliding window size is provided as a constraint.\r\n2. Dynamic Variant: Caterpillar\r\n\r\nHow to recognize these problems ?\r\nThings we iterate over sequentially;\r\n a. Contiguous Sequence of elements.\r\n b. Sliding arrays, linked-lists\r\n\r\nIn terms of the way questions are asked ? => Min, Max, Largest, Shortest\r\nQuestions Variants\r\n1. Fixed Length: Max Sub-array of size k\r\n2. Dynamic Variant: Smallest Sum (equal to S) => Will need to use Auxiliary DS, i.e. Arrays or Hashmap\r\n a. Largest sub-string with no more than k distinct characters.\r\n b. String Permutations\r\n\r\nQuestion: Given a string, find the length of the longest substring in it with no more than K distinct characters.\r\n\r\n Algo:\r\n 1. First, we will insert characters from the beginning of the string until we have K distinct characters\r\n in the HashMap.\r\n 2. These characters will constitute our sliding window. We are asked to find the longest such window having\r\n no more than K distinct characters. We will remember the length of this window as the longest window so far.\r\n 3. After this, we will keep adding one character in the sliding window (i.e., slide the window ahead) in a\r\n stepwise fashion.\r\n 4. In each step, we will try to shrink the window from the beginning if the count of distinct characters in\r\n the HashMap is larger than K. We will shrink the window until we have no more than K distinct characters in\r\n the HashMap. This is needed as we intend to find the longest window.\r\n 5. While shrinking, we\u2019ll decrement the character\u2019s frequency going out of the window and remove it from the\r\n HashMap if its frequency becomes zero.\r\n 6. At the end of each step, we\u2019ll check if the current window length is the longest so far, and if so, remember\r\n its length.\r\n\r\nExample:\r\nOutput:\r\n\r\n------------------------------------------------------ CODE ------------------------------------------------------------\r\n\"\"\"\r\n\r\n\r\nclass LongestSubstringKDistinctCharacters:\r\n @staticmethod\r\n def longest_substring_with_k_distinct(str1: str, K: int) -> int:\r\n max_length = 0\r\n window_start = 0\r\n char_freq = {}\r\n for window_end in range(len(str1)):\r\n right_char = str1[window_end]\r\n if right_char not in char_freq:\r\n char_freq[right_char] = 0\r\n char_freq[right_char] += 1\r\n # shrink the sliding window, until we are left with 'k' distinct characters in the char_frequency\r\n while len(char_freq) > K:\r\n left_char = str1[window_start]\r\n char_freq[left_char] -= 1\r\n if char_freq[left_char] == 0:\r\n del char_freq[left_char]\r\n window_start += 1 # shrink the window\r\n # remember the max_length so far\r\n max_length = max(max_length, window_end - window_start + 1)\r\n return max_length\r\n\r\n\r\ndef main():\r\n lskdc = LongestSubstringKDistinctCharacters()\r\n print(\"Length of the longest sub-string: \" + str(lskdc.longest_substring_with_k_distinct(\"araaci\", 2)))\r\n print(\"Length of the longest sub-string: \" + str(lskdc.longest_substring_with_k_distinct(\"araaci\", 1)))\r\n print(\"Length of the longest sub-string: \" + str(lskdc.longest_substring_with_k_distinct(\"cbbebi\", 3)))\r\n\r\n\r\nmain()\r\n\r\n\"\"\"\r\nOverall TC : O(2N) --> O(N)\r\nOverall SC: O(K+1) --> O(K)\r\n\"\"\"\r\n"} {"blob_id": "542468850d97510a4a6e3a4568c21fced0c31b83", "repo_name": "chuzcjoe/Leetcode", "path": "/109. Convert Sorted List to Binary Search Tree.py", "length_bytes": 1007, "score": 3.84375, "int_score": 4, "content": "# Definition for singly-linked list.\r\n# class ListNode:\r\n# def __init__(self, val=0, next=None):\r\n# self.val = val\r\n# self.next = next\r\n# Definition for a binary tree node.\r\n# class TreeNode:\r\n# def __init__(self, val=0, left=None, right=None):\r\n# self.val = val\r\n# self.left = left\r\n# self.right = right\r\nclass Solution:\r\n def sortedListToBST(self, head: ListNode) -> TreeNode:\r\n \r\n val = []\r\n \r\n while head:\r\n val.append(head.val)\r\n head = head.next\r\n \r\n def buildBST(nodes, left, right):\r\n \r\n if left > right:\r\n return\r\n \r\n mid = (left+right) // 2\r\n \r\n root = TreeNode(nodes[mid])\r\n \r\n root.left = buildBST(nodes, left, mid-1)\r\n root.right = buildBST(nodes, mid+1, right)\r\n \r\n return root\r\n \r\n return buildBST(val, 0, len(val)-1)\r\n "} {"blob_id": "1c866ac447232216df45c1f5eac79276cf1a0e9d", "repo_name": "Yeshwanthyk/algorithms", "path": "/leetcode/079_leet_minimum_substring.py", "length_bytes": 2040, "score": 4.15625, "int_score": 4, "content": "\"\"\"\nGiven a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).\n\nExample:\n\nInput: S = \"ADOBECODEBANC\", T = \"ABC\"\nOutput: \"BANC\"\n\nSimilar template:\n- Longest Substring with At Most Two Distinct Characters\n- Longest Substring Without Repeating Characters\n\"\"\"\n\nfrom collections import Counter\n\n# Psuedo Code\n# * Two pointer system - start, end\n# * Move end to find all the characters of T in S\n# * Retract start to find min_win\n# * Keep moving `end` till S is over and keep updating min_win\n\n\ndef min_window(S, T):\n\n if not S:\n return \"\"\n\n start = 0\n\n # Make a hashmap of the string we need to find\n T_map = Counter(T)\n # Keep track of the number of chars of T we found in S\n T_len = len(T)\n\n min_win = \"\"\n\n for end, char in enumerate(S):\n\n # If we find a char from T in S, we reduce `T_len`. If `T_len` becomes 0 we know that we found all the\n # chars in T\n if T_map[char] > 0:\n T_len -= 1\n\n # We keep adding all the chars of S we move through to the hashmap\n # Later when we start retracting `start`, this would help us to ensure we retract correctly\n T_map[char] -= 1\n\n while (T_len == 0):\n\n # Find length of the current substring that contains all chars of `T`. Later on as we keep retracting\n # if we find a smaller substring we can update `min_win` with that\n min_len = end - start + 1\n\n # if min_win is empty or if the len of new window is lesser than the older substring, we update it\n if not min_win or min_len < len(min_win):\n min_win = S[start:end+1]\n\n # we update the first char, and we check if is a part of `T`. If it is, we move `end` until we\n # find another substring\n T_map[S[start]] += 1\n\n if (T_map[S[start]] > 0):\n T_len += 1\n\n start += 1\n\n return min_win\n\n\nS = \"ADOBECODEBANC\"\nT = \"ABC\"\nans = min_window(S, T)\nprint(ans)\n"} {"blob_id": "7c5c3d3e8def5c8d2e6027fc05a479a94640cf24", "repo_name": "FilipLe/DailyInterviewPro-Unsolved", "path": "/Kaprekars Constant (SOLVED)/kaprekars.py", "length_bytes": 2312, "score": 4.0625, "int_score": 4, "content": "import math\nKAPREKAR_CONSTANT = 6174\n\ndef num_kaprekar_iterations(n):\n #Fill this in.\n large = 0\n small = 0\n counter = 0\n result = n\n #loop for the main function\n while result != KAPREKAR_CONSTANT:\n #get num in descending order\n large = getLarger(result)\n #get num in ascending order\n small = getSmaller(result)\n #Subtract the ascending number from the descending number.\n result = abs(large-small)\n #count number of iterations\n counter += 1\n return counter\n\n#function to convert the number into an array of digits \ndef convert_to_array(n):\n #convert input into a string\n number = str(n)\n #create an empty list to store the digits\n arr = []\n #iterate through the digits\n for digits in number:\n #add each digit into the array\n arr.append(digits)\n #return the array of digits\n return arr\n \n#sort the number into a number with digits in descending order (decreasing from left to right) -->largest possible\ndef getLarger(n):\n #convert num into array of digits\n arr = convert_to_array(n)\n #function to sort the array into descending order\n arr.sort(reverse=True)\n count = 0\n numStr = ''\n #while loop to iterate through the sorted array of digits to put them into one string\n while count < len(arr):\n numStr += arr[count]\n count += 1\n #convert the string into integer with digits in descending order\n numStr = int(numStr)\n #return num with digits in descending order\n return numStr\n\n#sort the number into a number with digits in ascending order (increasing from left to right) -->smallest possible\ndef getSmaller(n):\n #convert num into array of digits\n arr = convert_to_array(n)\n #function to sort the array into ascending order\n arr.sort()\n count = 0\n numStr = ''\n #while loop to iterate through the sorted array of digits to put them into one string\n while count < len(arr):\n numStr += arr[count]\n count +=1\n #convert the string into integer with digits in ascending order\n numStr = int(numStr)\n #return num with digits in ascending order\n return numStr\n\nprint(num_kaprekar_iterations(3524))\n# 3\n# Explanation:\n# 5432 - 2345 = 3087\n# 8730 - 0378 = 8352\n# 8532 - 2358 = 6174 (3 iterations)\n"} {"blob_id": "6f1ff3a3b16c190fe8967efdace456554e6d9aef", "repo_name": "syurskyi/Algorithms_and_Data_Structure", "path": "/_algorithms_challenges/leetcode/LeetCode/1021 Remove Outermost Parentheses.py", "length_bytes": 2688, "score": 4.15625, "int_score": 4, "content": "#!/usr/bin/python3\n\"\"\"\nA valid parentheses string is either empty (\"\"), \"(\" + A + \")\", or A + B, where\nA and B are valid parentheses strings, and + represents string concatenation.\nFor example, \"\", \"()\", \"(())()\", and \"(()(()))\" are all valid parentheses strings.\n\nA valid parentheses string S is primitive if it is nonempty, and there does not\nexist a way to split it into S = A+B, with A and B nonempty valid parentheses\nstrings.\n\nGiven a valid parentheses string S, consider its primitive decomposition:\nS = P_1 + P_2 + ... + P_k, where P_i are primitive valid parentheses strings.\n\nReturn S after removing the outermost parentheses of every primitive string in\nthe primitive decomposition of S.\n\nExample 1:\nInput: \"(()())(())\"\nOutput: \"()()()\"\nExplanation:\nThe input string is \"(()())(())\", with primitive decomposition \"(()())\" + \"(())\".\nAfter removing outer parentheses of each part, this is \"()()\" + \"()\" = \"()()()\".\n\nExample 2:\nInput: \"(()())(())(()(()))\"\nOutput: \"()()()()(())\"\nExplanation:\nThe input string is \"(()())(())(()(()))\", with primitive decomposition\n\"(()())\" + \"(())\" + \"(()(()))\".\nAfter removing outer parentheses of each part, this is \"()()\" + \"()\" +\n\"()(())\" = \"()()()()(())\".\n\nExample 3:\nInput: \"()()\"\nOutput: \"\"\nExplanation:\nThe input string is \"()()\", with primitive decomposition \"()\" + \"()\".\nAfter removing outer parentheses of each part, this is \"\" + \"\" = \"\".\n\n\nNote:\nS.length <= 10000\nS[i] is \"(\" or \")\"\nS is a valid parentheses string\n\"\"\"\nfrom collections import deque\n\n\nclass Solution:\n def removeOuterParentheses(self, S: str) -> str:\n \"\"\"\n Primitive parentheses will have equal number of opened and closed\n parentheses.\n\n Use count\n Exclude the first and last parathesis\n \"\"\"\n ret = []\n cnt = 0\n for e in S:\n if e == \"(\":\n cnt += 1\n if cnt > 1:\n ret.append(e)\n else:\n cnt -= 1\n if cnt > 0:\n ret.append(e)\n\n return \"\".join(ret)\n\n\n def removeOuterParentheses_error(self, S: str) -> str:\n \"\"\"\n stack + deque\n \"\"\"\n ret = []\n stk = []\n cur_q = deque()\n for e in S:\n if e == \"(\":\n stk.append(e)\n else:\n prev = stk.pop()\n if stk:\n cur_q.appendleft(prev)\n cur_q.append(e)\n else:\n ret.extend(cur_q)\n cur_q = deque()\n\n return \"\".join(ret)\n\n\nif __name__ == \"__main__\":\n assert Solution().removeOuterParentheses(\"(()())(())(()(()))\") == \"()()()()(())\"\n"} {"blob_id": "bad9ddae8e59ed27823113196eb286765cb93fed", "repo_name": "homeah/git", "path": "/prime_generator_iter.py", "length_bytes": 695, "score": 4.15625, "int_score": 4, "content": "import math\ndef is_prime(number):\n if number > 1:\n if number == 2:\n return True\n if number % 2 == 0:\n return False\n for current in range(3,int(math.sqrt(number)+1),2):\n if number % current == 0:\n return False\n return True\n return False\n\ndef get_primes(number):\n while True:\n if is_prime(number):\n number = yield number #\u9996\u6b21none\uff0c\u518d\u6b21\u9700\u8981send\u624d\u80fd\u8d4b\u503c?\n number += 1\n\ndef print_successive_primes(iteration,base = 10):\n prime_generator = get_primes(base)\n prime_generator.send(None)\n for power in range(iteration):\n print(prime_generator.send(base **power))\n\n\n"} {"blob_id": "e8f12f7028cab41b1cd51e1708815c932b00b528", "repo_name": "abhisheksingh75/Practice_CS_Problems", "path": "/Arrays/First_Missing_Integer2.py", "length_bytes": 742, "score": 3.75, "int_score": 4, "content": "\"\"\"\nGiven an unsorted integer array, find the first missing positive integer. \nExample: Given [1,2,0] return 3, [3,4,-1,1] return 2, [-8, -7, -6] returns 1 \nYour algorithm should run in O(n) time and use constant space.\n\"\"\"\n\nclass Solution:\n def firstMissingPositive(self, A):\n N = len(A)\n i = 0\n tmp = 0\n while(i < N):\n \n if A[i] < 1 or A[i] > N or A[i] == i+1 or A[A[i]-1] == A[i]:\n i += 1\n continue\n else:\n tmp = A[A[i]-1] \n A[A[i]-1] = A[i]\n A[i] = tmp \n \n for i in range(len(A)):\n if A[i] != i+1:\n return i+1\n \n return N+1\n \n"} {"blob_id": "d774cdec3a37c00e4a8ee831b5a92ee83c8f526f", "repo_name": "aldabbagh/Classes", "path": "/CV/ps4.py", "length_bytes": 12634, "score": 3.671875, "int_score": 4, "content": "import numpy as np\r\nimport cv2\r\n\r\n\r\ndef solve_least_squares(pts3d, pts2d):\r\n \"\"\"Solves for the transformation matrix M that maps each 3D point to corresponding 2D point\r\n using the least-squares method. See np.linalg.lstsq.\r\n\r\n Args:\r\n pts3d (numpy.array): 3D global (x, y, z) points of shape (N, 3). Where N is the number of points.\r\n pts2d (numpy.array): corresponding 2D (u, v) points of shape (N, 2). Where N is the number of points.\r\n\r\n Returns:\r\n tuple: two-element tuple containing:\r\n M (numpy.array): transformation (a.k.a. projection) matrix of shape (3, 4).\r\n error (float): sum of squared residuals of all points.\r\n \"\"\"\r\n number_of_points = len(pts3d)\r\n A = []\r\n B = []\r\n\r\n #construct A and B matrices to calculte M using (A x M = B)\r\n for i in range(number_of_points):\r\n X,Y,Z = pts3d[i]\r\n u,v = pts2d[i]\r\n #This is as described in office hours Feb. 21 https://www.youtube.com/watch?v=K3YfaeG6ZuU\r\n A.append([X,Y,Z,1,0,0,0,0,-u*X,-u*Y,-u*Z])\r\n A.append([0,0,0,0,X,Y,Z,1,-v*X,-v*Y,-v*Z])\r\n\r\n #Add u,v values to B in alteration\r\n B.append(u)\r\n B.append(v)\r\n\r\n A = np.asarray(A)\r\n B = np.asarray(B).transpose()\r\n\r\n #Apply linalg.lstsq https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.lstsq.html\r\n #returns solution(M), residuals, rank, s\r\n\r\n solution = np.linalg.lstsq(A,B) #This gets us values of m from m00 to m22\r\n M = np.append(solution[0],[1.0])*(-0.5968000) #First we add the value of m23 (which is 1.0) then this multiplied by the value in the HW M[2,3]\r\n residuals = solution[1][0]\r\n return M.reshape((3,4)),residuals\r\n pass\r\n\r\n\r\ndef project_points(pts3d, m):\r\n \"\"\"Projects each 3D point to 2D using the matrix M.\r\n\r\n Args:\r\n pts3d (numpy.array): 3D global (x, y, z) points of shape (N, 3). Where N is the number of points.\r\n m (numpy.array): transformation (a.k.a. projection) matrix of shape (3, 4).\r\n\r\n Returns:\r\n numpy.array: projected 2D (u, v) points of shape (N, 2). Where N is the same as pts3d.\r\n \"\"\"\r\n\r\n numPoints = len(pts3d)\r\n newPts3d = np.zeros((numPoints,4))\r\n #add ones to the points\r\n for i in range(numPoints):\r\n point = pts3d[i]\r\n newPoint = np.append(point,1.0)\r\n newPts3d[i] =newPoint\r\n\r\n #projected 2D (u, v) points of shape (N, 2). Where N is the same as pts3d.\r\n projectedPoints = np.zeros((numPoints,2))\r\n i =0\r\n\r\n for point in newPts3d:\r\n #calculate product\r\n p = np.dot(m,point) # this gets us [u',v',s]\r\n #divide u and v by the last value (s) to get [u, v, 1]\r\n u = p[0]/p[2]\r\n v = p[1]/p[2]\r\n projectedPoints[i]=[u,v]\r\n i+=1\r\n\r\n return projectedPoints\r\n pass\r\n\r\n\r\ndef get_residuals(pts2d, pts2d_projected):\r\n \"\"\"Computes residual error for each point.\r\n\r\n Args:\r\n pts2d (numpy.array): observed 2D (u, v) points of shape (N, 2). Where N is the number of points.\r\n pts2d_projected (numpy.array): 3D global points projected to 2D of shape (N, 2).\r\n Where N is the number of points.\r\n\r\n Returns:\r\n numpy.array: residual error for each point (L2 distance between each observed and projected 2D points).\r\n The array shape must be (N, 1). Where N is the same as in pts2d and pts2d_projected.\r\n \"\"\"\r\n def get_l2_distance(pt1, pt2):\r\n # http://stackoverflow.com/questions/1401712/how-can-the-euclidean-distance-be-calculated-with-numpy\r\n dist = np.linalg.norm(pt1-pt2)\r\n return dist\r\n\r\n numberOfPoints = len(pts2d)\r\n residualErr = []\r\n for i in range(numberOfPoints):\r\n distance = get_l2_distance(pts2d[i],pts2d_projected[i])\r\n residualErr.append([distance])\r\n\r\n return np.asarray(residualErr)\r\n pass\r\n\r\n\r\ndef calibrate_camera(pts3d, pts2d, set_size_k):\r\n \"\"\"Finds the best camera projection matrix given corresponding 3D and 2D points.\r\n\r\n Args:\r\n pts3d (numpy.array): 3D global (x, y, z) points of shape (N, 3). Where N is the number of points.\r\n pts2d (numpy.array): corresponding 2D (u, v) points of shape (N, 2). Where N is the number of points.\r\n set_size_k (int): set of k random points to choose from pts2d.\r\n\r\n Returns:\r\n tuple: three-element tuple containing:\r\n bestM (numpy.array): best transformation matrix M of shape (3, 4).\r\n error (float): sum of squared residuals of all points for bestM.\r\n avg_residuals (numpy.array): Average residuals array, one row for each iteration.\r\n The array should be of shape (10, 1).\r\n \"\"\"\r\n\r\n \"\"\"\r\n - Randomly choose k points from the 2D list and their corresponding points in the 3D list.\r\n - Compute the projection matrix M on the chosen points.\r\n - Pick 4 points not in your set of k, and compute the average residual.\r\n - Return the M that gives the lowest residual.\r\n \"\"\"\r\n def compute_average_residual(pts2dProjected, points2d):\r\n residuals = get_residuals(points2d,pts2dProjected)\r\n return np.mean(residuals)\r\n\r\n numberOfPoints = len(pts3d)\r\n concatTemp = np.zeros((numberOfPoints,5))\r\n concatTemp[:,0:3] = pts3d\r\n concatTemp[:,3:] = pts2d\r\n\r\n mPairs = []\r\n avg_residuals = []\r\n for i in range(10):\r\n np.random.shuffle(concatTemp)\r\n # Randomly choose k points from the 2D list and their corresponding points in the 3D list.\r\n k_points = concatTemp[:set_size_k,:]\r\n chosen3d = k_points[:,0:3]\r\n chosen2d = k_points[:,3:]\r\n\r\n # Compute the projection matrix M on the chosen points.\r\n M,residuals = solve_least_squares(chosen3d,chosen2d)\r\n pts2dProjected = project_points(chosen3d,M)\r\n\r\n # Pick 4 points not in your set of k\r\n otherfour = concatTemp[set_size_k:set_size_k+4,:]\r\n other3d = otherfour[:,0:3]\r\n other2d = otherfour[:,3:]\r\n\r\n # Compute the average residual\r\n averageResidualErr = compute_average_residual(pts2dProjected,other2d)\r\n\r\n mPairs.append([M,averageResidualErr])\r\n avg_residuals.append([averageResidualErr])\r\n\r\n # Return the M that gives the lowest residual.\r\n output = mPairs[0][0]\r\n lowestResidual = mPairs[0][1]\r\n for i in range(len(mPairs)):\r\n err = mPairs[i][1]\r\n if err= self.Min:\n super().push(x)\n else:\n super().push(x * 2 - self.Min)\n self.Min = x\n\n def pop(self):\n if super().peek() >= self.Min:\n val = super().pop()\n else:\n val = self.Min\n x = super().pop()\n self.Min = 2 * self.Min - x\n return val\n\n def peek(self):\n if super().peek() >= self.Min:\n val = super().peek()\n else:\n val = self.Min\n return val\n # function should return minimum element from the stack\n def getmin(self):\n return self.Min\n\n\n\nss = SpecialStack()\nss.push(18)\nss.push(19)\nss.push(29)\nprint(ss.getmin())\nss.push(15)\nprint(ss.getmin())\nss.push(15)\nprint(ss.getmin())\nprint(ss.pop())\nss.push(5)\nprint(ss.getmin())\nprint(ss.pop())\nprint(ss.getmin()) # 15\nprint(ss.pop())\nprint(ss.getmin()) # 18\nprint(ss.pop()) #29\nprint(ss.getmin()) #18\nprint(ss.pop()) #19\nprint(ss.getmin()) #18\nprint(ss.pop()) #18\nprint(ss.getmin()) #18\nprint(ss.pop())\nprint(ss.getmin()) # empty"} {"blob_id": "111e71f185df03518b6a52adb48549204f2225b5", "repo_name": "hasanmubarok9/Hackerrank-Problem-Solving", "path": "/countTriplets.py", "length_bytes": 505, "score": 3.5, "int_score": 4, "content": "from collections import defaultdict\ndef countTriplets(arr, r):\n v2 = defaultdict(int)\n v3 = defaultdict(int)\n count = 0\n for k in arr:\n print(\"nilai k \", k)\n count += v3[k]\n v3[k*r] += v2[k]\n v2[k*r] += 1\n print(\"nilai count \", count)\n print(\"nilai v3 \", v3)\n print(\"nilai v2 \", v2)\n\n return count\n\n# print(countTriplets([1 for _ in range(100)], 1))\nprint(countTriplets([1, 3, 9, 9, 27, 81], 3))\n# print(countTriplets([1, 5, 5, 25, 125], 5))"} {"blob_id": "9c2a48bdb3c604fe733ca450cf9ceeea0695361e", "repo_name": "yunieyuna/Solutions-for-Leetcode-Problems", "path": "/python_solutions/274-h-index.py", "length_bytes": 476, "score": 3.609375, "int_score": 4, "content": "# https://leetcode.com/problems/h-index/\n\nclass Solution:\n def hIndex(self, citations: List[int]) -> int:\n citations.sort(reverse = True)\n for idx, citation in enumerate(citations):\n if idx >= citation:\n return idx\n \n return len(citations)\n \n\"\"\"\nRuntime: 36 ms, faster than 64.67% of Python3 online submissions for H-Index.\nMemory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for H-Index.\n\"\"\"\n"} {"blob_id": "5542c0a91d67cea67f729e546f810c8f7f43e01f", "repo_name": "jbbaena/cryptopals", "path": "/Set1/set1_ch3.py", "length_bytes": 1997, "score": 3.765625, "int_score": 4, "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jul 16 19:41:56 2019\n\n@author: crypto\n\"\"\"\n\nimport string \n\n\nCHARACTER_FREQ = {\n 'a': 0.0651738, 'b': 0.0124248, 'c': 0.0217339, 'd': 0.0349835, 'e': 0.1041442, 'f': 0.0197881, 'g': 0.0158610,\n 'h': 0.0492888, 'i': 0.0558094, 'j': 0.0009033, 'k': 0.0050529, 'l': 0.0331490, 'm': 0.0202124, 'n': 0.0564513,\n 'o': 0.0596302, 'p': 0.0137645, 'q': 0.0008606, 'r': 0.0497563, 's': 0.0515760, 't': 0.0729357, 'u': 0.0225134,\n 'v': 0.0082903, 'w': 0.0171272, 'x': 0.0013692, 'y': 0.0145984, 'z': 0.0007836, ' ': 0.1918182\n}\n\n\ndef get_english_score(byte_string):\n \"\"\"Given an string od bytes, it returns a score which is the sum of the probabilities in how each letter of the input string\n appears in the English language. Uses the above probabilities.\n \"\"\"\n score = 0\n\n for byte in byte_string:\n score += CHARACTER_FREQ.get(chr(byte).lower(), 0)\n\n return score\n\ndef xor_single_char(byte_string, single_byte):\n \"\"\"both inputs are in bytes\"\"\"\n output = b''\n for char in byte_string:\n output += bytes([char ^ single_byte])\n \n return output\n \ndef dec_sin_char(byte_string):\n '''the input shpuld be a bytes string'''\n ''' It tries all possible keys and out put the decryption with hights score and its corresponging Key'''\n max = 0;\n decryption = '';\n key ='';\n\n for i in range(256):\n #print(i)\n result = xor_single_char(byte_string,i)\n score = get_english_score(result) \n # print(score)\n if score > max:\n max = score\n decryption = result\n key = i\n \n return key, decryption\n#print(bytes.fromhex(decryption).decode('ascii')) \n\n#input_string ='1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736'\n#cipher_text = bytes.fromhex(input_string);\n#key, plain_text = dec_sin_char(cipher_text)\n\n#print('Key:', chr(key), ',', 'Plain_Text: ', plain_text.decode('utf-8'))\n\n"} {"blob_id": "3c595033086482c9ef83494660c074f7d12e0281", "repo_name": "MTrajK/coding-problems", "path": "/Math/calculate_area_of_polygon.py", "length_bytes": 1078, "score": 4.28125, "int_score": 4, "content": "'''\nCalculate Area of Polygon\n\nGiven ordered coordinates of a polygon with n vertices. Find area of the polygon.\nHere ordered mean that the coordinates are given either in clockwise manner or anticlockwise from first vertex to last.\n\nInput: [(0, 0), (3, 0), (3, 2), (0, 2)]\nOutput: 6.0\nOutput explanation: The polygon is a 3x2 rectangle parallel with the X axis. The area is 6 (3*2).\n\n=========================================\nUse Shoelace formula (https://en.wikipedia.org/wiki/Shoelace_formula).\nabs( 1/2 ((X1Y2 + X2Y3 + ... + Xn-1Yn + XnY1) - (X2Y1 + X3Y2 + ... + XnYn-1 + X1Yn)) )\n Time Complexity: O(N)\n Space Complexity: O(1)\n'''\n\n\n############\n# Solution #\n############\n\ndef calculate_area_of_polygon(polygon):\n n = len(polygon)\n prev = polygon[-1]\n area = 0\n\n for curr in polygon:\n area += (prev[0] + curr[0]) * (prev[1] - curr[1])\n prev = curr\n\n return abs(area / 2) # return absolute value\n\n\n###########\n# Testing #\n###########\n\n# Test 1\n# Correct result => 6.0\nprint(calculate_area_of_polygon([(0, 0), (3, 0), (3, 2), (0, 2)]))"} {"blob_id": "1f49b0a86e395d4a300650813564c672a91e3bcf", "repo_name": "neerajp99/algorithms", "path": "/dynamic-programming/problems/subsets_count_sum.py", "length_bytes": 1598, "score": 3.671875, "int_score": 4, "content": "# Given an array arr[] of length N and an integer X, the task is to find the number of subsets with a sum equal to X.\n\"\"\"\n Input: arr[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n Target = 11\n Output: 4\n\"\"\"\n\n# Approach 1: Using recursion (backtracking)\ndef recursive_subset_count(arr, n, max_sum):\n if max_sum == 0:\n return 1\n if n == 0:\n return 0\n if arr[n-1] > max_sum:\n return recursive_subset_count(arr, n-1, max_sum)\n return recursive_subset_count(arr, n-1, max_sum) + recursive_subset_count(arr, n-1, max_sum-arr[n-1])\n\n\n# Approach 2: Using Dynamic Programming\ndef dp_subset_count(arr, n, max_sum):\n dp = [[0 for i in range(max_sum+1)] for j in range(n+1)]\n for i in range(n+1):\n dp[i][0] = 1\n for i in range(1, n+1):\n for j in range(1, max_sum+1):\n if arr[i-1] > j:\n dp[i][j] = dp[i-1][j]\n else:\n dp[i][j] = dp[i-1][j] + dp[i-1][j-arr[i-1]]\n return dp[n][max_sum]\n\n# Approach 3: Using recursion to count all the subsets\ndef recursive_subset_check_count(ip, op, final, target):\n if ip == []:\n if sum(op) == target:\n final.append(op)\n return\n recursive_subset_check_count(ip[1:], op, final, target)\n recursive_subset_check_count(ip[1:], op + [ip[0]], final, target)\n\n\nfinal = []\narr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\ntarget = 11\nrecursive_subset_check_count(arr, [], final, target)\nprint(final)\nprint(len(final))\n\nprint(dp_subset_count([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 10, 11))\nprint(recursive_subset_count([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 10, 11))"} {"blob_id": "e6e1fa653cc44f8ee78b0707577ba3942b1bdedd", "repo_name": "arfu2016/DuReader", "path": "/wiki-word2vec/pca.py", "length_bytes": 4294, "score": 3.6875, "int_score": 4, "content": "\"\"\"\n@Project : DuReader\n@Module : pca.py\n@Author : Deco [deco@cubee.com]\n@Created : 5/24/18 1:16 PM\n@Desc :\n\nIn Depth: Principal Component Analysis\nhttps://jakevdp.github.io/PythonDataScienceHandbook/05.09-principal-component-analysis.html\n\nPCA and proportion of variance explained:\nhttps://stats.stackexchange.com/questions/22569/pca-and-proportion-of-variance-explained\n\nMaking sense of principal component analysis, eigenvectors & eigenvalues\nhttps://stats.stackexchange.com/questions/2691/making-sense-of-principal-component-analysis-eigenvectors-eigenvalues\n\"\"\"\n\n'''\n\u56e0\u4e3a\u7528\u4e86numpy\u5305\uff0c\u7b97\u6cd5\u7684\u5b9e\u73b0\u975e\u5e38\u7b80\u5355\uff0c\u5982\u679c\u7eaf\u7cb9\u7528C\u5199\u7684\u8bdd\u8981\u590d\u6742\u7684\u591a\u3002\n\n\u9996\u5148\u5bf9\u5411\u91cfX\u8fdb\u884c\u53bb\u4e2d\u5fc3\u5316\n\u63a5\u4e0b\u6765\u8ba1\u7b97\u5411\u91cfX\u7684\u534f\u65b9\u5dee\u77e9\u9635\uff0c\u81ea\u7531\u5ea6\u53ef\u4ee5\u9009\u62e90\u6216\u80051\n\u7136\u540e\u8ba1\u7b97\u534f\u65b9\u5dee\u77e9\u9635\u7684\u7279\u5f81\u503c\u548c\u7279\u5f81\u5411\u91cf\n\u9009\u53d6\u6700\u5927\u7684k\u4e2a\u7279\u5f81\u503c\u53ca\u5176\u7279\u5f81\u5411\u91cf\n\u7528X\u4e0e\u7279\u5f81\u5411\u91cf\u76f8\u4e58\n'''\n\n\"\"\"\nCreated on Mon Sep 4 19:58:18 2017\n\n@author: zimuliu\nhttp://blog.jobbole.com/109015/\n\"\"\"\n\nfrom sklearn.datasets import load_iris\nimport numpy as np\nfrom numpy.linalg import eig\nimport matplotlib.pyplot as plt\n\nfrom sklearn import decomposition\n\n\ndef pca(X, k):\n print('mean used in pca:', X.mean(axis=0))\n # Standardize by remove average\n X = X - X.mean(axis=0)\n\n # Calculate covariance matrix:\n X_cov = np.cov(X.T, ddof=0)\n print('Covariance of the data matrix:')\n print(X_cov)\n\n # Calculate eigenvalues and eigenvectors of covariance matrix\n eigenvalues, eigenvectors = eig(X_cov)\n\n # top k large eigenvectors\n klarge_index = eigenvalues.argsort()[-k:][::-1]\n k_eigenvectors = eigenvectors[klarge_index]\n print('Coordinates of mean after eigenvector transform:',\n np.dot(X.mean(axis=0), k_eigenvectors.T))\n print('eigenvectors:')\n print(k_eigenvectors)\n print('Coordinates of eigenvectors after transform:')\n print(np.dot(k_eigenvectors, k_eigenvectors.T))\n print('Explained variance:', eigenvalues/sum(eigenvalues))\n\n return np.dot(X, k_eigenvectors.T)\n\n\ndef sk_pca(X, k):\n \"\"\"\n PCA can be implemented either by finding the eigenvectors of the covariance\n matrix or by applying SVD to the centered data matrix. You don't do both\n covariance and SVD. In practice, the SVD approach is preferable because\n the computation of covariance matrix amplifies numerical issues associated\n with poorly conditioned matrices.\n sklearn uses the SVD method, and applies data centering (remove mean) in the\n program\n\n https://stackoverflow.com/questions/47476209/why-does-sklearn-decomposition-pca-fit-transformx-no-multiplication-by-x\n https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/decomposition/pca.py#L432\n :param X:\n :param k:\n :return:\n \"\"\"\n pca2 = decomposition.PCA(n_components=k, svd_solver='full')\n\n # X = X - X.mean(axis=0)\n\n pca2.fit(X)\n print('mean used in pca process:', pca2.mean_)\n print('Coordinates of mean after transform:',\n pca2.transform(np.array([pca2.mean_.tolist()])))\n print('components after mean shift:')\n print(pca2.components_)\n adjust_components = pca2.components_ + pca2.mean_\n print('Coordinates of adjusted components after transform:')\n print(pca2.transform(adjust_components))\n print('Coordinates of eigenvector-like components after transform:')\n print(np.dot(pca2.components_, pca2.components_.T))\n print('Explained variance:', pca2.explained_variance_ratio_)\n\n X_reduced = pca2.transform(X)\n\n return X_reduced\n\n\ndef cal_scatter(func, X, k):\n X_pca = func(X, k)\n X_pca = X_pca.tolist()\n xy = zip(*X_pca)\n return xy\n\n\nif __name__ == '__main__':\n\n XX = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])\n print('mean:', XX.mean(axis=0))\n print('std:', XX.std(axis=0))\n\n iris = load_iris()\n X0 = iris.data\n print('Shape of X0:', X0.shape)\n k0 = 2\n\n x1y1 = cal_scatter(pca, X0, k0)\n x2y2 = cal_scatter(sk_pca, X0, k0)\n\n x1, y1 = x1y1\n x2, y2 = x2y2\n\n print('x1y1:', list(zip(x1, y1)))\n print('x2y2:', list(zip(x2, y2)))\n\n fig = plt.figure(1)\n ax = fig.add_subplot(1, 2, 1)\n ax.scatter(x1, y1, color='blue')\n ax2 = fig.add_subplot(1, 2, 2)\n ax2.scatter(x2, y2, color='red')\n plt.show()\n"} {"blob_id": "d59829e84bd1754ccf5cd9994951ea4ceaaafabd", "repo_name": "Krotonus/Deep-learn-lib", "path": "/fizzbuzz.py", "length_bytes": 1509, "score": 3.859375, "int_score": 4, "content": "# -*- coding: utf-8 -*-\n\"\"\"\nFizzBuzz is the following problem:\n \nFor each of the numbers 1 to 100:\n * if the number is divisible by 3, print \"fizz\"\n * if the number is divisible by 5, print \"buzz\"\n * if the number is divisible by 15, print \"fizzbuzz\"\n * otherwise, just print the number\n\"\"\"\n\nfrom typing import List\n\nimport numpy as np\n\nfrom krodeeplib.nn import NeuralNet\nfrom krodeeplib.train import train\nfrom krodeeplib.layers import Linear, Tanh\nfrom krodeeplib.optim import SGD\n\ndef fizz_buzz_encode(x: int) -> List[int]:\n if x % 15 == 0:\n return [0,0,0,1]\n elif x % 5 == 0:\n return [0,0,1,0]\n elif x % 3 == 0:\n return [0,1,0,0]\n else:\n return [1,0,0,0]\n \ndef binary_encode(x: int) -> List[int]:\n \"\"\"\n 10-digit binary encoding of x\n \"\"\"\n return [x >> i & 1 for i in range(10)]\n\n\ninputs = np.array([\n binary_encode(x) for x in range(101, 1024)])\n \ntargets = np.array([\n fizz_buzz_encode(x) for x in range(101, 1024)])\n \nnet = NeuralNet([Linear(input_size = 10, output_size = 50),\n Tanh(),\n Linear(input_size = 50, output_size = 4)])\n \ntrain(net, inputs, targets, num_epochs = 5000, optimizer = SGD(lr = 0.001))\n\nfor x in range(1, 101):\n predicted = net.forward(binary_encode(x))\n predicted_idx = np.argmax(predicted)\n actual_idx = np.argmax(fizz_buzz_encode(x))\n labels = [str(x), \"fizz\", \"buzz\", \"fizzbuzz\"]\n print(x, labels[predicted_idx], labels[actual_idx])\n\n\n"} {"blob_id": "21b8d29df4ed403797e3eefc1329cbfd990f8bf3", "repo_name": "qinemma/pig", "path": "/pig.py", "length_bytes": 7199, "score": 4.375, "int_score": 4, "content": "import random\nimport string\n\ndef rollDice(numDice):\n \"\"\"\n This function returns the score a player gets in a round by rolling some dice.\n If there is one dice with 1, the score of this round is 1;\n otherwise, the score is the sum of all dice.\n \"\"\"\n totalScore = 0\n for i in range(0, numDice):\n num = random.random()\n score = int(num * 6 + 1)\n totalScore += score\n #we know the score of the round is 1 as soon as we see one dice with 1\n if score == 1:\n return 1\n return totalScore\n \ndef takeTurn(opponentScore, numDice):\n \"\"\"\n This function returns the score a player gets in a round given the score of his/her\n opponent and the number of dice he/she chooses to roll. \n \"\"\"\n tens = opponentScore // 10\n ones = opponentScore - tens * 10\n #if the player chooses to roll zero dice, he/she receives a score of one greater than\n #the greater of the digits of his/her opponent's score\n if numDice == 0: \n return max(ones, tens) + 1\n #if the player chooses to roll non-zero dice, he/she receives a score of actually \n #rolling dice\n else:\n return rollDice(numDice)\n \ndef roll3UnlessCloseToEnd(score, opponentScore, goalScore, remainingTurns = 0):\n \"\"\"\n This function is a strategy for playing the game. The computer player always \n rolls three dice except in two specific cases. If the opponent could win by \n rolling a single six on the next turn and the computer score is less than 70% of \n the goal score, then the computer rolls eight dice. If the computer score is \n greater than 90% of the goal score, then the computer rolls two dice. The \n function returns the number of dice that this player has chosen to roll. \n \"\"\"\n #If the opponent could win by rolling a single six on the next turn and the \n #computer score is less than 70% of the goal score\n if (goalScore - opponentScore <= 6) and (score < 0.7 * goalScore):\n return 8\n #If the computer score is greater than 90% of the goal score\n elif score >= 0.9 * goalScore:\n return 2\n #default choice\n else: return 3\n\ndef humanPlayer(score, opponentScore, goalScore, remainingTurns = 0):\n \"\"\"\n This function lets a human player actually play the game. The function tells the \n human player of current scores and the goal score; then ask for the human player's\n choice. This function returns the number of dice the human player chose to roll.\n \"\"\"\n print(\"Your score is\", score, \", your opponent's score is\", opponentScore, \", and the goal is\", goalScore, \".\")\n numberAsAString = input(\"Enter in the number of dice to roll (0-10):\")\n numberAsAString = int(numberAsAString)\n print(\"You chose\", numberAsAString, \".\")\n return int(numberAsAString)\n \ndef playPig(goalScore, maxRounds, strategy1, strategy2):\n \"\"\"\n This function simulates a game of pig. The game has a goal score of goalScore and \n allows a maximum of maxRounds rounds. Player 1 deploys strategy1 while player 2 \n deploys strategy 2. This function returns 1 if player 1 wins, 0 if they tie, and\n -1 if player 2 wins.\n \"\"\"\n player1Score = 0\n player2Score = 0\n for rounds in range(0, maxRounds):\n player1Score += takeTurn(player2Score, strategy1(player1Score, player2Score, goalScore, maxRounds - rounds))\n #decide if player 1 wins after rolling a dice by achieving goal score\n if player1Score >= goalScore: return 1\n player2Score += takeTurn(player1Score, strategy2(player2Score, player1Score, goalScore, maxRounds - rounds))\n #decide if player 2 wins after rolling a dice by achieving goal score\n if player2Score >= goalScore: return -1\n #decide the result after maximum number of rounds have been played\n if player1Score > player2Score: return 1\n if player1Score == player2Score: return 0\n if player1Score < player2Score: return -1\n \ndef main():\n \"\"\"\n This is the main function. This function simulates an instance of the game. Goal\n score is set to be 100 and a maximun of 20 rounds is allowed. Player 1 is the \n computer player deploying roll3UnlessCloseToEnd and player 2 is a human player.\n This function prints the result of the game.\n \"\"\"\n outcome = playPig(100, 20, roll3UnlessCloseToEnd, humanPlayer)\n if outcome == 1: print(\"Player 1 wins!\")\n if outcome == 0: print(\"Tie!\")\n if outcome == -1: print(\"Player 2 wins!\")\n \ndef averageScoreForDice(numDice, numSimulations):\n \"\"\" This function aims to determine the average score per turn, using between \n\t\t0 and 10 dye.\n\t\tparameters: \n\t\tnumDice - the number of dye thrown each term, between 0 and 10\n\t\tnumSimulations - the number of simulations run, throwing a specific number of dye\n\t\"\"\"\n testingScore = 0\n for i in range(numSimulations + 1):\n testingScore += rollDice(numDice)\n averageScore = testingScore / numSimulations\n return averageScore\n\ndef maximumAverageScoreAction(numSimulations):\n \"\"\"\tThis function uses the function averageScoreForDice to determine which number of \n\t\tdice gives the highest score by comparing the average score produced using\n\t\tdifferent numbers of dye. \n\t\tparameters: \n\t\tnumSimulations - the number of simulations run, throwing a specific number of dye\n\t\"\"\"\n bestNum = 0\n bestScore = -9999\n for num in range(1, 11):\n score = averageScoreForDice(num, numSimulations)\n if score >= bestScore:\n bestNum = num\n bestScore = score\n return bestNum\n\ndef runExperiment(numSimulations, strategy):\n \"\"\" This function compares a specific strategies with computer's strategy using a \n given number of simulations, and the goal score is 100 with 20 round maximun in \n each simulation. It will give the winning rate of the specific strategy.\n\t\"\"\"\n player1Round = 0\n for i in range(numSimulations + 1):\n outcome = playPig(100, 20, strategy, roll3UnlessCloseToEnd)\n if outcome == 1: player1Round += 1\n percentage = (player1Round / numSimulations) * 100\n print(str(percentage) + \"%\")\n \n \ndef bestStrategy(score, opponentScore, goalScore):\n \"\"\" Our best strategy is to go 0 or otherwise 6. Our default is to roll\n six dice but we adjust this based on the opponent score and previous rolls. \n\t\"\"\"\n tens = opponentScore // 10\n ones = opponentScore - tens * 10\n #If we can guarantee to win by roll 0 dice, the strategy goes zero dice.\n if (goalScore - score) <= max(ones, tens) + 1 : return 0\n #According to the function of averageScoreForDice we defined above, the best score is \n #8.7 by 6 dice, so if we can reach that by rolling 0 dice, the strategy goes 0 dice.\n if max(ones, tens) + 1 > 8 : return 0\n #If the opponent is close enough to win the game and we are still far from the goal,\n #it would be better to take a risk by rolling 8 dice.\n if (goalScore - opponentScore <= 6) and (score < 0.7 * goalScore): return 8\n #Other than that, roll 6 dice.\n return 6\n \n\n\n\n \nif __name__ == \"__main__\":\n main()\n"} {"blob_id": "172337e12ff12532349346056f4c7488b3e536c2", "repo_name": "jagadeeshwithu/Data-Structures-and-Algos-Python", "path": "/Arrays/Sudoku2.py", "length_bytes": 1923, "score": 4.125, "int_score": 4, "content": "\"\"\"\nDetermine given input of Sudoku Puzzle is valid or not!\n\nFor e.g.,\n\ngrid = [['.', '.', '.', '.', '2', '.', '.', '9', '.'],\n ['.', '.', '.', '.', '6', '.', '.', '.', '.'],\n ['7', '1', '.', '.', '7', '5', '.', '.', '.'],\n ['.', '7', '.', '.', '.', '.', '.', '.', '.'],\n ['.', '.', '.', '.', '8', '3', '.', '.', '.'],\n ['.', '.', '8', '.', '.', '7', '.', '6', '.'],\n ['.', '.', '.', '.', '.', '2', '.', '.', '.'],\n ['.', '1', '.', '2', '.', '.', '.', '.', '.'],\n ['.', '2', '.', '.', '3', '.', '.', '.', '.']]\n\nthe output should be sudoku2(grid) = False, because there are two '1's in the second column\n\n\"\"\"\n\n\ndef sudoku2(grid):\n return (is_row_valid(grid) and\n is_col_valid(grid) and\n is_square_valid(grid))\n\n\ndef is_row_valid(grid):\n for row in grid:\n if not is_unit_valid(row):\n return False\n return True\n\n\ndef is_col_valid(grid):\n for col in zip(*grid):\n if not is_unit_valid(col):\n return False\n\n return True\n\n\ndef is_square_valid(grid):\n for i in (0, 3, 6):\n for j in (0, 3, 6):\n square = [grid[x][y] for x in range(i, i+3) for y in range(j, j+3)]\n if not is_unit_valid(square):\n return False\n\n return True\n\n\ndef is_unit_valid(unit):\n unit = [i for i in unit if i != '.']\n return len(set(unit)) == len(unit)\n\n\nif __name__ == \"__main__\":\n\n grid = [[\"7\",\".\",\".\",\".\",\"4\",\".\",\".\",\".\",\".\"],\n [\".\",\".\",\".\",\"8\",\"6\",\"5\",\".\",\".\",\".\"],\n [\".\",\"1\",\".\",\"2\",\".\",\".\",\".\",\".\",\".\"],\n [\".\",\".\",\".\",\".\",\".\",\"9\",\".\",\".\",\".\"],\n [\".\",\".\",\".\",\".\",\"5\",\".\",\"5\",\".\",\".\"],\n [\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],\n [\".\",\".\",\".\",\".\",\".\",\".\",\"2\",\".\",\".\"],\n [\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],\n [\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"]]\n\n print(sudoku2(grid))\n"} {"blob_id": "d2c8ecceea672f34cf30585f80af6eac3a28050a", "repo_name": "elieharik/SolutionAlgs", "path": "/pythonSolutions/MinStack.py", "length_bytes": 2390, "score": 3.734375, "int_score": 4, "content": "\"\"\"\nO(1) Time | O(n) Space worst case; 80th percentile Python perf.\n\"\"\"\n\nclass MinWithCount(object):\n def __init__(self, minim, count):\n self.min = minim\n self.count = count\n\n\nclass MinStack(object):\n \"\"\"\n Stack that supports push pop top and retrieves the min in constant time.\n \"\"\"\n\n # define global vars\n minim = None\n count = None\n\n def __init__(self):\n \"\"\"\n initialize your data structure here.\n \"\"\"\n self.stack = []\n self.minStackWithCount = []\n\n\n def push(self, x):\n \"\"\"\n :type x: int\n :rtype: void\n \"\"\"\n self.stack.append(x)\n if self.minStackWithCount: #not empty\n ## if element that you are adding is equal to currentMin\n if x ==self.minStackWithCount[-1].min:\n self.minStackWithCount[-1].count =self.minStackWithCount[-1].count + 1\n elif x list:\r\n \r\n # This problem was asked by Amazon.\r\n\r\n # Given an integer k and a string s, find the length of the longest substring that contains at most k distinct characters.\r\n\r\n # For example, given s = \"abcba\" and k = 2, the longest substring with k distinct characters is \"bcb\".\r\n\r\n l = []\r\n\r\n # Generate all possible substrings in a string\r\n for i in range(len(s)-1):\r\n\r\n for j in range(i, len(s)-1):\r\n\r\n if len(s[i:j+1]) >= k:\r\n\r\n l.append(s[i:j+1])\r\n\r\n # store string as key as unqiue char count as value\r\n dic = {i: len(set(i)) for i in l}\r\n\r\n # store len string as key and string as value of dic, when len of string == k \r\n dic2 = {len(i): i for i in dic if dic[i] == k} \r\n\r\n \r\n return dic2[max(dic2)] #dic2 max index value \r\n\r\n\r\n\r\nres = sub_str(\"araaci\", 2)\r\nprint(res)\r\n"} {"blob_id": "9e1c00ede46a1a4d4476b2c0404a738f0e5d784a", "repo_name": "poweihuang17/epi_python_practice", "path": "/Binary_Search_Tree/binary_tree_14_1.py", "length_bytes": 814, "score": 3.859375, "int_score": 4, "content": "class BSTNode:\n\n\tdef __init__(self, data=None, left=None, right=None):\n\t\tself.data, self.left,self.right= data, left, right\n\n\ndef is_binary_tree_bst(tree, low_range=float('-inf'), high_range=float('inf') ):\n\tif not tree:\n\t\treturn True\n\telif not high_range >= tree.data >= low_range:\n\t\treturn False\t\n\telse:\n\t\treturn is_binary_tree_bst(tree.left, low_range, tree.data) and is_binary_tree_bst(tree.right, tree.data, high_range)\n\n\n\nif __name__ == '__main__':\n\t\n\n\tD=BSTNode(2)\n\tE=BSTNode(5)\n\tC=BSTNode(3, D, E)\n\n\tH=BSTNode(13)\n\tG=BSTNode(17,H)\n\tF=BSTNode(11,None, G)\n\tB=BSTNode(7, C,F)\t\n\t\n\tM=BSTNode(31)\n\tL=BSTNode(29,None, M)\n\n\tN=BSTNode(41)\n\n\tK=BSTNode(37, L, N)\n\n\tJ=BSTNode(23, None, K)\n\n\tP=BSTNode(53)\n\tO=BSTNode(47, None, P)\n\tI=BSTNode(43,J, O)\n\n\tA=BSTNode(19,B,I)\n\n\tprint is_binary_tree_bst(A)\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\n"} {"blob_id": "20d37f22698bb3874e87a06dbcf7b9a28d4bfb40", "repo_name": "hsouporto/Note-Everyday", "path": "/Slides_Note/Stanford_Algorithms/PythonCode/Course2/Week1/scc_test.py", "length_bytes": 3201, "score": 3.796875, "int_score": 4, "content": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Apr 22 11:19:05 2020\r\n\r\n@author: HYJ\r\n1. \u300apython\u7b97\u6cd5\u6559\u7a0b\u300bDay7 - \u83b7\u53d6\u6709\u5411\u56fe\u7684\u6240\u6709\u5f3a\u8fde\u901a\u5206\u91cf\r\nhttps://www.jianshu.com/p/192ae0425917\r\n2. python\uff1a\u5982\u4f55\u5c06txt\u6587\u4ef6\u4e2d\u7684\u6570\u503c\u6570\u636e\u8bfb\u5165\u5230list\u4e2d\r\nhttps://blog.csdn.net/littlle_yan/article/details/79302315\r\n\r\n\u5bf9\u4e8e\u4e3b\u6587\u4ef6\u548ctest4\u4f1a\u62a5\u9519\uff01\r\n\"\"\"\r\n\r\nfrom collections import defaultdict\r\n\r\n#\u83b7\u53d6\u7ffb\u8f6c\u6240\u6709\u8fb9\u7684\u56fe\r\ndef tr(G):\r\n #\u521d\u59cb\u5316\u7ffb\u8f6c\u8fb9\u7684\u56feGT\r\n GT=dict()\r\n for u in G.keys():\r\n GT[u]=GT.get(u,set())\r\n #\u7ffb\u8f6c\u8fb9\r\n for u in G.keys():\r\n for v in G[u]:\r\n GT[v].add(u)\r\n return GT\r\n\r\n#\u83b7\u53d6\u6309\u8282\u70b9\u904d\u5386\u5b8c\u6210\u65f6\u95f4\u9012\u51cf\u6392\u5e8f\u7684\u987a\u5e8f\r\ndef topoSort(G):\r\n res=[]\r\n S=set()\r\n #dfs\u904d\u5386\u56fe\r\n def dfs(G,u):\r\n if u in S:\r\n return\r\n S.add(u)\r\n for v in G[u]:\r\n if v in S:\r\n continue\r\n dfs(G,v)\r\n res.append(u)\r\n #\u68c0\u67e5\u662f\u5426\u6709\u9057\u6f0f\u7684\u8282\u70b9\r\n for u in G.keys():\r\n dfs(G,u)\r\n #\u8fd4\u56de\u62d3\u6251\u6392\u5e8f\u540e\u7684\u8282\u70b9\u5217\u8868\r\n res.reverse()\r\n return res\r\n\r\n#\u901a\u8fc7\u7ed9\u5b9a\u7684\u8d77\u59cb\u8282\u70b9\uff0c\u83b7\u53d6\u5355\u4e2a\u8fde\u901a\u91cf\r\ndef walk(G,s,S=None):\r\n if S is None:\r\n s=set()\r\n Q=[]\r\n P=dict()\r\n Q.append(s)\r\n P[s]=None\r\n while Q:\r\n u=Q.pop()\r\n for v in G[u]:\r\n if v in P.keys() or v in S:\r\n continue\r\n Q.append(v)\r\n P[v]=P.get(v,u)\r\n #\u8fd4\u56de\u5f3a\u8fde\u901a\u56fe\r\n return P\r\n \r\n#G={\r\n# 'a':{'b','c'},\r\n# 'b':{'d','e','i'},\r\n# 'c':{'d'},\r\n# 'd':{'a','h'},\r\n# 'e':{'f'},\r\n# 'f':{'g'},\r\n# 'g':{'e','h'},\r\n# 'h':{'i'},\r\n# 'i':{'h'}\r\n#}\r\n# \u8fd9\u4e2a\u7248\u672c\u4ec5\u5bf9\u4e2a\u4f4d\u6570\u6709\u6548\uff01\r\ndef readGraph2Dict():\r\n graphDist = defaultdict(list)\r\n for line in open(\"./problem8.10test5.txt\"):\r\n #print(line) # \u6837\u5f0f '9 3\\n'\r\n edge = [int(line[0]), int(line[2])]\r\n graphDist[edge[0]].append(edge[1])\r\n return graphDist\r\n# \u53c2\u8003\u8fdb\u884c\u4f18\u5316\uff01\r\n#https://blog.csdn.net/littlle_yan/article/details/79302315\r\ndef readGraph2Dictv2(reverse=False):\r\n graphDist = defaultdict(list)\r\n for line in open(\"./problem8.10test4.txt\"):\r\n# for line in open(\"./SCC.txt\"):\r\n lineSep = line.rstrip().split()\r\n edge = [int(lineSep[0]), int(lineSep[1])]\r\n if reverse:\r\n graphDist[edge[1]].append(edge[0])\r\n else:\r\n graphDist[edge[0]].append(edge[1])\r\n return graphDist\r\n\r\nG = readGraph2Dictv2()\r\nGT = readGraph2Dictv2(reverse=True)\r\n#print(G)\r\n\r\n#\u8bb0\u5f55\u5f3a\u8fde\u901a\u5206\u91cf\u7684\u8282\u70b9\r\nseen=set()\r\n#\u50a8\u5b58\u5f3a\u5f3a\u8fde\u901a\u5206\u91cf\r\nscc=[]\r\n#GT=tr(G)\r\nfor u in topoSort(G):\r\n if u in seen :\r\n continue\r\n C=walk(GT,u,seen)\r\n seen.update(C)\r\n scc.append(sorted(list(C.keys())))\r\n\r\n#print(scc)\r\n\r\ndef top5SCC(scc):\r\n lenList = []\r\n sccLen = len(scc)\r\n for i in range(sccLen):\r\n lenList.append(len(scc[i]))\r\n sortLen = sorted(lenList,reverse=True)\r\n if sccLen >= 5:\r\n return sortLen[:5]\r\n else:\r\n for i in range(5-sccLen):\r\n sortLen.append(0)\r\n return sortLen\r\n \r\n \r\nprint('Top 5 SCC sizes:',top5SCC(scc))\r\n"} {"blob_id": "dd725e8830d3cd45d5b510ea9575ceb2cf6da802", "repo_name": "willianvaneli/algoritmos_de_busca", "path": "/codigo-fonte/src/heapsort.py", "length_bytes": 1549, "score": 3.8125, "int_score": 4, "content": "\n''' o Heap Sort o vetor \u0301e visto como uma \u0301arvore bin \u0301aria, \nonde ordena os elementos a medida que os insere naestrutura. \nO heap(monte) \u0301e gerado e montado no pr \u0301oprio vetor. C\nomparado a outrosalgoritmos de ordena \u0327c \u0303ao possui um bom desempenho \n e bom uso de mem \u0301oria pois n \u0303aonecessita de recurs \u0303ao. Baseado nisso \n sua complexidade tanto no pior, melhor e no m \u0301ediocaso \u0301e de \u0398(nlogn).'''\n\ndef heapsort_pilha(array, stackSize, compare):\n change = False\n i = 0\n while i < stackSize:\n left_node = 2 * i + 1\n right_node = 2 * i + 2\n # verificar se o filho esquerdo da raiz existe e \u00e9 maior que q raiz.\n if ((left_node < stackSize) and (compare(array[i] , array[left_node]) == -1)):\n array[i], array[left_node] = array[left_node], array[i]\n change = True\n # verificar se o filho da direita da raiz existe e \u00e9 maior que q raiz. \n if ((right_node < stackSize) and (compare(array[i] , array[right_node]) == -1)):\n array[i], array[right_node] = array[right_node], array[i]\n change = True\n i +=1\n return change\n\n\ndef heapsort(array, compare):\n arraySize = len(array)\n while arraySize > 1:\n change = True\n \n while change:\n change = heapsort_pilha(array, arraySize, compare)\n \n array[arraySize-1], array[0] = array[0], array[arraySize-1]\n arraySize -=1\n \n return array"} {"blob_id": "c4c3fef12f5b808294be6711c83f5d504ab4cf34", "repo_name": "lauromoura/playground", "path": "/introalgo/sum_bit_array.py", "length_bytes": 2326, "score": 4.15625, "int_score": 4, "content": "\"\"\"Introduction to Algorithms, Third Edition\n\nProblem 2.1-4 - Adding two integer as bit arrays\"\"\"\n\nimport sys\n\ndef add_integers(a, b):\n \"\"\"Adds two integers (arrays of n bits) and returns an array of n+1 bits\"\"\"\n\n # Specs: position [0] is the least significant bit. Position [n-1] is the\n # most significant bit\n\n # Loop invariant: Array of size i+1 with the result of two i bits numbers\n # added\n\n # Loop invariant initialization: The output array is of size 1 with zero,\n # as no numbers have been added\n output = [False]*(len(a) + 1)\n\n for i, (x, y) in enumerate(zip(a, b)):\n # Loop invariant maintenance: If i bits were processed, the loop\n # invariant contains i+1 bits with the current sum. After the loop,\n # the invariant contains i+1+1 contains the sum of i+1 bits\n\n # Table:\n # 0 + 0 + 0 = 0\n # 1 + 0 + 0 = 1\n # 1 + 1 + 0 = 0 (c 1)\n # 1 + 1 + 1 = 1 (c 1)\n\n has_carry = output[i]\n output[i] = (x != y) != has_carry # Double xor\n output[i+1] = (x and y) or ((x or y) and has_carry)\n\n # Loop invariant termination: The output array of size i+1 has the sum of\n # two arrays of i bits\n\n return output\n\ndef fromBitArray(a):\n x = 0;\n\n for i, bit in enumerate(a):\n x += bit * 2**i\n\n return x\n\ndef toBitArray(x, size=10):\n bits = []\n bin_str = bin(x)[2:] # Remote the leading 0b\n\n for i in bin_str[::-1]:\n bits.append(bool(int(i)))\n\n diff = size - len(bits)\n bits += [False] * diff\n\n return bits\n\ndef mergeArraySize(a, b):\n max_len = max(len(a), len(b))\n\n a.append([False]*())\n\ndef main():\n \n one = toBitArray(1, 5)\n two = toBitArray(2, 5)\n three = toBitArray(3, 5)\n five = toBitArray(5, 5)\n eleven = toBitArray(11, 5)\n twelve = toBitArray(12, 5)\n twenty = toBitArray(20, 5)\n twentysix = toBitArray(26, 5)\n seven = toBitArray(7, 5)\n fifteen = toBitArray(15, 5)\n\n print fromBitArray(add_integers(one, one))\n print fromBitArray(add_integers(one, two))\n print fromBitArray(add_integers(two, two))\n print fromBitArray(add_integers(eleven, twelve))\n print fromBitArray(add_integers(twentysix, twenty))\n print fromBitArray(add_integers(seven, fifteen))\n\n\nif __name__ == '__main__':\n main()"} {"blob_id": "eb02acf37384af7615e3754183a35dc4afbcfc56", "repo_name": "thisgeek/MIT6.00", "path": "/ps1b.py", "length_bytes": 1284, "score": 3.90625, "int_score": 4, "content": "#!/usr/bin/python\n\n# Package\nprimes = [2, 3]\n\ndef isInt(x):\n return x % 1 == 0\n\ndef isPrimeByHalf(x):\n assert isInt(x)\n i = x / 2\n while i > 1:\n if x % i == 0:\n return False\n i = i - 1\n return True\n\ndef isPrimeByKnownPrimes(x):\n assert isInt(x)\n for prime in primes:\n if x != prime and x % prime == 0:\n return False\n return True\n\ndef isPrime(x, by=\"byHalf\"):\n if (by == \"byKnownPrimes\"):\n return isPrimeByKnownPrimes(x)\n else:\n return isPrimeByHalf(x)\n\ndef nthPrime(n):\n while len(primes) < n:\n last = primes[-1]\n candidate = last + 2 # Need only try odds\n while not(isPrime(candidate, \"byKnownPrimes\")):\n candidate += 2\n assert isPrime(candidate)\n primes.append(candidate)\n return primes[n - 1]\n\n# Log\nfrom math import log\n\ndef sigmaLnPrimes(n):\n i = primes.index(n) - 1\n return reduce(lambda x, y: log(x) + y, primes[:i])\n\ndef printRatio(n):\n sum = sigmaLnPrimes(n)\n print \"sum: {} | n: {} | ratio: {}\".format(sum, n, sum/n)\n\n# Execute\n\nnthPrime(5000)\nmap(lambda x: printRatio(primes[x]), [\n 10,\n 100,\n 200,\n 300,\n 400,\n 500,\n 600,\n 700,\n 800,\n 900,\n 999,\n 2000,\n 3000,\n 4000,\n 4999\n])\n"} {"blob_id": "05f2f697899c72737afee1d804b0d406d8aef4ee", "repo_name": "brunomatt/ProjectEulerNum34", "path": "/ProjectEulerNum34.py", "length_bytes": 506, "score": 3.828125, "int_score": 4, "content": "# 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.\n#\n# Find the sum of all numbers which are equal to the sum of the factorial of their digits.\n#\n# Note: As 1! = 1 and 2! = 2 are not sums they are not included.\nanswer = 0\n\ndef factorial(int):\n value = 1\n for k in range(1, int + 1):\n value = k * value\n return value\n\nfor i in range(3,99999):\n num = 0\n for digit in str(i):\n num = num + factorial(int(digit))\n if num == i:\n answer += num\n\nprint(answer)\n\n"} {"blob_id": "5df269ae8c469a1f149d1bb3acb058c743b16fea", "repo_name": "anoopiitr/msl_lab_probs", "path": "/sorting_input.py", "length_bytes": 3049, "score": 4.375, "int_score": 4, "content": "\r\ndef swap(input_arr, x, y):\r\n \"\"\"\r\n Swaps two elements of array given the array and indexes of elements\r\n \"\"\"\r\n input_arr[x], input_arr[y] = input_arr[y], input_arr[x]\r\n\r\ndef shift_down_in_heap(input_arr, start_index, end_index):\r\n \"\"\"\r\n This method repairs the input array so that it can become a max heap\r\n @param input_arr: Input list of values\r\n @param start_index: Root index of tree/subtree\r\n @param end_index: End index of tree/subtree\r\n \r\n Returns: None \r\n \"\"\"\r\n root_index_subtree = start_index\r\n while (root_index_subtree * 2 + 1 <= end_index):\r\n child_index = root_index_subtree * 2 + 1\r\n swap_index = root_index_subtree\r\n if(input_arr[swap_index] < input_arr[child_index]):\r\n swap_index = child_index\r\n if child_index + 1 <= end_index and input_arr[swap_index] < input_arr[child_index + 1]:\r\n swap_index = child_index + 1\r\n if swap_index == root_index_subtree:\r\n return\r\n else:\r\n swap(input_arr, root_index_subtree, swap_index)\r\n root_index_subtree = swap_index\r\n \r\n \r\ndef heapify_array(input_arr):\r\n \"\"\"\r\n Creates the max heap out of given list of values with the help of shift_down_in_heap function\r\n \r\n @param input_arr: List of input numbers to be sorted \r\n \r\n Returns: None. Updates the array in place. \r\n \"\"\"\r\n input_len = len(input_arr)\r\n \r\n # Calculating floor((input_len - 2)/2)\r\n # As shifting down is needed only for non leaf elements\r\n start_index = (input_len - 2)//2\r\n \r\n while start_index >= 0 :\r\n shift_down_in_heap(input_arr, start_index, input_len-1)\r\n start_index = start_index - 1\r\n \r\ndef heap_sort(input_arr):\r\n \"\"\"\r\n This function is to sort a list/tuple containing int values using heap sort algorithm\r\n \r\n @param input_arr: list/tuple of integers \r\n Returns: Sorted list of values in ascending order\r\n \"\"\"\r\n input_len = len(input_arr)\r\n \r\n # No need to do anything if list is empty or has 1 element\r\n if not input_arr or input_len == 1:\r\n return input_arr \r\n \r\n # Handling the case where supplied input is a constant tuple (i. e. tuple)\r\n if isinstance(input_arr, tuple):\r\n input_arr = list(input_arr)\r\n\r\n # Creating MAX heap out of input supplied\r\n heapify_array(input_arr)\r\n \r\n end_index = len(input_arr) - 1\r\n while end_index > 0:\r\n # Swapping root(max element to end index of unsorted sub array)\r\n swap(input_arr, 0, end_index)\r\n \r\n # Updating unsorted sub array\r\n end_index = end_index - 1\r\n \r\n # Repairing the heap of unsorted sub array\r\n shift_down_in_heap(input_arr, 0, end_index) \r\n return input_arr\r\n \r\n \r\n \r\nif __name__ == '__main__':\r\n \r\n print heap_sort([])\r\n print heap_sort([5])\r\n print heap_sort([10, 9])\r\n print heap_sort ((5, 3, 2, 4, 6))\r\n print heap_sort(range(10, -11, -1))\r\n \r\n \r\n \r\n \r\n \r\n "} {"blob_id": "94afff6b5cb99503484c985c79dfe9c702389bc3", "repo_name": "HarshPathakhp/RL-M2019", "path": "/A2/q4.py", "length_bytes": 2344, "score": 3.59375, "int_score": 4, "content": "import numpy as np\n\"\"\" \ngrid representation (index)\n 1 2 3 4 5\n 6 7 8 9 10\n11 12 13 14 15\n16 17 18 19 20\n21 22 23 24 25\n\"\"\"\ndef out_of_grid(ij):\n #checks whether an index (i,j) is outside the grid\n if(ij[0] < 0 or ij[0] > 4):\n return True\n if(ij[1] < 0 or ij[1] > 4):\n return True\n return False\n\ndef output_V(A):\n #print A\n for i in range(5):\n for j in range(5):\n print(\"%0.2f\"%(A[i, j]), end = \" \")\n print()\n\nmap_index_to_ij = {}\nmap_ij_to_index = {}\nadjacency = {}\ntemp_count = 1\na = (0,1)\nb = (0,3)\nb_p = (2,3)\na_p = (4,1)\n\n#create adjacency list\nfor i in range(5):\n for j in range(5): \n adjacency[(i, j)] = [(i-1, j), (i, j-1), (i+1, j), (i, j+1)]\n if(i == a[0] and j == a[1]):\n adjacency[(i, j)] = [a_p]\n elif(i == b[0] and j == b[1]):\n adjacency[(i, j)] = [b_p]\n map_index_to_ij[temp_count] = (i, j)\n map_ij_to_index[(i, j)] = temp_count\n temp_count += 1\n\n\"\"\"\nsolving bellman optimality equation using linear programming\nv*(s) = max (p(s',r|s,a)[r + yv*(s')])\nsince each s has 4 actions, we have 4 inequalities for each state\nsince there are 25 states, we have 100 inequalities\nWe now want to minimize sigma(v*(s)) with respect to these inequalities\n\nLet c = e, where e is a vector of all 1's with length 25\nA -> 100 x 25 matrix that will capture the inequalities\nb -> 100 length vector that stores the constants -> r * p(s',r|s,a)\nOptimization -> minimize cx such Ax <= b\nwhere x is what we want to find (25 length vector storing all v(s))\n\"\"\"\ngamma = 0.9\nA = np.zeros((100, 25))\nB = np.zeros(100)\nc = np.ones((25))\ncounter = 0\nfor idx in range(1, 26):\n ij = map_index_to_ij[idx]\n neigh = adjacency[ij]\n for i in range(len(neigh)):\n if(out_of_grid(neigh[i])):\n neigh[i] = ij\n for i in neigh:\n idx2 = map_ij_to_index[i]\n reward = None\n if(i == ij):\n reward = -1\n elif(ij == a):\n reward = 10\n elif(ij == b):\n reward = 5\n else:\n reward = 0\n coef = gamma\n const = -1*reward\n A[counter, idx - 1] += -1\n A[counter, idx2 - 1] += coef\n B[counter] += const\n counter += 1\n \n\nfrom scipy.optimize import linprog\nres = linprog(c, A_ub=A, b_ub=B)\nprint(res)"} {"blob_id": "9da8fefae8cf715d7796e4cafaa07c65c6304115", "repo_name": "avirupdandapat/ALGOPROJECT", "path": "/kthpermutation.py", "length_bytes": 645, "score": 3.625, "int_score": 4, "content": "from math import factorial as fact\nclass Solution:\n # @param A : integer\n # @param B : integer\n # @return a strings\n def getPermutation(self, A, B):\n digits = [str(i) for i in range(1, A + 1)]\n return self.recurse(digits, B - 1)\n\n def recurse(self, digits, k):\n n = len(digits)\n if n == 1:\n return digits[0]\n\n di = int(k / fact(n - 1))\n k2 = int(k % fact(n - 1))\n d = digits[di]\n digits = digits[:di] + digits[di + 1:]\n print(d, digits, k2)\n return d + self.recurse(digits, k2)\n\n\nif __name__ == '__main__':\n print(Solution().getPermutation(3, 4))"} {"blob_id": "a36a06e81672816e45fd24bee6066bc28188420a", "repo_name": "mcxu/code-sandbox", "path": "/PythonSandbox/src/sorting/merge_sort.py", "length_bytes": 1974, "score": 3.796875, "int_score": 4, "content": "'''\nMerge Sort\n'''\n\nfrom utils.number_utils import NumberUtils\n\nclass Prob:\n def mergeSort(self, array):\n if not array or len(array)==1:\n return array\n median = int(len(array)/2)\n left = array[:median]\n right = array[median:]\n #print(\"mergeSort: median:{}, l:{}, r:{}\".format(median,left,right))\n sl = self.mergeSort(left)\n sr = self.mergeSort(right)\n return Prob.mergeArrays(sl,sr)\n \n # merge pre-sorted arrays\n def mergeArrays(self, l,r):\n print(\"merging arrays: l:{}, r:{}\".format(l,r))\n \n out = []\n i = 0\n j = 0\n while(i FeedForward(\n #> (_activations): ModuleList(\n #> (0): ReLU()\n #> (1): ReLU()\n #> )\n #> (_linear_layers): ModuleList(\n #> (0): Linear(in_features=124, out_features=64, bias=True)\n #> (1): Linear(in_features=64, out_features=32, bias=True)\n #> )\n #> (_dropout): ModuleList(\n #> (0): Dropout(p=0.2, inplace=False)\n #> (1): Dropout(p=0.2, inplace=False)\n #> )\n #> )\n ```\n \"\"\"\n\n def __init__(\n self,\n input_dim: int,\n num_layers: int,\n hidden_dims: Union[int, List[int]],\n activations: Union[str, List[str]],\n dropout: Union[float, List[float]] = 0.0,\n ) -> None:\n\n super().__init__()\n if not isinstance(hidden_dims, list):\n hidden_dims = [hidden_dims] * num_layers # type: ignore\n if not isinstance(activations, list):\n activations = [activations] * num_layers # type: ignore\n activations = [activation_from_name(a)() for a in activations]\n if not isinstance(dropout, list):\n dropout = [dropout] * num_layers # type: ignore\n if len(hidden_dims) != num_layers:\n raise ValueError(\n \"len(hidden_dims) (%d) != num_layers (%d)\" % (len(hidden_dims), num_layers)\n )\n if len(activations) != num_layers:\n raise ValueError(\n \"len(activations) (%d) != num_layers (%d)\" % (len(activations), num_layers)\n )\n if len(dropout) != num_layers:\n raise ValueError(\n \"len(dropout) (%d) != num_layers (%d)\" % (len(dropout), num_layers)\n )\n self._activations = torch.nn.ModuleList(activations)\n input_dims = [input_dim] + hidden_dims[:-1]\n linear_layers = []\n for layer_input_dim, layer_output_dim in zip(input_dims, hidden_dims):\n linear_layers.append(torch.nn.Linear(layer_input_dim, layer_output_dim))\n self._linear_layers = torch.nn.ModuleList(linear_layers)\n dropout_layers = [torch.nn.Dropout(p=value) for value in dropout]\n self._dropout = torch.nn.ModuleList(dropout_layers)\n self._output_dim = hidden_dims[-1]\n self.input_dim = input_dim\n\n def get_output_dim(self):\n return self._output_dim\n\n def get_input_dim(self):\n return self.input_dim\n\n def forward(self, inputs: torch.Tensor) -> torch.Tensor:\n\n output = inputs\n for layer, activation, dropout in zip(\n self._linear_layers, self._activations, self._dropout\n ):\n output = dropout(activation(layer(output)))\n return output\n"} {"blob_id": "09f82fabdb858cbce771ca718cd3aac8d2c141e1", "repo_name": "enramir/-Artificial-Intelligence", "path": "/practica-02.py", "length_bytes": 19467, "score": 3.671875, "int_score": 4, "content": "# IA: practica-05.py\n# Clustering (algoritmo k-medias)\n# Dpto. de C. de la Computaci\u00f3n e I.A. (Univ. de Sevilla)\n#=====================================================================\n\nimport math,random \n\n# Esta pr\u00e1ctica tiene dos partes:\n# - En la primera parte vamos a implementar en Python el algoritmo de\n# clustering conocido como de K-medias\n# - En la segunda parte experimentaremos la implementaci\u00f3n sobre un\n# conjunto de datos: el conocido como \"iris\", una base de datos en la\n# que cada instancia refleja una serie de medidas sobre la flor de la\n# planta del iris, junto con una clasificaci\u00f3n sobre el tipo de flor\n\n# ***********************************\n# Parte I: Implementaci\u00f3n de K-medias \n# ***********************************\n\n# El algoritmo de K-medias es un algoritmo de clustering que sirve\n# para clasificar en grupos o clusters una serie de ejemplos (vectores\n# num\u00e9ricos) que constituyen el conjunto de datos de entrada. Adem\u00e1s\n# del conjunto de datos, recibe como entrada el n\u00famero K de clusters\n# de la clasificaci\u00f3n que se pretende hacer.\n\n# B\u00e1sicamente, comienza escogiendo K centros y asignando cada elemento\n# a la clase representada por el centro m\u00e1s cercano. Una vez asignado\n# un cluster a cada ejemplo, la media aritm\u00e9tica de los ejemplos de\n# cada cluster se toma como nuevo centro del cluster. Este proceso de\n# asignaci\u00f3n de clusters y de rec\u00e1lculo de los centros se repite hasta\n# que se cumple alguna condici\u00f3n de terminaci\u00f3n (estabilizaci\u00f3n de los\n# centros, por ejemplo).\n\n# El pseudoc\u00f3digo visto en clase es el siguiente:\n\n# -------------------------------------------------------------------\n# K-MEDIAS(K,DATOS)\n\n# 1. Inicializar c_i (i=1,...,k) (aleatoriamente o con alg\u00fan criterio\n# heur\u00edstico) \n# 2. REPETIR (hasta que los c_i no cambien):\n# 2.1 PARA j=1,...,N, HACER: \n# Calcular el cluster correspondiente a x_j, escogiendo, de entre\n# todos los c_i, el c_h tal que distancia(x_j,c_h) sea m\u00ednima \n# 2.2 PARA i=1,...,k HACER:\n# Asignar a c_i la media aritm\u00e9tica de los datos asignados al\n# cluster i-\u00e9simo \n# 3. Devolver c_1,...,c_k\n# ---------------------------------------------------------------------\n\n\n# Los siguientes ejercicios tienen como objetivo final la implementaci\u00f3n en\n# Python del algoritmo de K-medias. La funci\u00f3n distancia ser\u00e1 un par\u00e1metro de\n# entrada al algoritmo.\n\n# Para hacer pruebas a medida que se van definiendo las funciones,\n# usar el siguiente conjunto de datos, en el que aparecen datos sobre\n# los pesos de una poblaci\u00f3n (en forma de vector unidimensional). Es\n# de suponer que estos datos corresponden a dos grupos (hombres y\n# mujeres), y en principio desconocemos a qu\u00e9 grupo pertenece cada\n# peso. La distancia entre los datos ser\u00e1 simplemente su diferencia en\n# valor absoluto.\n\npesos_poblacion = [[51.0],[43.0],[62.0],[64.0],[45.0],[42.0],[46.0],[45.0],[45.0],[62.0],[47.0],\n\t\t\t\t [52.0],[64.0],[51.0],[65.0],[48.0],[49.0],[46.0],[64.0],[51.0],[52.0],[62.0],\n\t\t\t\t [49.0],[48.0],[62.0],[43.0],[40.0],[48.0],[64.0],[51.0],[63.0],[43.0],[65.0],\n\t\t\t\t [66.0],[65.0],[46.0],[39.0],[62.0],[64.0],[52.0],[63.0],[64.0],[48.0],[64.0],\n\t\t\t\t [48.0],[51.0],[48.0],[64.0],[42.0],[48.0],[41.0]]\n\ndef distancia_abs(x,y):\n return abs(x[0]-y[0])\n\n# ---------------------------------------------------------------\n# Ejercicio 1\n\n# La asignaci\u00f3n de clusters a cada ejemplo durante cada iteraci\u00f3n del\n# algoritmo la almacenaremos en una lista (que llamaremos \"lista de\n# clasificaci\u00f3n\") cuyos elementos son a su vez listas con dos elementos: cada\n# dato concreto y el n\u00famero de cluster que tiene asignado. Para comenzar,\n# definir una funci\u00f3n \"clasificacion_inicial_vacia(datos)\" que recibe un\n# conjunto de datos y crea una lista de clasificaci\u00f3n, en el que el n\u00famero\n# de cluster de cada dato est\u00e1 sin definir.\n#\n# Ejemplo:\n\n# >>> clasificacion_inicial_vacia(pesos_poblacion)\n# [[[51.0], None], [[43.0], None], [[62.0], None], [[64.0], None], \n# [[45.0], None], [[42.0], None], [[46.0], None], [[45.0], None], \n# [[45.0], None], [[62.0], None], [[47.0], None], [[52.0], None], \n# .......]\n\n# ---------------------------------------------------------------\n# ====== Soluci\u00f3n:\n\ndef clasificacion_inicial_vacia(datos):\n\treturn [[x,None] for x in datos]\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# =======\n\n# ---------------------------------------------------------------\n# Ejercicio 2\n# Los centros que se vayan calculando durante el algoritmo los vamos a\n# almacenar en un lista de K componentes (a la que llamaremos \"lista de\n# centros\"). \n\n# Para definir los centros iniciales, vamos a elegir aleatoriamente K\n# ejemplos distintos de entre los datos de entrada. \n# Se pide definir una funci\u00f3n \"centros_iniciales(ejemplos,num_clusters)\"\n# que recibiendo el conjunto de datos de entrada, y el n\u00famero total \n# de clusters, genera una lista inicial de centros.\n\n# Por ejemplo (el resultado puede variar):\n# >>> centros_iniciales(pesos_poblacion,2)\n# [[65.0], [48.0]]\n# ---------------------------------------------------------------\n\n\n\n# Sugerencia: usar la funci\u00f3n random.sample\n\n\n\n\n\n\n\n\n\n\n\n\n\n# ====== Soluci\u00f3n:\n\ndef centros_iniciales(ejemplos,num_clusters):\n return random.sample(ejemplos,num_clusters)\n\n# =======\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n# ---------------------------------------------------------------\n# Ejercicio 3\n\n# Definir una funci\u00f3n \"calcula_centro_mas_cercano(dato,centros,distancia)\"\n# que recibiendo como entrada un dato, una lista de centros de cada cluster y\n# una funci\u00f3n distancia, devuelve el n\u00famero de cluster cuyo centro est\u00e1 m\u00e1s\n# cercano al dato (los clusters los numeraremos de 0 a K-1). \n\n# Por ejemplo:\n\n# >>> calcula_centro_mas_cercano([41.0],[[39.0],[45.0]],distancia_abs)\n# 0\n# >>> calcula_centro_mas_cercano([64.0],[[39.0],[45.0]],distancia_abs)\n# 1\n# -----------------------------------------------------------------\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# ======= Soluci\u00f3n:\n\ndef calcula_centro_mas_cercano(dato,centros,distancia):\n minima_distancia=float(\"infinity\")\n for i,c in enumerate(centros):\n dist=distancia(dato,c)\n if dist < minima_distancia:\n minima_distancia=dist\n min_ind=i\n return min_ind\n \n# ================\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# --------------------------------------------------------------- \n# Ejercicio 4\n\n# Define la funci\u00f3n \"asigna_cluster_a_cada_ejemplo(clasif,centros,distancia)\"\n# que recibiendo una lista de clasificaci\u00f3n \"clasif\" y una lista de centros\n# \"centros\", actualice clasif de manera que en cada dato, el cluster asignado\n# sea el del centro en \"centros\" m\u00e1s cercano al ejemplo.\n\n# Por ejemplo:\n\n# >>> clas=clasificacion_inicial_vacia(pesos_poblacion)\n# >>> centr=[[65.0],[48.0]]\n# >>> asigna_cluster_a_cada_ejemplo(clas,centr,distancia_abs)\n# >>> clas\n# [[[51.0], 1], [[43.0], 1], [[62.0], 0], [[64.0], 0], [[45.0], 1], \n# [[42.0], 1], [[46.0], 1], [[45.0], 1], [[45.0], 1], [[62.0], 0], \n# [[47.0], 1], [[52.0], 1], [[64.0], 0], [[51.0], 1], [[65.0], 0],\n# ...]\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# -----------------------------------------------------------------\n# ====== Soluci\u00f3n:\n\ndef asigna_cluster_a_cada_ejemplo(clasif,centros,distancia):\n for x in clasif:\n x[1]=calcula_centro_mas_cercano(x[0],centros,distancia)\n\n# ===============\n\n\n\n# ---------------------------------------------------------------\n# Ejercicio 5\n\n# Definir una funci\u00f3n \"recalcula_centros(clasif,num_clusters)\" que recibiendo\n# una lista de clasificaci\u00f3n y el n\u00famero total de clusters, devuelve la lista\n# con los nuevos centros calculados como media aritm\u00e9tica de los datos de cada\n# cluster. \n\n# Por ejemplo (si \"clas\" con el valor del ejemplo anterior):\n# >>> recalcula_centros(clas,2)\n# [[63.63157894736842], [46.8125]]\n\n# ====== Soluci\u00f3n:\n\n# Comentario: \n# - Creamos la lista nuevos_centros, formada por k puntos [0,0,...,0]\n# - Para cada d = [Pto, Cluster], sumamos el Pto, i.e. d[0], al valor \n# acumulado del centro de \u00edndice d[1]. De este modo, en la lista\n# que ocupa el lugar i-\u00e9simo de nuevos centros tendremos la suma \n# de todos los puntos que tienen asociado el cluster i. Adem\u00e1s,\n# contamos cu\u00e1ntos hay y lo guargamos en la lista \"num\".\n# - Finalmente dividimos al suma por el n\u00famero de sumandos y obtenemos el valor medio.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ndef recalcula_centros(clasif,k): \n\n def suma_vec(v1,v2):\n return [x+y for (x,y) in zip(v1,v2)]\n\n def div_vec(v,n):\n return [x/n for x in v]\n \n nuevos_centros=[[0]*len(clasif[0][0]) for _ in range(k)] # acumulador, para cada cluster, de\n # la suma (vectorial) de los datos asignados\n # al cluster. Al final dividiremos por\n # el n\u00famero de datos en el cluster\n num=[0]*k # contador del n\u00famero de datos en cada cluster\n for d in clasif:\n nuevos_centros[d[1]]=suma_vec(nuevos_centros[d[1]],d[0])\n num[d[1]]+=1\n for i in range(k):\n nuevos_centros[i]=div_vec(nuevos_centros[i],num[i])\n return nuevos_centros \n# ================\n\n\n\n\n\n\n\n\n\n#------------------------------------------------------------------------------\n# Ejercicio 6\n#------------------------------------------------------------------------------\n\n# Usando las funciones definidas anteriormente, definir la funci\u00f3n \n# \"k-medias(k,datos,distancia)\"\n# que implementa la siguiente versi\u00f3n del algoritmo k-medias:\n# -------------------------------------------------------------------\n\n# -------------------------------------------------------------------\n# K-MEDIAS(K,DATOS, distancia)\n\n# 1. Inicializar c_i (i=1,...,k) (aleatoriamente o con alg\u00fan criterio\n# heur\u00edstico) \n# 2. REPETIR (hasta que los c_i no cambien):\n# 2.1 PARA j=1,...,N, HACER: \n# Calcular el cluster correspondiente a x_j, escogiendo, de entre\n# todos los c_i, el c_h tal que distancia(x_j,c_h) sea m\u00ednima \n# 2.2 PARA i=1,...,k HACER:\n# Asignar a c_i la media aritm\u00e9tica de los datos asignados al\n# cluster i-\u00e9simo \n# 3. Devolver c_1,...,c_k y el cluster asignado a cada dato\n# ---------------------------------------------------------------------\n\n\n \n# El algoritmo debe devolver como salida una tupla con los centros finalmente\n# obtenidos y con la lista de clasificaci\u00f3n.\n\n# Por ejemplo: \n\n# >>> k_medias(2,pesos_poblacion,distancia_abs)\n# [[[46.8125], [63.63157894736842]], \n\n# [[[51.0], 0], [[43.0], 0], [[62.0], 1], [[64.0], 1], [[45.0], 0], \n# [[42.0], 0], [[46.0], 0], [[45.0], 0], [[45.0], 0], [[62.0], 1], \n# [[47.0], 0], [[52.0], 0], [[64.0], 1], [[51.0], 0], [[65.0], 1], \n# ....]]\n\n# -------------------------------------------------------------\n\n# =========Soluci\u00f3n:\n\n\ndef k_medias(k,datos,distancia):\n centros=centros_iniciales(datos,k)\n clasif=clasificacion_inicial_vacia(datos)\n while True:\n asigna_cluster_a_cada_ejemplo(clasif,centros,distancia)\n nuevos_centros=recalcula_centros(clasif,k)\n if nuevos_centros != centros:\n centros=nuevos_centros\n else:\n return [centros,clasif]\n\n\n# ===============\n\n# **************************************************\n# Parte II: experimentaci\u00f3n de k-medias sobre \"iris\"\n# **************************************************\n\n# La siguiente lista \"iris\" contiene uno de los conjuntos de datos m\u00e1s\n# conocido y usado como banco de pruebas en aprendizaje autom\u00e1tico. Se trata\n# de una lista con 150 vectores de datos, cada uno de ellos con cuatro medidas\n# num\u00e9ricas sobre longitud y anchura de s\u00e9palo y p\u00e9talo de la flor de la\n# planta iris. Cada vector tiene asignado una de las tres posibles\n# clasificaciones: setosa, versicolor o virg\u00ednica (que es la quinta\n# componente).\n\niris= \\\n [[5.1,3.5,1.4,0.2,\"Iris setosa\"],\n [4.9,3.0,1.4,0.2,\"Iris setosa\"],\n [4.7,3.2,1.3,0.2,\"Iris setosa\"],\n [4.6,3.1,1.5,0.2,\"Iris setosa\"],\n [5.0,3.6,1.4,0.2,\"Iris setosa\"],\n [5.4,3.9,1.7,0.4,\"Iris setosa\"],\n [4.6,3.4,1.4,0.3,\"Iris setosa\"],\n [5.0,3.4,1.5,0.2,\"Iris setosa\"],\n [4.4,2.9,1.4,0.2,\"Iris setosa\"],\n [4.9,3.1,1.5,0.1,\"Iris setosa\"],\n [5.4,3.7,1.5,0.2,\"Iris setosa\"],\n [4.8,3.4,1.6,0.2,\"Iris setosa\"],\n [4.8,3.0,1.4,0.1,\"Iris setosa\"],\n [4.3,3.0,1.1,0.1,\"Iris setosa\"],\n [5.8,4.0,1.2,0.2,\"Iris setosa\"],\n [5.7,4.4,1.5,0.4,\"Iris setosa\"],\n [5.4,3.9,1.3,0.4,\"Iris setosa\"],\n [5.1,3.5,1.4,0.3,\"Iris setosa\"],\n [5.7,3.8,1.7,0.3,\"Iris setosa\"],\n [5.1,3.8,1.5,0.3,\"Iris setosa\"],\n [5.4,3.4,1.7,0.2,\"Iris setosa\"],\n [5.1,3.7,1.5,0.4,\"Iris setosa\"],\n [4.6,3.6,1.0,0.2,\"Iris setosa\"],\n [5.1,3.3,1.7,0.5,\"Iris setosa\"],\n [4.8,3.4,1.9,0.2,\"Iris setosa\"],\n [5.0,3.0,1.6,0.2,\"Iris setosa\"],\n [5.0,3.4,1.6,0.4,\"Iris setosa\"],\n [5.2,3.5,1.5,0.2,\"Iris setosa\"],\n [5.2,3.4,1.4,0.2,\"Iris setosa\"],\n [4.7,3.2,1.6,0.2,\"Iris setosa\"],\n [4.8,3.1,1.6,0.2,\"Iris setosa\"],\n [5.4,3.4,1.5,0.4,\"Iris setosa\"],\n [5.2,4.1,1.5,0.1,\"Iris setosa\"],\n [5.5,4.2,1.4,0.2,\"Iris setosa\"],\n [4.9,3.1,1.5,0.1,\"Iris setosa\"],\n [5.0,3.2,1.2,0.2,\"Iris setosa\"],\n [5.5,3.5,1.3,0.2,\"Iris setosa\"],\n [4.9,3.1,1.5,0.1,\"Iris setosa\"],\n [4.4,3.0,1.3,0.2,\"Iris setosa\"],\n [5.1,3.4,1.5,0.2,\"Iris setosa\"],\n [5.0,3.5,1.3,0.3,\"Iris setosa\"],\n [4.5,2.3,1.3,0.3,\"Iris setosa\"],\n [4.4,3.2,1.3,0.2,\"Iris setosa\"],\n [5.0,3.5,1.6,0.6,\"Iris setosa\"],\n [5.1,3.8,1.9,0.4,\"Iris setosa\"],\n [4.8,3.0,1.4,0.3,\"Iris setosa\"],\n [5.1,3.8,1.6,0.2,\"Iris setosa\"],\n [4.6,3.2,1.4,0.2,\"Iris setosa\"],\n [5.3,3.7,1.5,0.2,\"Iris setosa\"],\n [5.0,3.3,1.4,0.2,\"Iris setosa\"],\n [7.0,3.2,4.7,1.4,\"Iris versicolor\"],\n [6.4,3.2,4.5,1.5,\"Iris versicolor\"],\n [6.9,3.1,4.9,1.5,\"Iris versicolor\"],\n [5.5,2.3,4.0,1.3,\"Iris versicolor\"],\n [6.5,2.8,4.6,1.5,\"Iris versicolor\"],\n [5.7,2.8,4.5,1.3,\"Iris versicolor\"],\n [6.3,3.3,4.7,1.6,\"Iris versicolor\"],\n [4.9,2.4,3.3,1.0,\"Iris versicolor\"],\n [6.6,2.9,4.6,1.3,\"Iris versicolor\"],\n [5.2,2.7,3.9,1.4,\"Iris versicolor\"],\n [5.0,2.0,3.5,1.0,\"Iris versicolor\"],\n [5.9,3.0,4.2,1.5,\"Iris versicolor\"],\n [6.0,2.2,4.0,1.0,\"Iris versicolor\"],\n [6.1,2.9,4.7,1.4,\"Iris versicolor\"],\n [5.6,2.9,3.6,1.3,\"Iris versicolor\"],\n [6.7,3.1,4.4,1.4,\"Iris versicolor\"],\n [5.6,3.0,4.5,1.5,\"Iris versicolor\"],\n [5.8,2.7,4.1,1.0,\"Iris versicolor\"],\n [6.2,2.2,4.5,1.5,\"Iris versicolor\"],\n [5.6,2.5,3.9,1.1,\"Iris versicolor\"],\n [5.9,3.2,4.8,1.8,\"Iris versicolor\"],\n [6.1,2.8,4.0,1.3,\"Iris versicolor\"],\n [6.3,2.5,4.9,1.5,\"Iris versicolor\"],\n [6.1,2.8,4.7,1.2,\"Iris versicolor\"],\n [6.4,2.9,4.3,1.3,\"Iris versicolor\"],\n [6.6,3.0,4.4,1.4,\"Iris versicolor\"],\n [6.8,2.8,4.8,1.4,\"Iris versicolor\"],\n [6.7,3.0,5.0,1.7,\"Iris versicolor\"],\n [6.0,2.9,4.5,1.5,\"Iris versicolor\"],\n [5.7,2.6,3.5,1.0,\"Iris versicolor\"],\n [5.5,2.4,3.8,1.1,\"Iris versicolor\"],\n [5.5,2.4,3.7,1.0,\"Iris versicolor\"],\n [5.8,2.7,3.9,1.2,\"Iris versicolor\"],\n [6.0,2.7,5.1,1.6,\"Iris versicolor\"],\n [5.4,3.0,4.5,1.5,\"Iris versicolor\"],\n [6.0,3.4,4.5,1.6,\"Iris versicolor\"],\n [6.7,3.1,4.7,1.5,\"Iris versicolor\"],\n [6.3,2.3,4.4,1.3,\"Iris versicolor\"],\n [5.6,3.0,4.1,1.3,\"Iris versicolor\"],\n [5.5,2.5,4.0,1.3,\"Iris versicolor\"],\n [5.5,2.6,4.4,1.2,\"Iris versicolor\"],\n [6.1,3.0,4.6,1.4,\"Iris versicolor\"],\n [5.8,2.6,4.0,1.2,\"Iris versicolor\"],\n [5.0,2.3,3.3,1.0,\"Iris versicolor\"],\n [5.6,2.7,4.2,1.3,\"Iris versicolor\"],\n [5.7,3.0,4.2,1.2,\"Iris versicolor\"],\n [5.7,2.9,4.2,1.3,\"Iris versicolor\"],\n [6.2,2.9,4.3,1.3,\"Iris versicolor\"],\n [5.1,2.5,3.0,1.1,\"Iris versicolor\"],\n [5.7,2.8,4.1,1.3,\"Iris versicolor\"],\n [6.3,3.3,6.0,2.5,\"Iris virg\u00ednica\"],\n [5.8,2.7,5.1,1.9,\"Iris virg\u00ednica\"],\n [7.1,3.0,5.9,2.1,\"Iris virg\u00ednica\"],\n [6.3,2.9,5.6,1.8,\"Iris virg\u00ednica\"],\n [6.5,3.0,5.8,2.2,\"Iris virg\u00ednica\"],\n [7.6,3.0,6.6,2.1,\"Iris virg\u00ednica\"],\n [4.9,2.5,4.5,1.7,\"Iris virg\u00ednica\"],\n [7.3,2.9,6.3,1.8,\"Iris virg\u00ednica\"],\n [6.7,2.5,5.8,1.8,\"Iris virg\u00ednica\"],\n [7.2,3.6,6.1,2.5,\"Iris virg\u00ednica\"],\n [6.5,3.2,5.1,2.0,\"Iris virg\u00ednica\"],\n [6.4,2.7,5.3,1.9,\"Iris virg\u00ednica\"],\n [6.8,3.0,5.5,2.1,\"Iris virg\u00ednica\"],\n [5.7,2.5,5.0,2.0,\"Iris virg\u00ednica\"],\n [5.8,2.8,5.1,2.4,\"Iris virg\u00ednica\"],\n [6.4,3.2,5.3,2.3,\"Iris virg\u00ednica\"],\n [6.5,3.0,5.5,1.8,\"Iris virg\u00ednica\"],\n [7.7,3.8,6.7,2.2,\"Iris virg\u00ednica\"],\n [7.7,2.6,6.9,2.3,\"Iris virg\u00ednica\"],\n [6.0,2.2,5.0,1.5,\"Iris virg\u00ednica\"],\n [6.9,3.2,5.7,2.3,\"Iris virg\u00ednica\"],\n [5.6,2.8,4.9,2.0,\"Iris virg\u00ednica\"],\n [7.7,2.8,6.7,2.0,\"Iris virg\u00ednica\"],\n [6.3,2.7,4.9,1.8,\"Iris virg\u00ednica\"],\n [6.7,3.3,5.7,2.1,\"Iris virg\u00ednica\"],\n [7.2,3.2,6.0,1.8,\"Iris virg\u00ednica\"],\n [6.2,2.8,4.8,1.8,\"Iris virg\u00ednica\"],\n [6.1,3.0,4.9,1.8,\"Iris virg\u00ednica\"],\n [6.4,2.8,5.6,2.1,\"Iris virg\u00ednica\"],\n [7.2,3.0,5.8,1.6,\"Iris virg\u00ednica\"],\n [7.4,2.8,6.1,1.9,\"Iris virg\u00ednica\"],\n [7.9,3.8,6.4,2.0,\"Iris virg\u00ednica\"],\n [6.4,2.8,5.6,2.2,\"Iris virg\u00ednica\"],\n [6.3,2.8,5.1,1.5,\"Iris virg\u00ednica\"],\n [6.1,2.6,5.6,1.4,\"Iris virg\u00ednica\"],\n [7.7,3.0,6.1,2.3,\"Iris virg\u00ednica\"],\n [6.3,3.4,5.6,2.4,\"Iris virg\u00ednica\"],\n [6.4,3.1,5.5,1.8,\"Iris virg\u00ednica\"],\n [6.0,3.0,4.8,1.8,\"Iris virg\u00ednica\"],\n [6.9,3.1,5.4,2.1,\"Iris virg\u00ednica\"],\n [6.7,3.1,5.6,2.4,\"Iris virg\u00ednica\"],\n [6.9,3.1,5.1,2.3,\"Iris virg\u00ednica\"],\n [5.8,2.7,5.1,1.9,\"Iris virg\u00ednica\"],\n [6.8,3.2,5.9,2.3,\"Iris virg\u00ednica\"],\n [6.7,3.3,5.7,2.5,\"Iris virg\u00ednica\"],\n [6.7,3.0,5.2,2.3,\"Iris virg\u00ednica\"],\n [6.3,2.5,5.0,1.9,\"Iris virg\u00ednica\"],\n [6.5,3.0,5.2,2.0,\"Iris virg\u00ednica\"],\n [6.2,3.4,5.4,2.3,\"Iris virg\u00ednica\"],\n [5.9,3.0,5.1,1.8,\"Iris virg\u00ednica\"]]\n\n# ---------------------------------------------------------------\n# Ejercicio 7\n\n# La siguiente funci\u00f3n nos permite validar una clasificaci\u00f3n cualquiera de los\n# 150 vectores num\u00e9ricos de la lista iris, compar\u00e1ndola con la clasificaci\u00f3n\n# original que aparece en la base de datos. Para cada una de las tres\n# clasificaciones originales, cuenta cuantos ejemplos hay en cada uno de los\n# clusters asignados en la clasificaci\u00f3n que se le pasa como argumento de\n# entrada.\n\n\ndef validacion_iris(clasificacion):\n posibles_valores=[\"Iris setosa\", \"Iris versicolor\", \"Iris virg\u00ednica\"]\n contadores=dict()\n for val in posibles_valores:\n for x in range(3):\n contadores[val,x]=0\n for i in range(len(clasificacion)):\n contadores[iris[i][4],clasificacion[i][1]]+=1\n for val in posibles_valores:\n print(val+\"\\n\"+\"==============\\n\")\n for x in range(3):\n print(\"Cluster \",x,\": \",contadores[val,x])\n print(\"\\n\\n\")\n\n# Se pide:\n# - Obtener, a partir de los datos de iris la lista de vectores\n# num\u00e9ricos, SIN el tipo de iris.\n# - Aplicar el algoritmo de k-medias a esos datos (con la distancia eucl\u00eddea)\n# - Validar la clasificaci\u00f3n obtenida respecto de la clasificaci\u00f3n\n# original\n\n# ======== Soluci\u00f3n:\n\n\ndef distancia_euclidea(v,w):\n return math.sqrt(sum((vi-wi)**2 for (vi,wi) in zip(v,w)))\n\n# Sesi\u00f3n: \n\n\n# >>> iris_sin_clasificar=[x[:-1] for x in iris]\n# >>> iris_k_medias=k_medias(3,iris_sin_clasificar,distancia_euclidea)[1]\n# >>> validacion_iris(iris_k_medias)\n# Iris setosa\n# ==============\n\n# Cluster 0 : 50\n# Cluster 1 : 0\n# Cluster 2 : 0\n\n\n\n# Iris versicolor\n# ==============\n\n# Cluster 0 : 0\n# Cluster 1 : 48\n# Cluster 2 : 2\n\n\n\n# Iris virg\u00ednica\n# ==============\n\n# Cluster 0 : 0\n# Cluster 1 : 14\n# Cluster 2 : 36\n\n\n\n\n\n# Comentarios: como se observa, el cluster 0 ha sido reconocido\n# completamente como el cluster original de iris setosa. El cluster 1\n# casi al completo (excepto 2 ejemplos del 2) ha reconocido a iris\n# versicolor. Sin embargo ha incluido tambi\u00e9n 14 ejemplos de iris\n# virginica. El resto de iris virginica se ha asignado al cluster 2.\n \n# Los resultados son bastante aceptables, aunque el algoritmo EM los mejora\n# un poco. \n\n# ============ \n \n\n"} {"blob_id": "bdce43e8bfe9a0264b0a258672e6d0d406767f83", "repo_name": "Michael5531/COMP2123", "path": "/Assignement/ASM2/tree.py", "length_bytes": 3906, "score": 4.28125, "int_score": 4, "content": "\"\"\"\r\nTree\r\n-------\r\n\r\nThis is the tree file, it holds the main data structure that will be used for\r\ntesting. The tree contains a root node which then has children until the\r\nleaves.\r\nThis is the main file for the interaction of tests.\r\n\r\nYour task is to implement the methods for put and flatten.\r\n\"\"\"\r\n\r\nimport node\r\n\r\nclass Tree:\r\n \"\"\"\r\n Tree Class\r\n Holds nodes, where each node in the tree has children, unless it is a leaf,\r\n where it has 0 children.\r\n\r\n Each node in the tree is type defined in `node.py`.\r\n\r\n - Init: Sets up the tree with the specified root node.\r\n - put(node, child): Adds the child node to the specified node in the tree.\r\n - flatten(node): flatten the node.\r\n - swap(subtree_a, subtree_b): Swap the position of the subtrees.\r\n \"\"\"\r\n\r\n def __init__(self, root):\r\n \"\"\"\r\n Initialises the tree with a root node.\r\n :param root: the root node.\r\n \"\"\"\r\n self.root = root\r\n\r\n def put(self, node, child):\r\n \"\"\"\r\n Inserts a node into the tree. Adds `child` to `node`.\r\n :param node: The node currently in the tree.\r\n :param child: The child to add to the tree.\r\n \"\"\"\r\n node.add_child(child)\r\n\r\n def flatten(self, node):\r\n \"\"\"\r\n Flatten the node given by removing the subtree rooted at this node.\r\n You must (a) flatten the subtree, (b) compute the sum of all nodes\r\n below and perform any updates\r\n to other nodes.\r\n\r\n :param node: The root of the subtree to flatten.\r\n\r\n Example\r\n\r\n A(5)\r\n / \\\r\n B(3) C(6)\r\n / | \\\r\n D(2) E(3) F(6)\r\n flatten(C)\r\n\r\n A(5)\r\n / \\\r\n B(3) C(15)\r\n /\r\n D(2)\r\n \"\"\"\r\n self.sum_calc(node)\r\n node.subtree_value = node.key # sum_calc\r\n node.children = []\r\n node.post_order()\r\n\r\n def sum_calc(self, node):\r\n if not node.is_external():\r\n count = 0\r\n for i in node.children:\r\n self.sum_calc(i) # is_external return true\r\n count += i.key\r\n node.key += count\r\n else:\r\n return node.key\r\n\r\n def swap(self, subtree_a, subtree_b):\r\n temp_a_parent = subtree_a.parent\r\n temp_b_parent = subtree_b.parent # Set up temp parent\r\n temp_b_parent.children.remove(subtree_b) # Disconnect to parent\r\n temp_a_parent.children.remove(subtree_a)\r\n subtree_a.parent = temp_b_parent\r\n subtree_b.parent = temp_a_parent\r\n temp_b_parent.children.append(subtree_a)\r\n temp_a_parent.children.append(subtree_b)\r\n current_node = subtree_a\r\n while current_node.parent is not None:\r\n self.swap_calc(current_node)\r\n current_node = current_node.parent\r\n current_node = subtree_b\r\n while current_node.parent is not None:\r\n self.swap_calc(current_node)\r\n current_node = current_node.parent\r\n\r\n def swap_calc(self, node):\r\n temp = 0\r\n node.parent.subtree_value = node.parent.key # re assign parent subtree_value to node.parent.key\r\n if node.subtree_value > node.parent.subtree_value:\r\n temp = node.subtree_value\r\n else:\r\n temp = node.parent.subtree_value\r\n for i in node.parent.children:\r\n if i.subtree_value > temp:\r\n temp = i.subtree_value\r\n node.parent.subtree_value = temp\r\n\r\n\r\n\r\n \"\"\"\r\n Swap subtree A with subtree B\r\n :param subtree_a: The root node of subtree_a.\r\n :param subtree_b: The root node of subtree_b.\r\n\r\n Example:\r\n\r\n A\r\n / \\\r\n B C\r\n / / \\\r\n D J K\r\n\r\n SWAP(B, C)\r\n A\r\n / \\\r\n C B\r\n / | \\\r\n J K D\r\n \"\"\"\r\n\r\n"} {"blob_id": "99346902d82a94c423c5f4572cc72414c18f68fb", "repo_name": "Yucheng7713/CodingPracticeByYuch", "path": "/Easy/427_constructQuadTree.py", "length_bytes": 1178, "score": 3.625, "int_score": 4, "content": "\n# Definition for a QuadTree node.\nclass Node:\n def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight):\n self.val = val\n self.isLeaf = isLeaf\n self.topLeft = topLeft\n self.topRight = topRight\n self.bottomLeft = bottomLeft\n self.bottomRight = bottomRight\n\nclass Solution:\n def isLeaf(self, grid):\n N = len(grid)\n return all(grid[0][0] == grid[i][j] for i in range(N) for j in range(N))\n def construct(self, grid) -> 'Node':\n if not grid: return None\n if self.isLeaf(grid):\n return Node(grid[0][0], True, None, None, None, None)\n n = len(grid) // 2\n tL = self.construct([row[:n] for row in grid[:n]])\n tR = self.construct([row[n:] for row in grid[:n]])\n bL = self.construct([row[:n] for row in grid[n:]])\n bR = self.construct([row[n:] for row in grid[n:]])\n root = Node('*', False, tL, tR, bL, bR)\n return root\n\ngrid = [[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0]]\nn = len(grid) // 2\nprint([row[:n] for row in grid[:n]])"} {"blob_id": "cec091fd1504e6362afe03dfd4f4c944c62097d1", "repo_name": "mfsalama/Homework", "path": "/drift.py", "length_bytes": 2073, "score": 4.34375, "int_score": 4, "content": "\n# coding: utf-8\n\n# # Part 3:\n\n# In[1]:\n\n#We start by importing scipy , which we will use to draw random numbers,and we write the first function, generating a population\nimport scipy # for random numbers\ndef build_population(N, p):\n \"\"\"The population consists of N individuals.\n Each individual has two chromosomes, containing\n allele \"A\" or \"a\", with probability p and 1-p,\n respectively.\n \n The population is a list of tuples.\n \"\"\"\n population = []\n for i in range(N):\n allele1 = \"A\"\n if scipy.random.rand() > p:\n allele1 = \"a\"\n allele2 = \"A\"\n if scipy.random.rand() > p:\n allele2 = \"a\"\n population.append((allele1, allele2))\n return population\n\n\n# In[2]:\n\n#build_population(10, 0.7)\n\n\n# In[3]:\n\n#Now we write the second function, which is used to produce a genotype count for the population:\ndef compute_frequencies(population):\n \"\"\" Count the genotypes.\n Returns a dictionary with counts for each genotype.\n \"\"\"\n AA = population.count(( 'A', 'A'))\n Aa = population.count(('A', 'a'))\n aA = population.count(('a', 'A'))\n aa = population.count(('a', 'a'))\n return({'AA': AA,\n 'aa': aa,\n 'Aa': Aa,\n 'aA': aA})\n\n\n# In[4]:\n\n#my_pop = build_population(6, 0.5)\n#my_pop\n\n#compute_frequencies(my_pop)\n\n\n# In[5]:\n\ndef reproduce_population(population):\n \"\"\" Create a new generation through sexual reproduction\n For each of N new offspring:\n - Choose the parents at random\n - The offspring receives a chromosomes from each of\n the parents\n \"\"\"\n new_generation = []\n N = len(population)\n for i in range(N):\n dad = scipy.random.randint(N) # random integerbetween 0 and N-1\n mom = scipy.random.randint(N)\n chr_mom = scipy.random.randint(2) # which chromosome comes from mom\n offspring = (population[mom][chr_mom], population[\n dad][1 - chr_mom])\n new_generation.append(offspring)\n return(new_generation)\n\n\n# In[ ]:\n\n#reproduce_population(my_pop)\n\n"} {"blob_id": "e84e2d173f47640823fc842ccd9111642c5c9d76", "repo_name": "heongbin/algolithm", "path": "/\uc0ac\uce59 \uc5f0\uc0b0 \uc720\ud6a8\uc131.py", "length_bytes": 1727, "score": 3.5625, "int_score": 4, "content": "class Node:\n def __init__(self,idx):\n self.idx=idx\n self.value=\"\"\n self.left=None\n self.right=None\n\n\n\ndef post_order(index):\n if nodelist[index].left==None and nodelist[index].right==None: #\uc22b\uc790\uc784.\n q.append(nodelist[index].value)\n\n\n\n else:\n post_order(nodelist[index].left)\n post_order(nodelist[index].right)\n q.append(nodelist[index].value)\n\n\n\n\n\n\n\ndef calculate():\n while q:\n curr=q.pop(0)\n if curr in op:\n if curr==\"+\":\n a=number.pop()\n b=number.pop()\n tmp=b+a\n number.append(tmp)\n\n elif curr==\"-\":\n a = number.pop()\n b = number.pop()\n tmp = b-a\n number.append(tmp)\n\n\n elif curr==\"/\":\n a = number.pop()\n b = number.pop()\n tmp = b//a\n number.append(tmp)\n\n else:\n a = number.pop()\n b = number.pop()\n tmp = b*a\n number.append(tmp)\n\n else: #\uc22b\uc790\ub77c\uba74\n number.append(int(curr))\n\n\n return number[0]\n\n\n\n\n\n\n\nfor test_case in range(1,11):\n number=[]\n q=[]\n op=[\"+\",\"-\",\"*\",\"/\"]\n\n n=int(input())\n nodelist=[Node(i) for i in range(n+1)]\n\n for i in range(1,n+1):\n tmp=list(input().split())\n if tmp[1]==\"+\" or tmp[1]==\"-\" or tmp[1]==\"*\" or tmp[1]==\"/\":\n nodelist[i].value=tmp[1]\n nodelist[i].left=int(tmp[2])\n nodelist[i].right=int(tmp[3])\n\n else:\n nodelist[i].value=tmp[1]\n\n\n\n\n\n\n\n\n\n post_order(1)\n print(\"#{} {}\".format(test_case,calculate()))\n\n\n\n\n\n\n\n\n\n\n"} {"blob_id": "4d6452d481a0d4a6bb7f3663a66470a9765c7fe6", "repo_name": "grumble1965/advent2018", "path": "/d11-1.py", "length_bytes": 1202, "score": 3.546875, "int_score": 4, "content": "#!/usr/bin/python3\n\nprint('Hello advent - Day 11 - Problem 1')\n\ndef calcPowerLevel(x, y, serial):\n\trackID = x + 10\n\tpl = rackID * y\n\tpl += serial\n\tpl *= rackID\n\tpl = (pl // 100) % 10\n\tpl -= 5\n\treturn pl\n\n# testing\nprint('Power level @( 3, 5) # 8:', calcPowerLevel(3, 5, 8))\nprint('Power level @(122, 79) #57:', calcPowerLevel(122, 79, 57))\nprint('Power level @(217, 196) #39:', calcPowerLevel(217, 196, 39))\nprint('Power level @(101, 153) #71:', calcPowerLevel(101, 153, 71))\n\n# fill in grid values\ngrid = [[0 for _ in range(300)] for _ in range(300)]\nserial = 8561\nfor y in range(1, 300):\n\tfor x in range(1, 300):\n\t\tgrid[y-1][x-1] = calcPowerLevel(x, y, serial)\n\n# compute 3x3 grid sums\nsums = [[0 for _ in range(297)] for _ in range(297)]\nfor y in range(1, 297):\n\tfor x in range(1, 297):\n\t\ts = grid[y-1][x-1] + grid[y-1][x] + grid[y-1][x+1] + grid[y][x-1] + grid[y][x] + grid[y][x+1] + grid[y+1][x-1] + grid[y+1][x] + grid[y+1][x+1]\n\t\tsums[y-1][x-1] = s\n\n# find maximum sum\nmaxsum, mx, my = float('-inf'), -1, -1\nfor y in range(1, 297):\n\tfor x in range(1, 297):\n\t\tif sums[y-1][x-1] > maxsum:\n\t\t\tmaxsum, mx, my = sums[y-1][x-1], x, y\n\t\t\t\n\nprint('max sum =', maxsum,'at (', mx, ',', my, ')')\n"} {"blob_id": "eeb2474b129b8f24e3e32073ad2c067ba9fd8794", "repo_name": "austinsonger/CodingChallenges", "path": "/Hackerrank/_Contests/Project_Euler/Python/pe188.py", "length_bytes": 994, "score": 3.8125, "int_score": 4, "content": "'''\nThe hyperexponentiation of a number\nProblem 188\nThe hyperexponentiation or tetration of a number a by a positive integer b,\ndenoted by a\u2191\u2191b or ba, is recursively defined by:\n\na\u2191\u21911 = a,\na\u2191\u2191(k+1) = a(a\u2191\u2191k).\n\nThus we have e.g. 3\u2191\u21912 = 33 = 27, hence 3\u2191\u21913 = 327 = 7625597484987 and 3\u2191\u21914 is\nroughly 103.6383346400240996*10^12.\n\nFind the last 8 digits of 1777\u2191\u21911855.\n'''\n\n__date__ = '14-3-1'\n__author__ = 'SUN'\n\ndef pow_mod_recursive(a, x, mod):\n if x == 0 or x == 1:\n return a ** x % mod\n elif x % 2 == 0:\n return pow_mod_recursive(a, x // 2, mod) ** 2 % mod\n else:\n return a * pow_mod_recursive(a, x // 2, mod) ** 2 % mod\n\ndef pow_mod(a, x, mod):\n pow_value = 1\n while x > 0:\n if x & 1 == 1:\n pow_value = pow_value * a % mod\n a = a ** 2 % mod\n x >>= 1\n return pow_value\n\nif __name__ == '__main__':\n res = 1\n for i in range(1855):\n res = pow_mod(1777, res, 10 ** 8)\n print(res)"} {"blob_id": "6f8efae2ada6885524ee5c33fffbce474fb95cb3", "repo_name": "boonchu/python3lab", "path": "/coursera.org/python3/quiz/homework4/quiz4-3.py", "length_bytes": 1346, "score": 3.890625, "int_score": 4, "content": "#! /usr/bin/env python\n\nfrom sequence import *\n\ndef seq_size(outcomes):\n return math.log(outcomes)/math.log(2)\n\ndef is_in_seq(nums):\n ranges = sum((list(t) for t in zip(nums, nums[1:]) if t[0]+1 != t[1]), [])\n return len(ranges) == 0\n\ndef sequence_trials():\n '''\n Given a trial in which a decimal digit is selected from the list\n [\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\"] with equal\n probability 0.1, consider a five-digit string created by a\n sequence of such trials (leading zeros and repeated digits are allowed).\n \n What is the probability that this five-digit string consists of five\n consecutive digits in either ascending or descending order (e.g; \"34567\" or \"43210\") ?\n\n Enter your answer as a floating point number with at least\n four significant digits of precision.\n '''\n outcomes = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)\n state = gen_all_sequences(outcomes, 5)\n product = 0\n\n print \"[DEBUG] state => %s size => %s\" % (state, len(state))\n \n count=0.0\n for item in state:\n if is_in_seq(item):\n print \"item is %s or %s\" % (str(item), str(tuple(reversed(item))))\n count += 2.0\n\n print \"length of state => %s\" % len(state)\n print \"count is %s\" % str(count)\n\n return float(count/len(state))\n\nprint 'Question 4 answer:', sequence_trials()\n"} {"blob_id": "3d7af146cd826a936ab7da034557046b437f4cf5", "repo_name": "ricwtk/result-ai-a1-202104", "path": "/players/Group02Player1/player.py", "length_bytes": 9254, "score": 3.59375, "int_score": 4, "content": "import random\n#list out of range. need try catch\n# Node class. Represents a coordinate.\n\nclass Node:\n \n def __init__(self, x, y, parent = None):\n\n \t# Coordinates of the node\n self.x = x\n self.y = y\n\n # Parent of the node. The node that the snake came from to reach current node\n self.parent = parent\n\n # List of children of the node. The nodes the snake can get to from current node\n self.children = []\n\n# Returns the children of the given node. m and n are the dimensions of the grid\ndef expandAndReturnChildren(node, m, n):\n dx = [0, 0, 1, -1]\n dy = [1, -1, 0, 0]\n children = []\n for i in range(4):\n\n \t# (x, y) represent all possible places the snake can go\n \tx = node.x+dx[i]\n \ty = node.y+dy[i]\n\n \t# The parent of the node cannot be its child\n \tif (node.parent is not None and node.parent.x == x and node.parent.y == y):\n \t\tcontinue\n\n \t# If node falls off the grid, ignore it\n \tif (x < 0 or y < 0 or x >= m or y >= n):\n \t\tcontinue\n\n \t# Add the node to the children array\n \tchildren.append(Node(x, y, node))\n\n return children\n\nclass Player():\n name = \"A*Player\"\n group = \"Four Stooges\"\n members = [\n [\"Amrita Menon\", \"17029596\"],\n [\"Marcus Teow\", \"19024371\"],\n [\"Muhammad Hafiz\", \"16027344\"],\n [\"Liew Tze Chen\", \"18032730\"]\n ]\n informed = True\n\n def __init__(self, setup):\n # setup = {\n # maze_size: [int, int],\n # static_snake_length: bool\n # }\n self.setup = setup\n\n def func(self, problem):\n\n \t# Source and destination coordinates\n src = problem[\"snake_locations\"][0]\n dest = problem[\"food_locations\"][0]\n \n # Frontier is our BFS queue\n frontier = []\n\n # Explored contains the visited nodes\n explored = []\n\n # Final solution\n solution = []\n\n # Final search tree\n search_tree = []\n\n # When we reach our destination, found_goal will become True\n found_goal = False\n\n # Destination node\n goalie = Node(dest[0], dest[1])\n\n # Adding source node to frontier queue\n frontier.append(Node(src[0], src[1]))\n\n # cnt is used for ids of the search_tree nodes\n cnt = 1\n\n # Source node for our search tree\n d = {}\n\n # Setting parameters\n d[\"id\"] = cnt\n cnt = cnt+1\n d[\"state\"] = str(frontier[0].x)+\",\"+str(frontier[0].y)\n d[\"coor\"] = [frontier[0].x, frontier[0].y]\n d[\"parent\"] = None\n d[\"actions\"] = []\n d[\"removed\"] = False\n d[\"children\"] = []\n d[\"expansionsequence\"] = 1\n\n # Adding dict entry to search_tree\n search_tree.append(d)\n\n while not found_goal:\n # Break out of loop when no nodes in frontier\n \ttry:\n frontier[0]\n \texcept:\n break\n \n \t# Children of the top node in BFS queue(frontier[0])\n \tchildren = expandAndReturnChildren(frontier[0], self.setup[\"maze_size\"][0], self.setup[\"maze_size\"][1])\n\n \t# A* implementation. Sorts children based on Manhattan distance. Remove this line to convert algo to normal BFS\n \tchildren = sorted(children, key = lambda p: abs(p.x-dest[0])+abs(p.y-dest[1]))\n\n \t# Finding top node in BFS queue in search tree\n \tfor node in search_tree:\n \t\tif (node[\"coor\"] == [frontier[0].x, frontier[0].y]):\n \t\t\t# dc is now the dictionary entry for the parent of the nodes in children array\n \t\t\tdc = node\n \t\t\tbreak\n \tfor node in search_tree:\n \t\tif (frontier[0].parent is not None and node[\"coor\"] == [frontier[0].parent.x, frontier[0].parent.y]):\n \t\t\t# Since we are currently expanding frontier[0], its expansion sequence will be 1 more than that of its parent\n \t\t\tdc[\"expansionsequence\"] = node[\"expansionsequence\"]+1\n \t\t\tbreak\n\n \t# This loop creates the search tree\n \tfor child in children:\n \t\t# For each child, we create a dict entry and add it to the search_tree\n \t\td = {}\n \t\td[\"id\"] = cnt\n \t\tcnt = cnt+1\n \t\td[\"state\"] = str(child.x)+\",\"+str(child.y)\n \t\td[\"coor\"] = [child.x, child.y]\n \t\td[\"children\"] = []\n \t\td[\"actions\"] = []\n \t\td[\"parent\"] = dc[\"id\"]\n \t\td[\"expansionsequence\"] = -1\n\n \t\t# dc is the parent dict element. So we need to add current child id in its children array\n \t\tdc[\"children\"].append(d[\"id\"])\n\n \t\t# The code below fills up the action array of the parent node\n \t\tdiffx = child.x-frontier[0].x\n \t\tdiffy = child.y-frontier[0].y\n \t\tif diffx == 0 and diffy == -1:\n \t\t\tdc[\"actions\"].append(\"n\")\n \t\telif diffx == 0 and diffy == 1:\n \t\t\tdc[\"actions\"].append(\"s\")\n \t\telif diffx == 1 and diffy == 0:\n \t\t\tdc[\"actions\"].append(\"e\")\n \t\telif diffx == -1 and diffy == 0:\n \t\t\tdc[\"actions\"].append(\"w\")\n\n \t\t# If child is explored or currently in BFS queue or is a part of the snake's body, then that node can't be expanded further. So its removed value is True\n \t\tif ([child.x, child.y] in [[e.x, e.y] for e in explored]) or ([child.x, child.y] in [[f.x, f.y] for f in frontier]) or [child.x, child.y] in problem[\"snake_locations\"]:\n \t\t\td[\"removed\"] = True\n\n \t\t# Adding the dictionary element we created to the search_tree\n \t\tsearch_tree.append(d)\n\n \t# Normal BFS algo continues after finding search_tree\n\n \t# First node is popped and inserted into the explored array\n \texplored.append(frontier[0])\n \tdel frontier[0]\n\n \t# Only those children that are neither explored nor in the frontier queue and not part of the snake's body must be pushed to the frontier queue\n \tfor child in children:\n \t\tif not ([child.x, child.y] in [[e.x, e.y] for e in explored]) and not ([child.x, child.y] in [[f.x, f.y] for f in frontier]) and [child.x, child.y] not in problem[\"snake_locations\"]:\n \t\t\t\n \t\t\t# If the child node is our destination\n \t\t\tif child.x == dest[0] and child.y == dest[1]:\n \t\t\t\tfound_goal = True\n \t\t\t\tgoalie = child\n \t\t\tfrontier.append(child)\n\n\n final_path = [goalie]\n while goalie.parent is not None:\n\n \t# Keep adding the parent to the front of the array till the node has no parent. This would give us the final path\n \tfinal_path.insert(0, goalie.parent)\n \tgoalie = goalie.parent\n\n\t# We are out of the BFS loop and we have our final path but it is in the form of coordinates. This loop changes them to the n,s,e,w format\n for i in range(len(final_path)-1):\n diffx = final_path[i+1].x - final_path[i].x\n diffy = final_path[i+1].y - final_path[i].y\n if diffx == 0 and diffy == -1:\n solution.append(\"n\")\n elif diffx == 0 and diffy == 1:\n solution.append(\"s\")\n elif diffx == 1 and diffy == 0:\n solution.append(\"e\")\n elif diffx == -1 and diffy == 0:\n solution.append(\"w\")\n\n return solution, search_tree\n\n\n\n def run(self, problem):\n # problem = {\n # snake_locations: [[int,int],[int,int],...],\n # current_direction: str,\n # food_locations: [[int,int],[int,int],...],\n # }\n solution = []\n directions = \"nswe\"\n # the following algorithm is NOT a valid algorithm\n # it randomly generates solution that is invalid\n # its purpose is to show you how this class will work\n # not a guide to how to write your algorithm\n solution, search_tree = self.func(problem)\n # the following search tree is a static search tree \n # to show you the format of the variable \n # to generate a search tree that can be displayed in the frontend.\n # you are required to generate the search tree based on your search algorithm\n # search_tree = [\n # {\n # \"id\": 1,\n # \"state\": \"0,0\",\n # \"expansionsequence\": 1,\n # \"children\": [2,3,4],\n # \"actions\": [\"n\",\"w\",\"e\"],\n # \"removed\": False,\n # \"parent\": None\n # },\n # {\n # \"id\": 2,\n # \"state\": \"5,0\",\n # \"expansionsequence\": 2,\n # \"children\": [5,6,7],\n # \"actions\": [\"n\",\"s\",\"w\"],\n # \"removed\": False,\n # \"parent\": 1\n # },\n # {\n # \"id\": 3,\n # \"state\": \"0,3\",\n # \"expansionsequence\": -1,\n # \"children\": [],\n # \"actions\": [],\n # \"removed\": False,\n # \"parent\": 1\n # },\n # {\n # \"id\": 4,\n # \"state\": \"0,4\",\n # \"expansionsequence\": -1,\n # \"children\": [],\n # \"actions\": [],\n # \"removed\": False,\n # \"parent\": 1\n # },\n # {\n # \"id\": 5,\n # \"state\": \"5,0\",\n # \"expansionsequence\": -1,\n # \"children\": [],\n # \"actions\": [],\n # \"removed\": True,\n # \"parent\": 2\n # },\n # {\n # \"id\": 6,\n # \"state\": \"5,3\",\n # \"expansionsequence\": -1,\n # \"children\": [],\n # \"actions\": [],\n # \"removed\": False,\n # \"parent\": 2\n # },\n # {\n # \"id\": 7,\n # \"state\": \"1,0\",\n # \"expansionsequence\": -1,\n # \"children\": [],\n # \"actions\": [],\n # \"removed\": False,\n # \"parent\": 2\n # }\n # ]\n # this function should return the solution and the search_tree\n return solution, search_tree\n\n\nif __name__ == \"__main__\":\n p1 = Player({ \"maze_size\": [10,10], \"static_snake_length\": True })\n sol, st = p1.run({'snake_locations': [[0, 5]], 'current_direction': 'e', 'food_locations': [[6, 7]]})\n print(\"Solution is:\", sol)\n print(\"Search tree is:\")\n print(st)\n\n"} {"blob_id": "faf8fce008d1a6d80125dd073fad0e74d2c39783", "repo_name": "Kacper-Sleziak/CRT-in-Redudant-Residue-Number-System", "path": "/main.py", "length_bytes": 3822, "score": 3.859375, "int_score": 4, "content": "from System import *\nfrom rns_to_pos_converter import *\n\n\ndef main_menu():\n while True:\n print(\"Wcisnij: \")\n print(\"1 aby dokonac operacji w systemie resztowym\")\n print(\"2 aby zamienic liczbe z systemu resztowego na pozycyjny\")\n print(\"3 aby wyjsc z programu\")\n\n print(\"\")\n x = input(\"Wpisz numer: \")\n print(\"\")\n\n if x == '1':\n rns_operations_menu()\n\n if x == '2':\n rns_number = []\n base = []\n\n print(\"Podaj dlugosc bazy oraz liczby w systemie resztowym: \")\n length = int(input(\"Podaj dlugosc: \"))\n\n print(\"\")\n\n for i in range(length):\n x = int(input(f\"Podaj liczbe w bazie na pozycji {i}: \"))\n base.append(x)\n\n print(\"\")\n\n for i in range(length):\n x = int(input(f\"Podaj liczbe w systemie resztowym na pozycji {i}: \"))\n rns_number.append(x)\n\n print(converter(rns_number, base))\n\n print(\"\")\n\n if x == '3':\n break\n\n\ndef rns_operations_menu():\n print(\"CRT MENU\")\n base_len = int(input(\"Podaj wielkosc bazy: \"))\n base = []\n\n for i in range(base_len):\n z = int(input(f\"Podaj numer bazy na pozycji numer {i + 1}: \"))\n base.append(z)\n\n print(\"\")\n\n pos_number = int(input(\"Podaj liczbe w systemie pozycyjnym: \"))\n print(\"\")\n\n RNS = System(base, pos_number)\n\n while True:\n print(\"Wcisnij: \")\n print(\"0 aby zmienic baze i liczbe\")\n print(\"1 aby otrzymac liczbe w systmie resztowym\")\n print(\"2 aby dodac dwie liczby w systemie resztowym\")\n print(\"3 aby pomnozyc dwie liczby w systemie resztowym\")\n print(\"4 aby podzielic dwie liczby w systemie resztowym\")\n print(\"5 aby obliczy\u0107 rang\u0119 liczby\")\n print(\"6 aby obliczy\u0107 rang\u0119 liczby nadmiarowo\")\n print(\"7 aby obliczyc liczbe w systemie pozycyjnym przy pomocy rangi\")\n print(\"8 aby wyjsc z menu operacji w systemie resztowym\")\n\n print(\"\")\n x = input(\"Wpisz numer: \")\n print(\"\")\n\n if x == '0':\n base_len = int(input(\"Podaj wielkosc nowej bazy: \"))\n base = []\n\n for i in range(base_len):\n z = int(input(f\"Podaj numer bazy na pozycji numer {i + 1}: \"))\n base.append(z)\n\n pos_number = int(input(\"Podaj nowa liczbe w systemie pozycyjnym: \"))\n print(\"\")\n\n RNS = System(base, pos_number)\n\n elif x == '1':\n print(f\"liczba w systmie resztowym: {RNS.get_rns()}\")\n print(\"\")\n\n elif x == '2':\n pos_number_b = int(input(\"Podaj druga liczbe w systmie pozycyjnym: \"))\n RNS_b = System(base, pos_number_b)\n print(f\"Wynik dodawania {RNS.addition(RNS_b)}\")\n print(\"\")\n\n elif x == '3':\n pos_number_b = int(input(\"Podaj druga liczbe w systmie pozycyjnym: \"))\n RNS_b = System(base, pos_number_b)\n print(f\"Wynik mnozenia: {RNS.multiplication(RNS_b)}\")\n print(\"\")\n\n elif x == '4':\n pos_number_b = int(input(\"Podaj druga liczbe w systmie pozycyjnym: \"))\n RNS_b = System(base, pos_number_b)\n print(f\"Wynik dzielenia: {RNS.division(RNS_b)}\")\n print(\"\")\n\n elif x == '5':\n print(f\"Ranga liczby: {RNS.get_rank_of_number()}\")\n print(\"\")\n\n elif x == '6':\n print(f\"Ranga liczby: {RNS.get_rank_of_number_redundant()}\")\n print(\"\")\n\n elif x == '7':\n print(f\"Liczba w systemie pozycyjnym: {RNS.convert_to_pos_by_rank()}\")\n print(\"\")\n\n elif x == '8':\n break\n\n else:\n print(\"Wprowadziles/as zly znak!\")\n\nmain_menu()\n"} {"blob_id": "e0846afd3aadf7a7e656654cdc75ad8f18d40c4c", "repo_name": "vsdrun/lc_public", "path": "/co_dropbox/924_Minimize_Malware_Spread.py", "length_bytes": 11321, "score": 3.84375, "int_score": 4, "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\n\"\"\"\nhttps://leetcode.com/problems/minimize-malware-spread/\n\nIn a network of nodes,\neach node i is directly connected to another node\nj if and only if graph[i][j] = 1.\n\nSome nodes initial are initially infected by malware.\nWhenever two nodes are directly connected and at least one of those\ntwo nodes is infected by malware, both nodes will be infected by malware.\nThis spread of malware will continue until no more nodes\ncan be infected in this manner.\n\nSuppose M(initial) is the final number of nodes infected with malware in\nthe entire network, after the spread of malware stops.\n\n----------\nM(initial) => \u6240\u6709\u88abinfected nodes!\n\u554f: \u5f9einitial\u4e2d\u79fb\u9664\u90a3\u4e00\u500bnode\u6703\u4f7fM(initial)\u503c\u6700\u5c0f???\n----------\n\n\nWe will remove one node from the initial list.\nReturn the node that if removed, would minimize M(initial).\nIf multiple nodes could be removed to minimize M(initial),\n***return such a node with the smallest index. \u9700\u6c42\u770b\u6e05\u695a!\n\nNote that if a node was removed from the initial list of infected nodes,\nit may still be infected later as a result of the malware spread.\n\n\nExample 1:\nInput: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]\nOutput: 0\n\nExample 2:\nInput: graph = [[1,0,0],[0,1,0],[0,0,1]], initial = [0,2]\nOutput: 0\n\nExample 3:\nInput: graph = [[1,1,1],[1,1,1],[1,1,1]], initial = [1,2]\nOutput: 1\n\nNote:\n* 1 < graph.length = graph[0].length <= 300\n* 0 <= graph[i][j] == graph[j][i] <= 1\n* graph[i][i] = 1\n* 1 <= initial.length < graph.length\n* 0 <= initial[i] < graph.length\n\ngraph \u7684format explain:\n1. graph\u7684index\u70banode index\n2. graph[0] = [1,1,0] \u4ee3\u8868 0->0 == 1, 0->1 == 1, 0->2 == 0\n\"\"\"\n\n\nclass Solution(object):\n def minMalwareSpread(self, graph, initial):\n \"\"\"\n :type graph: List[List[int]]\n :type initial: List[int]\n :rtype: int\n \"\"\"\n import collections\n\n def find(x):\n if x != parents[x]:\n parents[x] = find(parents[x])\n return parents[x]\n\n def union(x, y):\n parents[find(x)] = find(y)\n\n # init\n n = len(graph)\n parents = range(n)\n\n # union\n for i in range(n):\n for j in range(i + 1, n):\n if graph[i][j] == 1:\n union(i, j)\n\n # print(\"parents: {}\".format(parents))\n\n area = collections.Counter(find(i) for i in range(n))\n print(\"allNodes: {}\".format(area))\n\n malware = collections.Counter(find(i) for i in initial)\n # print(\"badnodes: {}\".format(malware))\n return min(initial, key=lambda i: [\n (malware[find(i)] == 1) * -area[find(i)], i])\n\n def rewrite(self, graph, initial):\n \"\"\"\n :type graph: List[List[int]]\n :type initial: List[int]\n :rtype: int\n\n no rank compress\n \"\"\"\n from collections import Counter as cc\n\n nodes = len(graph)\n parents = range(nodes) # [0, 1, 2, 3, ... ] SMART!\n\n def find(node):\n if parents[node] != node:\n return find(parents[node])\n return node\n\n def union(x, y):\n fx = find(x)\n fy = find(y)\n parents[fx] = fy\n\n # build union parents\n for x in range(nodes):\n for y in range(x + 1, nodes):\n # \u6ce8\u610f\u6b64! \u70ba1\u624d\u662f\u6709conncetion!\n if graph[x][y] == 1:\n union(x, y)\n\n # print(\"parents: {}\".format(parents))\n\n # dissect nodes forms a quorum\n # allNodes means: for each node if they form a quorum, will eventually\n # has the same return node, thus the node count would be the nodes\n # inside a quorum.\n allNodes = cc(find(i) for i in range(nodes))\n # print(\"allNodes: {}\".format(allNodes))\n\n # initial means the nodes being effected.\n # with this effected nodes, see are they in the same quorum.\n # If they are, then will have single node with multiple counts.\n # If not, if having 2 effected nodes, will have 2 counter key, each\n # has value 1.\n # badNodes = cc(find(i) for i in initial)\n # print(\"badNodes: {}\".format(badNodes))\n\n result = []\n # \u91cd\u9ede! \u4ee5unin\u7684!root! \u70ba key! \u4ee5\u6b64key\u4f86\u7b97count!\n\n for bad in initial:\n key = find(bad)\n result.append((allNodes[key], -bad))\n\n # print(result)\n\n return -max(result)[1]\n\n def rewrite2(self, graph, initial):\n \"\"\"\n :type graph: List[List[int]]\n :type initial: List[int]\n :rtype: int\n union rank compress\n \"\"\"\n from collections import defaultdict as dd\n\n class Node(object):\n def __init__(self, val):\n self.rank = 0\n self.val = val\n self.parent = self\n self.children = set()\n\n def addChild(self, node):\n self.children.add(node)\n\n def getc(self):\n return self.children\n\n def getp(self):\n return self.parent\n\n def setp(self, pnode):\n self.parent = pnode\n pnode.addChild(self)\n\n def incrRank(self):\n self.rank += 1\n\n\n nodeCnt = len(graph)\n tmpNodes = range(nodeCnt)\n nodes = [Node(n) for n in range(nodeCnt)]\n\n def find(node):\n if node.parent != node:\n node.parent = find(node.parent)\n return node.getp()\n\n def union(x, y):\n fx = find(x)\n fy = find(y)\n if fx.val == fy.val:\n return\n\n if fx.rank > fy.rank:\n fy.setp(fx)\n elif fx.rank < fy.rank:\n fx.setp(fy)\n else:\n fy.incrRank()\n fx.setp(fy)\n\n # build union parents\n for x in range(nodeCnt):\n for y in tmpNodes[:x] + tmpNodes[x+1:]:\n # \u6ce8\u610f\u6b64! \u70ba1\u624d\u662f\u6709conncetion!\n if graph[x][y] == 1:\n union(nodes[x], nodes[y])\n\n # key: nodes, val: which initial\n dmap = dd(list)\n mkey = float(\"-inf\")\n\n for bad in initial:\n b = nodes[bad]\n m = len(b.getp().getc())\n mkey = max(mkey, m)\n dmap[m].append(bad)\n\n return [] if mkey == float(\"-inf\") else sorted(dmap[mkey])[0]\n\n def rewrite3(self, graph, initial):\n \"\"\"\n :type graph: List[List[int]]\n :type initial: List[int]\n :rtype: int\n union rank compress + build graph from initial\n \"\"\"\n from collections import defaultdict as dd\n\n class Node(object):\n def __init__(self, val):\n self.rank = 0\n self.val = val\n self.parent = self\n self.children = set()\n\n def addChild(self, node):\n self.children.add(node)\n\n def getc(self):\n return self.children\n\n def getp(self):\n return self.parent\n\n def setp(self, pnode):\n self.parent = pnode\n pnode.addChild(self)\n\n def incrRank(self):\n self.rank += 1\n\n nodes = [Node(n) for n in range(len(graph))]\n\n def find(node):\n if node.parent != node:\n node.parent = find(node.parent)\n return node.getp()\n\n def union(x, y):\n fx = find(x)\n fy = find(y)\n if fx.val == fy.val:\n return\n\n if fx.rank > fy.rank:\n fy.setp(fx)\n elif fx.rank < fy.rank:\n fx.setp(fy)\n else:\n fy.incrRank()\n fx.setp(fy)\n\n oinitial = initial\n visited = set()\n\n while initial:\n tmp = []\n\n for x in initial:\n visited.add(x)\n\n for y in range(len(graph[x])):\n if y != x and graph[x][y] == 1 and y not in visited:\n tmp.append(y)\n union(nodes[x], nodes[y])\n initial = tmp\n\n maxx = float(\"-inf\")\n dmap = dd(list)\n\n for i in oinitial:\n n = nodes[i]\n parent = n.getp()\n children = parent.getc()\n maxx = max(maxx, len(children))\n dmap[len(children)].append(i)\n\n return [] if maxx == 0 or maxx == float(\"-inf\") else \\\n sorted(dmap[maxx])[0]\n\ndef build():\n # [0, 4, 7, 8, 11, 28, 29]\n # bad: 13 parent: 4 children: [15, 16, 17, 18, 19, 20, 21, 22, 24, 26, 27, 28, 29, 0, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13]\n# bad: 4 parent: 4 children: [15, 16, 17, 18, 19, 20, 21, 22, 24, 26, 27, 28, 29, 0, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13]\n# bad: 1 parent: 19 children: [1, 25, 23]\n# bad: 3 parent: 4 children: [15, 16, 17, 18, 19, 20, 21, 22, 24, 26, 27, 28, 29, 0, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13]\n return [\n [1,0,0,0,1,0,1,0,1,1,1,0,1,1,0,0,1,0,1,0,1,0,0,0,0,0,0,0,0,0],\n [0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,0],\n [0,0,1,0,0,0,0,1,1,0,1,0,0,1,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0],\n [0,0,0,1,0,0,1,1,0,1,0,0,0,0,1,1,0,1,1,0,0,0,1,0,0,1,0,0,1,1],\n [1,0,0,0,1,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1],\n [0,0,0,0,0,1,0,0,1,1,0,1,0,0,0,0,1,0,0,1,0,1,0,1,0,1,0,0,0,1],\n [1,0,0,1,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0],\n [0,0,1,1,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,1],\n [1,0,1,0,1,1,0,0,1,0,0,0,1,1,0,1,0,0,1,1,0,0,0,0,0,1,0,0,0,0],\n [1,0,0,1,0,1,1,0,0,1,0,0,0,1,0,1,0,0,0,0,1,0,1,0,0,1,0,0,0,0],\n [1,0,1,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,1,1,0,0,1,1,0,0,0,0,0],\n [0,0,0,0,1,1,0,0,0,0,0,1,0,0,0,1,1,1,0,0,0,0,1,0,0,0,1,0,0,1],\n [1,0,0,0,0,0,0,1,1,0,0,0,1,0,0,0,0,0,0,1,0,1,0,0,0,1,0,0,1,0],\n [1,0,1,0,0,0,0,0,1,1,0,0,0,1,0,0,0,1,0,1,0,0,0,0,0,0,1,0,1,0],\n [0,0,1,1,0,0,0,0,0,0,1,0,0,0,1,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0],\n [0,0,0,1,0,0,0,0,1,1,0,1,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0],\n [1,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,1,0,1,0,1,0,0,0,1,0,1,0,0,0],\n [0,0,0,1,0,0,0,0,0,0,0,1,0,1,1,0,0,1,1,1,0,0,0,0,0,1,0,0,1,0],\n [1,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,1,1,1,0,0,0,0,1,0,0,0,1,0,1],\n [0,1,0,0,0,1,1,0,1,0,1,0,1,1,1,0,0,1,0,1,0,1,1,0,0,0,0,0,0,0],\n [1,0,1,0,0,0,0,0,0,1,1,0,0,0,0,1,1,0,0,0,1,1,1,0,1,0,0,0,0,0],\n [0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,1,1,1,1,0,0,1,0,0,1,0],\n [0,0,0,1,0,0,0,1,0,1,0,1,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1],\n [0,1,0,0,0,1,0,1,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,1,0,1,0,0,0,0],\n [0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0],\n [0,1,0,1,0,1,1,0,1,1,0,0,1,0,0,0,0,1,0,0,0,1,0,1,0,1,0,1,0,0],\n [0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0],\n [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,1,0,1,0,0],\n [0,0,0,1,1,0,0,0,0,0,0,0,1,1,0,0,0,1,0,0,0,1,1,0,0,0,0,0,1,1],\n [0,0,0,1,1,1,0,1,0,0,0,1,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,1,1]], [13,4,1,3]\n\n return [[1,1,1],[1,1,1],[1,1,1]], [1,2]\n return [[1,1,0],[1,1,0],[0,0,1]], [0,1]\n return [[1,0,0,0],[0,1,0,0],[0,0,1,1],[0,0,1,1]], [3,1]\n\n\nif __name__ == \"__main__\":\n s = Solution()\n print(s.minMalwareSpread(*build()))\n print(s.rewrite3(*build()))\n"} {"blob_id": "b9e3d69ab0bdf2976ef597e32e5894bcb540d2ef", "repo_name": "zirin12/Leetcode-InterviewBit-Solutions", "path": "/InterviewBit/spiral_order_example.py", "length_bytes": 1191, "score": 3.75, "int_score": 4, "content": "'''\nGiven a matrix of m * n elements (m rows, n columns), return all elements of the matrix in spiral order.\n'''\nclass Solution:\n\t# @param A : tuple of list of integers\n\t# @return a list of integers\n\tdef spiralOrder(self, A):\n\t m = len(A)\n\t n = len(A[0])\n\t total = m*n\n\t count = 0 \n\t direction = [0,0,0,0] # up , down , left , right\n\t direction[0] = 1\n\t row,col = 0,0\n\t result = []\n\t while count self.heap1[0] * (-1):\n heapq.heappush(self.heap2, num)\n else:\n heapq.heappush(self.heap1, num * (-1))\n heapq.heappush(self.heap2, heapq.heappop(self.heap1) * (-1))\n\n def GetMedian(self, n = None):\n # write code here\n if self.heap1:\n if (len(self.heap1) + len(self.heap2)) & 1 == 1:\n return self.heap1[0] * (-1)\n else:\n return (self.heap1[0] * (-1) + self.heap2[0]) / 2.0"} {"blob_id": "99617ea58a26569ba772913af3373e24da937b1f", "repo_name": "jacquerie/leetcode", "path": "/leetcode/0211_add_and_search_word_data_structure_design.py", "length_bytes": 1380, "score": 3.875, "int_score": 4, "content": "# -*- coding: utf-8 -*-\n\n\nclass TrieNode:\n def __init__(self):\n self.children = {}\n self.leaf = False\n\n\nclass Trie:\n def __init__(self):\n self.root = TrieNode()\n\n def insert(self, word):\n current = self.root\n for char in word:\n if char not in current.children:\n current.children[char] = TrieNode()\n current = current.children[char]\n current.leaf = True\n\n def search(self, word):\n return self._search(word, self.root)\n\n def _search(self, word, current):\n for i, char in enumerate(word):\n if char == \".\":\n for child in current.children:\n if self._search(word[i + 1 :], current.children[child]):\n return True\n return False\n elif char not in current.children:\n return False\n current = current.children[char]\n return current.leaf\n\n\nclass WordDictionary:\n def __init__(self):\n self.trie = Trie()\n\n def addWord(self, word):\n self.trie.insert(word)\n\n def search(self, word):\n return self.trie.search(word)\n\n\nif __name__ == \"__main__\":\n obj = WordDictionary()\n\n obj.addWord(\"bad\")\n obj.addWord(\"dad\")\n obj.addWord(\"mad\")\n assert not obj.search(\"pad\")\n assert obj.search(\"bad\")\n assert obj.search(\".ad\")\n"} {"blob_id": "ca23b553919b11432fb4746ebc5bc861245f8fe4", "repo_name": "HarrrrryLi/LeetCode", "path": "/1214. Two Sum BSTs/Python 3/solution.py", "length_bytes": 878, "score": 3.78125, "int_score": 4, "content": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\n\nclass Solution:\n def twoSumBSTs(self, root1: TreeNode, root2: TreeNode, target: int) -> bool:\n tree1 = set()\n self.DFS(root1, tree1)\n stack = collections.deque()\n stack.append(root2)\n\n while stack:\n cur = stack.pop()\n if target - cur.val in tree1:\n return True\n if cur.left:\n stack.append(cur.left)\n if cur.right:\n stack.append(cur.right)\n\n return False\n\n def DFS(self, root, nodes):\n if not root:\n return\n\n nodes.add(root.val)\n if root.left:\n self.DFS(root.left, nodes)\n if root.right:\n self.DFS(root.right, nodes)\n"} {"blob_id": "ed466332824abe44bff0747eb9503a8b58be0abd", "repo_name": "likhith10/Machine-Learning-Algorithms-", "path": "/PCA.py", "length_bytes": 1700, "score": 3.5, "int_score": 4, "content": "#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Sep 22 00:19:39 2017\r\n\r\n@author: likhith\r\n\"\"\"\r\n\r\n\r\nimport numpy as np\r\n\r\n\r\n\r\n\r\n\r\n#Reading the dataset file from the computer\r\ndata=np.recfromcsv(\"/Users/likhith/Downloads/dataset_1.csv\")\r\n# considering each coloumn into one variable and one using more variable in which all three are combined coloumn wise\r\nd1=data[\"x\"]\r\nd2=data[\"y\"]\r\nd3=data['z']\r\nd4 = np.array([d1,d2,d3])\r\nnp.var(d1)\r\nnp.var(d2)\r\nnp.var(d3)\r\nnp.cov(d1,d2)\r\nnp.cov(d2,d3)\r\n\r\n#Calculating mean of each variable \r\nmean_x = np.mean(d1)\r\nmean_y = np.mean(d2)\r\nmean_z = np.mean(d3)\r\n\r\n\r\n#forming an array from the means found out from above step \r\nmean_vect = np.array([[mean_x],[mean_y],[mean_z]])\r\nprint('Mean Vector:\\n', mean_vect)\r\n\r\n\r\n#Calculating covariance for each coloumn\r\ncov_matrix = np.cov([d1,d2,d3])\r\nprint('Covariance Matrix:\\n', cov_matrix)\r\n\r\n\r\n#Calculating the Eigen values and Eigen vectors by using covariance matrix\r\neig_value_cov, eig_vect_cov = np.linalg.eig(cov_matrix)\r\n\r\n\r\n#making key value eigen pairs \r\neig_pairs = [(np.abs(eig_value_cov[i]), eig_vect_cov[:,i]) for i in range(len(eig_value_cov))]\r\neig_pairs.sort(key=lambda x: x[0], reverse=True)\r\n\r\nfor i in eig_pairs:\r\n print(i[0])\r\n \r\n \r\n# reducing a 3-dimensional feature space to a 2-dimensional feature subspace \r\nmatrix_r = np.hstack((eig_pairs[0][1].reshape(3,1), eig_pairs[1][1].reshape(3,1)))\r\n#combined the two eigenvectors with the highest eigenvalues to construct d\u00d7k-dimensional eigenvector matrix R and printing it\r\nprint('Matrix R:\\n', matrix_r)\r\n\r\n\r\n#Transforming the given dataset into new Eigen Spaces\r\ntransformed = matrix_r.T.dot(d4)\r\ntransformed"} {"blob_id": "1e579ab8d9325bf02b1c4b050bb5d84bf5974412", "repo_name": "sadimanna/project_euler", "path": "/p58.py", "length_bytes": 578, "score": 3.5625, "int_score": 4, "content": "import math, time\r\n\r\ndef isprime(n):\r\n\tfor i in range(2, int(math.sqrt(n))+1):\r\n\t\tif n%i==0:\r\n\t\t\treturn 0\r\n\treturn 1\r\n\r\nif __name__ == '__main__':\r\n\tlenside = 1\r\n\tprimeperc = 100\r\n\tnumprime = 0\r\n\tnumtot = 1\r\n\tstime = time.time()\r\n\twhile primeperc >= 10 :\r\n\t\tlenside+=2\r\n\t\tval = lenside**2\r\n\t\tlenm1 = lenside - 1\r\n\r\n\t\tfor i in range(4):\r\n\t\t\tif isprime(val-i*lenm1):\r\n\t\t\t\t#primes.append(val-i*lenm1)\r\n\t\t\t\tnumprime+=1\r\n\t\tnumtot+=4\r\n\t\tprimeperc = 100*numprime/numtot\r\n\t\t#print(lenside, primeperc)\r\n\tprint(\"Time taken : %s milliseconds\"%((time.time()-stime)*1000))\r\n\tprint(lenside)\r\n"} {"blob_id": "d038a3b204f9ee24d3ad8300aa1f54142184ae35", "repo_name": "ecgaebler/Practice", "path": "/LeetCode/0472.py", "length_bytes": 854, "score": 3.765625, "int_score": 4, "content": "from functools import lru_cache\nclass Solution:\n def findAllConcatenatedWordsInADict(self, words: List[str]) -> List[str]: \n concats = set() #set of concatenated words\n words_set = set(words) #set of all input words, for quick lookup\n \n @lru_cache(maxsize=15000)\n def is_concat(word):\n for i in range(len(word)):\n word_start = word[:i]\n word_end = word[i:]\n if word_start != \"\" and word_start in words_set: #check if beginning of word is in words_set\n if word_end in words_set or is_concat(word_end): #check if end is in words_set, or is a concat\n return True\n return False\n \n for word in words:\n if is_concat(word):\n concats.add(word)\n return list(concats)"} {"blob_id": "0345016c429b4c1166cb0a86f077b7b83dc7a473", "repo_name": "valenpendragon/Blackjack-py36", "path": "/lib/BlackjackLibraries.py", "length_bytes": 57337, "score": 4.0625, "int_score": 4, "content": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jul 5 07:17:53 2018\r\n\r\nThis is the principal Class library for Blackjack Games. These classes include:\r\n\r\n Class Card: Stores a card, along with its value in Blackjack.\r\n SubClass Ace: Stores aces, which have two possible values in game.\r\n\r\n Class Deck: 52 card object\r\n SubClass CardShoe: A multideck (1 to 8 decks) object fully shuffled\r\n with additional entropy added to improve randomness.\r\n\r\n Class Hand: A grouping of cards dealt to players.\r\n SubClass SplitHand: Handles the special methods unique to split hands.\r\n SubClass DealerHand: A hand specifically designed for the dealer.\r\n\r\n Class Player: Stores the hand(s), bet(s), and bank status of each player\r\n SubClass Dealer: Stores the hand of the dealer and the dealer's bank.'\r\n\r\n Class CasinoTable: Object stores blackjack multipliers, players, the deck\r\n and the Dealer. It hands the actual play of rounds of Blackjack.\r\n\r\n Class Casino: Store CasinoTable objects of various kinds. Methods\r\n arbitrate which tables players can play at and controls special events.\r\n\r\n Class Game: This object stores the attributes of the players between games.\r\n\r\n@author: Jeffrey Scott\r\n\"\"\"\r\n\r\nimport random as rd\r\n\r\n# Constants:\r\nRANKS = ('A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K')\r\nSUITS = ('S', 'D', 'H', 'C')\r\n\r\n\r\nclass Card(object):\r\n '''\r\n This class is used to simulate a playing card. It is composed of a\r\n three attributes: rank, suit, and value, where rank is taken from 2 through\r\n king, suit (also found below), and value is based on the rank, being\r\n equal to numerical value appearing in the rank. All \"face\" cards, Jack,\r\n Queen, and King, have a value of 10 as well.\r\n Note: Aces are dealt with in a subclass.\r\n\r\n Methods:\r\n __init__: creates a card tuple using provided rank and suit.\r\n __str__: returns the card in Rank-Suit format.\r\n\r\n Attributes:\r\n self.rank: This is the rank of the card. Valid values are: '2', '3',\r\n '4', '5', '6', '7','8', '9', '10', 'J', 'Q', 'K'.\r\n Note: The rank of this base class does not include Aces.\r\n self.suit: This is the card suit (Spades, Diamonds, Hearts, Clubs),\r\n represented by the first character of the name of the suit.\r\n self.value: This is the integer value of the rank (2 - 10).\r\n '''\r\n\r\n # Methods\r\n def __init__(self, rank, suit):\r\n \"\"\"\r\n This method creates a card object from two arguments, rank and suit.\r\n If a rank appears that is not in ranks, it will raise a ValueError.\r\n INPUTS: rank, suit, both strings\r\n OUTPUT: None\r\n \"\"\"\r\n # First we need to check the rank. If is not in a specific set of\r\n # values, we need to raise an error. We have to explicitly create\r\n # a local copy of ranks and suits since they do not exist yet.\r\n ranks = ('2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K')\r\n suits = ('S', 'D', 'H', 'C')\r\n if rank not in ranks:\r\n print(f\"Card: An invalid rank was supplied {rank}.\")\r\n raise ValueError(\"Card objects must have a valid rank.\") from None\r\n return None\r\n\r\n if suit not in suits:\r\n print(f\"Card: An invalid suit was supplied {suit}.\")\r\n raise ValueError(\"Card objects must have a valid suit.\") from None\r\n return None\r\n\r\n # If we get to this point, the rank and suit are valid choices.\r\n self.rank = rank\r\n self.suit = suit\r\n # Now, we need to check the value. We will try to convert the rank to\r\n # an integer. If successful, we know that the card is 2 to 10. If not,\r\n # we know that it is a face card (Aces are dealt with in a subclass).\r\n try:\r\n value = int(self.rank)\r\n except ValueError:\r\n # This is a face card.\r\n value = 10\r\n self.value = value\r\n\r\n def __str__(self):\r\n \"\"\"\r\n This method returns the card in the format Rank-Suit. It suppresses\r\n the newline very specifically. It takes no arguments.\r\n \"\"\"\r\n return \"{0}-{1} \".format(self.rank, self.suit)\r\n\r\n\r\nclass Ace(Card):\r\n \"\"\"\r\n This class deals with the special case that a card is an Ace. Aces have two\r\n possible values in Blackjack, 1 or 11. The value depends on whether or not\r\n the dealer or player would bust if the Ace is considered an 11. This class\r\n inherits __str__, but needs a separate __init__() method. In usage in game\r\n programming, use an if statement like this one:\r\n if type(card) == Ace:\r\n to separate Aces from the other cards when scoring hands, etc.\r\n\r\n Unique Methods:\r\n __init__: Adds an extra attribute reflecting an ace's second value.\r\n Takes only suit as an argument.\r\n\r\n Inherited Methods:\r\n __str__: Returns a value string in Rank-Suit format.\r\n\r\n Unique Attributes:\r\n self.additional_value: This is the higher value of a Ace, 11.\r\n\r\n Inherited Attributes:\r\n self.rank: This is the rank of the card. Valid values are: '2', '3',\r\n '4', '5', '6', '7','8', '9', '10', 'J', 'Q', 'K'.\r\n Note: The rank of this base class does not include Aces.\r\n self.suit: This is the card suit (Spades, Diamonds, Hearts, Clubs),\r\n represented by the first character of the name of the suit.\r\n self.value: This is the integer value of the rank (2 - 10).\r\n\r\n \"\"\"\r\n\r\n # Methods:\r\n def __init__(self, suit):\r\n \"\"\"\r\n Aces only take a str value for suit. They take no other arguments.\r\n INPUT: suit, string\r\n OUTPUT: None\r\n \"\"\"\r\n suits = ('S', 'D', 'H', 'C')\r\n if suit not in suits:\r\n print(f\"Card: An invalid suit was supplied {suit}.\")\r\n raise ValueError(\"Card objects must have a valid suit.\") from None\r\n return None\r\n\r\n # A valid suit was supplied.\r\n self.rank = 'A'\r\n self.suit = suit\r\n self.value = 1\r\n self.additional_value = 11\r\n\r\n\r\nclass Deck(object):\r\n '''\r\n This class returns a 52-card shuffled deck consisting of 4 suits, and 13\r\n cards per suit, Ace through King.\r\n\r\n Methods:\r\n __init__: returns a shuffled deck of 52 cards. Takes no arguments.\r\n __str__: returns the string \"A shuffled deck of {length} cards\", where\r\n length is the length determined by the __len__ function below.\r\n When invoked with diagnostic=True, prints the CardShoe.\r\n __len__: returns the number of cards remaining in the deck.\r\n remove_top: removes the card at index 0 and shifts the cards up one\r\n accordingly. This method takes no arguments.\r\n Attributes:\r\n shuffled_deck: the contents of the deck (a list of card objects\r\n length: The number of cards in the original deck.\r\n\r\n '''\r\n def __init__(self):\r\n \"\"\"\r\n This method generates a 52-card fully shuffled deck. It uses calls to\r\n rd.randint and rd.shuffle to create additional chaos in the shuffling\r\n process.\r\n\r\n NOTE: This randomization is good enough for a video game, but it is not\r\n random enough for gambling purposes.\r\n\r\n \"\"\"\r\n # This is a single standard deck of 52 cards.\r\n self.length = 52\r\n\r\n # Next, we need to create an unshuffled deck to move cards from.\r\n deck = []\r\n for rank in RANKS:\r\n for suit in SUITS:\r\n # Create the card.\r\n if rank == 'A':\r\n card = Ace(suit)\r\n else:\r\n card = Card(rank, suit)\r\n deck.append(card)\r\n\r\n # Next, we shuffle it using the rd.shuffle.\r\n rd.shuffle(deck)\r\n\r\n # To add some additional entropy, we take this shuffled set of cards\r\n # and randomly remove them one at a time and put them in the actual\r\n # shuffled deck, self.shuffled_deck.\r\n self.shuffled_deck = []\r\n while len(deck) > 0:\r\n next_card = deck.pop(rd.randint(0, len(deck) - 1))\r\n self.shuffled_deck.append(next_card)\r\n del deck\r\n\r\n def __len__(self):\r\n \"\"\"\r\n This method prints out the number of cards remaining in the Deck.\r\n object. It takes no arguments.\r\n INPUTS: None\r\n OUTPUTS: length, integer\r\n \"\"\"\r\n return len(self.shuffled_deck)\r\n\r\n def __str__(self, diagnostic=False):\r\n \"\"\"\r\n This method prints out the deck. In normal mode, it prints a string\r\n with the number of cards reamining in the deck. When diagnostic is\r\n True, it will print cards listed in the deck.\r\n INPUTS: diagnostic, boolean, defaults to False\r\n OUTPUTS: a string indicating remaining cards or an actual printout of\r\n the deck to the terminal screen.\r\n NOTE: To use the diagnostic option, use the Deck.__str__(**kwargs) form\r\n not the print(Deck) or str(Deck) methods.\r\n \"\"\"\r\n if not diagnostic:\r\n return \"The deck has {0} cards remaining.\".format(len(self))\r\n else:\r\n for card in self.shuffled_deck:\r\n print(card)\r\n\r\n def remove_top(self):\r\n \"\"\"\r\n This method removes the card at index zero of the Deck object. This is\r\n used when dealing cards from the deck.\r\n INPUTS: None\r\n OUTPUTS: card, Card type object\r\n \"\"\"\r\n return self.shuffled_deck.pop(0)\r\n\r\n\r\nclass CardShoe(Deck):\r\n '''\r\n This class uses the Deck class to create a CardShoe of up to 1 to 8 52 card\r\n decks.\r\n\r\n Unique Methods:\r\n __init__: The creation method requires an argument indicating the\r\n number of 52 card decks that will make up the CardShoe.\r\n\r\n Inherited Methods:\r\n __str__: returns the string \"A shuffled deck of {length} cards\", where\r\n length is the length determined by the __len__ function below.\r\n When invoked with diagnostic=True, prints the CardShoe.\r\n __len__: returns the number of cards remaining in the deck.\r\n remove_top: removes the card at index 0 and shifts the cards up one\r\n accordingly. This method takes no arguments.\r\n\r\n Unique Attributes: None\r\n\r\n Inherited Attributes:\r\n shuffled_deck: the contents of the deck (a list of card objects\r\n length: The number of cards in the original deck.\r\n '''\r\n def __init__(self, cs_size):\r\n \"\"\"\r\n This method creates a CardShoe object that contains cs_size 52 card\r\n Deck objects. It will check cs_size for a valid integer between 1 and\r\n 8, raising a TypeError if it is not an integer or a ValueError if\r\n cs_size is not in the correct range.\r\n INPUTS: cs_size, integer\r\n OUTPUTS: CardShoe object\r\n \"\"\"\r\n # Handling problems with cs_size that could break this method.\r\n if type(cs_size) != int:\r\n raise TypeError(\"CardShoe: cs_size must be an integer\")\r\n elif not 1 <= cs_size <= 8:\r\n raise ValueError(\"CardShoe: cs_size must be within interval [1, 8].\")\r\n\r\n self.length = 52 * cs_size\r\n self.shuffled_deck = []\r\n for i in range(cs_size):\r\n self.shuffled_deck.extend(Deck().shuffled_deck)\r\n\r\n\r\nclass Hand(object):\r\n '''\r\n This class stores cards for a normal blackjack hand. The receive_card\r\n method handles maintaining attributes for the Hand object as it receives\r\n Cards.\r\n\r\n Class Order Attributes:\r\n hand_type = 'regular' (string)\r\n Note: The subclasses use a different value for this constant.\r\n\r\n Methods:\r\n __init__(ante): Creates an empty player's hand. Initializes all of the\r\n Hand's attributes. Raises a TypeError if the ante is not an\r\n integer.\r\n __str__: Prints out the Hand.\r\n __len__: Returns the number of cards in the Hand.\r\n receive_card(card): Requires a Card object. Adds it to the Hand, then\r\n updates all of the Hand's attributes (listed below) accordingly.\r\n\r\n Attributes:\r\n cards: list of Card or Ace objects. Starts empty.\r\n has_ace: Boolean. Starts False.\r\n soft_score: integer, highest possible hand score less than 22 derivable\r\n from the cards (differs from hard_score if an ace is present).\r\n Starts 0.\r\n hard_score: integer, score of the hand if all Aces are scored as rank 1\r\n (differs from soft_score only if an ace is present). Starts 0.\r\n blackjack: Boolean. Starts False.\r\n has_pair: Boolean. Starts False.\r\n busted: Boolean. Starts False.\r\n bet_amt: integer. Must be supplied when instantiated.\r\n\r\n '''\r\n hand_type = 'regular'\r\n\r\n def __init__(self, ante):\r\n \"\"\"\r\n This method creates an empty player's Hand and initializes the Hand's\r\n attributes. Raises a TypeError if ante is not an integer.\r\n INPUTS: ante (integer)\r\n OUTPUTS: Hand object\r\n \"\"\"\r\n if type(ante) != int:\r\n raise TypeError(\"Hand.__init__:A bet must be an integer.\")\r\n self.cards = []\r\n self.has_ace = False\r\n self.soft_score = 0\r\n self.hard_score = 0\r\n self.blackjack = False\r\n self.has_pair = False\r\n self.busted = False\r\n self.bet_amt = ante\r\n\r\n def __len__(self):\r\n \"\"\"\r\n This method returns the number of cards in the Hand object.\r\n INPUTS: None\r\n OUTPUTS: length, integer\r\n \"\"\"\r\n return len(self.cards)\r\n\r\n def __str__(self, diagnostic=False):\r\n \"\"\"\r\n This method prints out the cards contained in the Card object and the\r\n possible scores for this hand. If this method is invoked using the form\r\n Hand.__str__(diagnostic=True), it will print out all of the Hand\r\n attributes.\r\n \"\"\"\r\n # This code checks to see which Hand types have been loaded along with\r\n # the Hand base class.\r\n if diagnostic:\r\n print(\"Type of hand: {0}\".format(self.hand_type))\r\n if len(self) == 0:\r\n print(\"No cards in the hand currently.\", end='')\r\n else:\r\n print(\"Cards in player's hand: \", end='')\r\n for card in self.cards:\r\n print(card, end='')\r\n print(\"\\nRemaining Attributes:\")\r\n\r\n # These attributes exist in all classes and subclasses of Hand.\r\n print(\"\\thas_ace = {0}\".format(self.has_ace))\r\n print(\"\\tsoft_score = {0}\".format(self.soft_score))\r\n print(\"\\thard_score = {0}\".format(self.hard_score))\r\n # This is Dealer only attribute.\r\n if self.hand_type == 'dealer':\r\n print(\"\\tinsurance = {0}\".format(self.insurance))\r\n # Only the Dealer has no bet_amt attribute.\r\n if self.hand_type != 'dealer':\r\n print(\"\\tbet_amt = {0}\".format(self.bet_amt))\r\n\r\n # The following code makes this method work for all subclasses:\r\n # self.blackjack does not exist for split hands.\r\n if self.hand_type != 'split':\r\n print(\"\\tblackjack = {0}\".format(self.blackjack))\r\n # self.has_pair only exists for a player's regular hand.\r\n if self.hand_type == 'regular':\r\n print(\"\\thas_pair = {0}\".format(self.has_pair))\r\n\r\n # self.busted exists in all classes and subclasses\r\n print(\"\\tbusted = {0}\".format(self.busted))\r\n else:\r\n if len(self) == 0:\r\n print(\"No cards have been dealt to the {0} hand yet.\".format(\r\n self.hand_type))\r\n if self.hand_type != 'dealer':\r\n print(\"Initial bet = {0}\".format(self.bet_amt))\r\n else:\r\n if self.hand_type == 'dealer':\r\n print(\"Dealer's hand: \".format(self.hand_type), end='')\r\n else:\r\n print(\"Player's {0} hand: \".format(self.hand_type), end='')\r\n for card in self.cards:\r\n print(card, end='')\r\n print(\"\\n\\tSoft Score: {0}\".format(self.soft_score))\r\n print(\"\\tHard Score: {0}\".format(self.hard_score))\r\n if self.hand_type != 'dealer':\r\n print(\"Current bet = {0}\".format(self.bet_amt))\r\n\r\n # This code may seem a little cumbersome, but SplitHand does\r\n # not have a blackjack attribute. This makes the code fully\r\n # inheritable for all classes. A try block is not as much of a\r\n # problem here.\r\n try:\r\n if self.hand_type != 'split' and self.blackjack:\r\n print(\"This player has blackjack.\")\r\n except NameError:\r\n # This pass command traps the NameError on split hands.\r\n pass\r\n\r\n # All Hand classes have a busted attribute.\r\n if self.busted:\r\n print(\"This hand has busted.\")\r\n else:\r\n print(\"This hand is still solvent.\")\r\n # Note: The attributes self.has_ace and self.has_pair (if they\r\n # exist for this object) are used behind the scenes.\r\n return \"\"\r\n\r\n def receive_card(self, top_card):\r\n \"\"\"\r\n This method adds a card to the Hand. This card should have been the top\r\n card from the CardShoe or Deck object in the game.\r\n INPUTS: top_card, a Card class object\r\n OUTPUTS: None. All changes are made to attributes.\r\n \"\"\"\r\n # First, we check for to see if the new card is an ace. If an ace was\r\n # already added, self.has_ace is already True.\r\n if type(top_card) == Ace:\r\n self.has_ace = True\r\n # Next, we check for pairs. Only the base (regular) Hand class cares\r\n # about pairs.\r\n if self.hand_type == 'regular' and len(self) == 1:\r\n if self.cards[0].rank == top_card.rank:\r\n self.has_pair = True\r\n # Next, we need check to see if the second card in the hand is an Ace\r\n # or a 10 value card. The DealerHand is the only class that cares about\r\n # this condition. This only matters for the face up card (2nd dealt) as\r\n # well.\r\n if self.hand_type == 'dealer' and len(self) == 1:\r\n if top_card.value == 1 or top_card.value == 10:\r\n self.insurance = True\r\n # Next, we need to add the card to the cards list.\r\n self.cards.append(top_card)\r\n # Next, we need to rescore the hand. All hands are scored using the\r\n # same formulas. The scores will be the same if there are no Aces in\r\n # the hand. The hard score is always the lower of the two scores. It\r\n # treats all Aces as a value of 11.\r\n hard_score = soft_score = 0\r\n for card in self.cards:\r\n hard_score += card.value\r\n if self.has_ace:\r\n # So, we detected at least one Ace. We can only score one Ace as a\r\n # 11 since 22 is an automatic bust. So, we only need to add 10 to\r\n # the hard score to see if it busts.\r\n soft_score = hard_score + 10\r\n else:\r\n soft_score = hard_score\r\n # We check the new soft_score. If it busts, we adjust it down. If not,\r\n # then both scores are solvent. Note, we have not tested the hard score\r\n # but it is lowest possible score the hand can have. So, we have to\r\n # record the score now, even if it is a bust and check for a bust.\r\n if soft_score > 21:\r\n self.soft_score = hard_score\r\n self.hard_score = hard_score\r\n # This is the bust check. Any type of Hand can bust.\r\n if hard_score > 21:\r\n self.busted = True\r\n else: # both scores are solvent\r\n self.soft_score = soft_score\r\n self.hard_score = hard_score\r\n # For regular and dealer Hands, we have to check for a blackjack.\r\n if self.hand_type != 'split' and len(self) == 2:\r\n # A blackjack requires 1 Ace and 1 10 value card.\r\n if self.cards[0].value == 1 and self.cards[1].value == 10:\r\n self.blackjack = True\r\n if self.cards[1].value == 1 and self.cards[0].value == 10:\r\n self.blackjack = True\r\n\r\n\r\nclass SplitHand(Hand):\r\n '''\r\n Class SplitHand is a subclass of class Hand. Like Hand, it stores cards and\r\n attributes for blackjack split hands. When a player has a pair of cards,\r\n they have the option of splitting up the pair, creating two new hand. This\r\n new type of hand, the \"split hand\", is more restricted than a regular hand.\r\n It cannot have a blackjack, nor can it split off another hand if the player\r\n draws a pair for it. The original regular Hand is deleted after the cards\r\n and bets are moved.\r\n\r\n Class Order Attributes:\r\n hand_type = 'split' (string)\r\n\r\n Unique Methods:\r\n __init__(card, bet): This subclass requires a card and a bet amount as\r\n arguments. Raises a TypeError if card is not Card type or bet is\r\n not an integer.\r\n\r\n Inherited Methods:\r\n __str__: Prints out the SplitHand.\r\n __len__: Returns the number of cards in the SplitHand.\r\n receive_card(card): Requires a Card object. Adds it to the SplitHand,\r\n then updates all of the Hand's attributes (listed below)\r\n accordingly.\r\n\r\n Unique Attributes: None\r\n\r\n Inherited Attributes:\r\n cards: list of Card or Ace objects. Starts empty, then adds Card or Ace\r\n object supplied as an argument to the new SplitHand.\r\n has_ace: Boolean. Starts False.\r\n soft_score: integer, highest possible hand score less than 22 derivable\r\n from the cards (differs from hard_score if an ace is present).\r\n Starts 0.\r\n hard_score: integer, score of the hand if all Aces are scored as rank 1\r\n (differs from soft_score only if an ace is present). Starts 0.\r\n busted: Boolean. Starts False.\r\n bet_amt: integer. Must be supplied when instantiated.\r\n\r\n Note: SplitHand has no blackjack or has_pair attribute because it is formed\r\n after 2 cards have already been dealt to the player.\r\n\r\n '''\r\n hand_type = 'split'\r\n\r\n def __init__(self, card, bet):\r\n \"\"\"\r\n This method initializes the SplitHand. It requires two arguments, a\r\n card to start off the hand, and bet amount for this hand. SplitHands\r\n are created from a pair of cards of the same rank.\r\n INPUTS: card (a Card or Ace object), bet (integer)\r\n OUTPUTS: a new SplitHand object\r\n \"\"\"\r\n self.cards = []\r\n self.has_ace = False\r\n self.soft_score = 0\r\n self.hard_score = 0\r\n self.busted = False\r\n self.bet_amt = bet\r\n self.receive_card(card)\r\n\r\n\r\nclass DealerHand(Hand):\r\n '''\r\n Class DealerHand is a subclass of Class Hand. Like Hand, it stores cards\r\n and attributes for the blackjack Dealer. As such, pairs have no meaning\r\n because the Dealer cannot have split hands. The condition of Blackjack does\r\n have meanning for the Dealer, however. The Dealer scores Aces the same way\r\n players do, although the Dealer has more restricted choices about how they\r\n play their Hand. The Dealer can bust, like any other player. The Dealer\r\n makes no bets. So, their hand has no bet_amt attribute.\r\n\r\n There is a unique attribute for the Dealer. When the Dealer has a card that\r\n is has a value of ten or an Ace showing, player's have the option to place\r\n an \"insurance bet\" on whether or not the Dealer has blackjack. The Dealer\r\n keeps their first card unexposed until the Dealer's turn arrives.\r\n\r\n Class Order Attribute:\r\n hand_type = 'dealer' (split)\r\n\r\n Unique Methods:\r\n __init__: Initializes the values for the Dealer's Hand. It takes no\r\n argument, unlike the other Hand objects.\r\n dealer_prin(diagnostic)t: Prints out the Dealer's Hand, while keeping\r\n the hold card \"face down\".\r\n\r\n Inherited Methods:\r\n __str__: Prints out the SplitHand.\r\n __len__: Returns the number of cards in the SplitHand.\r\n receive_card(card): Requires a Card object. Adds it to the SplitHand,\r\n then updates all of the Hand's attributes (listed below)\r\n accordingly.\r\n\r\n Unique Attributes:\r\n insurance: Boolean. Starts False. Indicates that the Dealer's visible\r\n card had a value of ten or is an Ace.\r\n\r\n Inherited Attributes:\r\n cards: list of Card or Ace objects. Starts empty.\r\n has_ace: Boolean. Starts False.\r\n soft_score: integer, highest possible hand score less than 22 derivable\r\n from the cards (differs from hard_score if an ace is present).\r\n Starts 0.\r\n hard_score: integer, score of the hand if all Aces are scored as rank 1\r\n (differs from soft_score only if an ace is present). Starts 0.\r\n blackjack: Boolean. Starts False.\r\n busted: Boolean. Starts False.\r\n\r\n Note: DealerHand has no bet_amt because bets are determined by the Players\r\n not by the Dealer. It also does not have a has_pair attribute because\r\n the Dealer cannot split their hands.\r\n '''\r\n hand_type = 'dealer'\r\n\r\n def __init__(self):\r\n \"\"\"\r\n This method initializes the Dealer's Hand. It takes no arguments\r\n because the Dealer makes no bets.\r\n INPUTS: None\r\n OUTPUTS: A new DealerHand object\r\n \"\"\"\r\n self.cards = []\r\n self.has_ace = False\r\n self.soft_score = 0\r\n self.hard_score = 0\r\n self.blackjack = False\r\n self.busted = False\r\n self.insurance = False\r\n\r\n def dealer_print(self, diagnostic=False):\r\n \"\"\"\r\n This method prints out the dealer's hand, while keeping the hold card\r\n concealed. This is used during the player's turns and while hands are\r\n being dealt to everyone at the table.\r\n INPUTS: diagnostic (boolean), optional argument\r\n OUTPUTS: None. All output is to the screen.\r\n \"\"\"\r\n # This code prints out a diagnostic version of the card con\r\n if diagnostic:\r\n print(\"Type of hand: {0}\".format(self.hand_type))\r\n if len(self) == 0:\r\n print(\"No cards in the hand currently.\", end='')\r\n else:\r\n print(\"Cards in Dealer's hand: \", end='')\r\n for card in self.cards:\r\n print(card, end='')\r\n print(\"\\nRemaining Attributes:\")\r\n\r\n # These attributes exist in all classes and subclasses of Hand.\r\n print(\"\\thas_ace = {0}\".format(self.has_ace))\r\n print(\"\\tsoft_score = {0}\".format(self.soft_score))\r\n print(\"\\thard_score = {0}\".format(self.hard_score))\r\n\r\n # self.insurance is unique to Dealer's.\r\n print(\"\\tinsurance = {0}\".format(self.insurance))\r\n\r\n # self.busted exists in all classes and subclasses\r\n print(\"\\tbusted = {0}\".format(self.busted))\r\n else:\r\n if len(self) == 0:\r\n print(\"No cards have been dealt to the Dealer's hand yet.\")\r\n else:\r\n print(\"Dealer's {0} hand: \".format(self.hand_type), end='')\r\n for card in self.cards:\r\n if card == self.cards[0]:\r\n print(\"hold \", end='')\r\n else:\r\n print(card, end='')\r\n # All Hand classes have a busted attribute.\r\n print(\"\\n\")\r\n if self.busted:\r\n print(\"This hand has busted.\")\r\n else:\r\n print(\"This hand is still solvent.\")\r\n return\r\n\r\n\r\nclass Player(object):\r\n '''\r\n The Player object is a computer player controlled by the Human Player. A\r\n player object is used to track the stake (money) this computer player has,\r\n the hands, if any, that this player is playing, and current total of all\r\n outstanding bets this player has, including insurance bets. It also tracks\r\n the relattve skill level of this computer player, as that controls which\r\n tables it can challenge. Player.hands is a dictionary of up to two Hands.\r\n\r\n Note: Bets on individual hands are attributes of class Hand and SplitHand.\r\n NOte: Player objects start with no Hand objects. All hands are removed at\r\n the end of each round. During a round, a Player can will have either one\r\n regular Hand or two Split Hands.\r\n\r\n Class Order Attributes:\r\n SKILL_TYPES = ('starter', 'adept', 'professional', 'master',\r\n 'high roller')\r\n\r\n Methods:\r\n __init__(name, skill, bank, reserve, table_min): This method requires\r\n a name, a string). For the other four arguments, there are default\r\n values. It uses these values to initialize the computer player.\r\n __str__(diagnostic): The argument defaults to False. This prints out\r\n the information on this computer player. Diagnostic mode prints\r\n out additional information.\r\n __len__: Returns the number of valid hands this Player still has.\r\n __del__(diagnostic): The argument defaults to False. Prints o message\r\n when a player breaks their bank with no reserve. Diagnostic movde\r\n prints more information.\r\n create_hand(ante): Creates an empty in Player.hands['one'] with a bet\r\n equal to the ante argument.\r\n create_split_hand(ante, which_hand, start_card): Creates a split hand\r\n with a bet equal to ante in PLayer.hands[which_hand] containing\r\n start_card as the first card.\r\n add_card_to_hand(card, which_hand): card must be a Card or Ace object.\r\n which_hand defaults to 'one'. This method returns True if the hand\r\n remains solvent, False if it busts.\r\n split_check(): Returns the value of hands['one'].has_pair.\r\n split_hand(hands['one]): This method takes the original hand (a pair)\r\n and splits it up into two SplitHand objects. It prompts the human\r\n player for an ante for this new hand. It removes the original hand\r\n frorm the game.\r\n update_bet(amt, which_hand,table_max): amt is a required value.\r\n which_hand defaults to 'one', table_max to 0. table_max is the\r\n maximum value allowed for any final bet. It also checks the bet\r\n on the Hand since bets cannot be raised to more than double the\r\n original ante. Sometables hove no max. So, table_max=0 means the\r\n max will be ignored.\r\n\r\n Attributes:\r\n name: a string. There is no default valur for it. It must be supplied\r\n to __init__().\r\n skill_level: string, restricted to values in SKILL_TYPES. Default is\r\n 'starter'.\r\n reserve: integer. This is the money the human player opted to have\r\n this computer player hold in reserve to avoid removal from the\r\n game. Default is 0.\r\n bank: integer. This is the amount of money this computer player can use\r\n to plave bets. No default or starting value.\r\n insurance_bet: integer. Normally set to None unless the player decides\r\n to place an insurance bet, if one could be made during the current\r\n round. Default None,.\r\n total_bets: integer. Total of all bets places, including insurance\r\n bets. Starts each round as None and returns to None once all bets\r\n have been resolved. Cannot exceed the computer player's bank.\r\n hands: A dictionary of Hand objects. Can consist of one regular Hand,\r\n addressed as hands['one'] or two SplitHand objects, addressed as\r\n hands['one'] or hands['two']. Starts with each Hand set to None.\r\n Each hand is reset to None.\r\n '''\r\n\r\n # Class Order Attributes:\r\n SKILL_TYPES = ('starter', 'adept', 'professional', 'master', 'high roller')\r\n\r\n def __init__(self, name, skill='starter', bank=10000, reserve=0, table_min=10):\r\n \"\"\"\r\n This method initializes the Player object's at attributes using the\r\n values supplied in the arguments. For a starting player, all of the\r\n defaults are used. Only a player name is required.\r\n INPUTS: name, string (required). skill. string that must match a value\r\n in SKILL_TYPES (optional, defaults to 'starter'). bank, integer\r\n (optional, default is 10000). reserve, integer (optional default\r\n is 0). table_min, integer (optional, default is 10).\r\n OUTPUTS: a Player object\r\n \"\"\"\r\n\r\n # The name is a required argument, but we can render it a string.\r\n self.name = str(name)\r\n # skill_level must be a choice in SKILL_TYPES. If not, we raise a\r\n # ValueError. Since this constant does not exist yet, we need to create\r\n # a local copy for the purpose of instantiating the object.\r\n skills = ('starter', 'adept', 'professional', 'master', 'high roller')\r\n if skill in skills:\r\n self.skill_level = skill\r\n else:\r\n raise ValueError(\"Pleyer.__init__(): {0} is an invalid choice\".format(skill))\r\n # The bank amount cannot prevent the player from making their ante on\r\n # the first hand.\r\n if (bank - table_min) < 0:\r\n raise ValueError(\"Player.__init__(): bank amount is too small.\")\r\n else:\r\n self.bank = bank - reserve\r\n self.reserve = reserve\r\n self.total_bets = 0\r\n self.insurance_bet = None\r\n self.hands = {'one': None, 'two': None}\r\n\r\n def __str__(self, diagnostic=False):\r\n \"\"\"\r\n This method prints out the player's name, bank, reserve, hand, and\r\n insurance bets. In diagnoistic mode, adds a diagnostic header to the\r\n output and requests diagnostic output from the Hands. This method can\r\n tell if it is called for a regular player or a dealer.\r\n INTPUTS: diagnostic, boolean (optional, default is False).\r\n OUTPUTS: None, All output is to the terminal screen.\r\n \"\"\"\r\n if type(self) == Player:\r\n if not diagnostic:\r\n print(f\"Player: {self.name}\")\r\n print(\"Remaining Bank: ${:,}\".format(self.bank))\r\n print(\"Cash Reserve: ${:,}\".format(self.reserve))\r\n print(f\"Skill Level: {self.skill_level}\")\r\n if self.insurance_bet:\r\n print(\"Insurance bet: {:,}\".format(self.insurance_bet))\r\n if self.hands['one'] is not None:\r\n print(self.hands['one'])\r\n if self.hands['two'] is not None:\r\n print(self.hands['two'])\r\n else: # This is a diagnostic printout.\r\n print(f\"Diagnostic printout for {self.name}\")\r\n print(\"Bank contains ${:,}, with a cash reserve of ${:,}.\".format(self.bank, self.reserve))\r\n print(f\"Skill level is {self.skill_level}.\")\r\n if self.total_bets:\r\n print(\"Player's bet total: ${:,}\".format(self.total_bets))\r\n else:\r\n print(\"Total bets has not been populated.\")\r\n if self.insurance_bet:\r\n print(\"Insurance bet: ${:,}\".format(self.insurance_bet))\r\n else:\r\n print(\"No insurance bet exists.\")\r\n print(\"Players hands are:\")\r\n if self.hands['one'] is not None:\r\n self.hands['one'].__str__(diagnostic=True)\r\n else:\r\n print(\"First hand does not exist.\")\r\n if self.hands['two'] is not None:\r\n self.hands['two'].__str__(diagnostic=True)\r\n else:\r\n print(\"Second hand does not exist.\")\r\n else: # This is a dealer.\r\n pass\r\n return \"\"\r\n\r\n def __len__(self):\r\n \"\"\"\r\n This method returns the number of remaining valid Hand objects that the\r\n Player object still has.\r\n INPUTS: None\r\n OUTPUTS: nunber of valid Hand objects, integer [0,2]\r\n \"\"\"\r\n # Initialize the counter.\r\n hand_ctr = 0\r\n # Increment the counter if the Hand exist and is not busted..\r\n if self.hands['one'] is not None:\r\n if not self.hands['one'].busted:\r\n hand_ctr += 1\r\n if self.hands['two'] is not None:\r\n if not self.hands['two'].busted:\r\n hand_ctr += 1\r\n # Return the value in the counter.\r\n return hand_ctr\r\n\r\n def __del__(self):\r\n \"\"\"\r\n This method warns the human player that one of their computer players,\r\n or the current dealer, has been removed from the current game.\r\n INPUTS: None\r\n OUTPUTS: None\r\n \"\"\"\r\n if type(self) == Player:\r\n print(f\"Player {self.name} has been removed from the game.\")\r\n else: # This is a Dealer object.\r\n print(f\"The Dealer, {self.name} has been removed from the game.\")\r\n\r\n def validate_bet(self, amt, table_max, table_min):\r\n \"\"\"\r\n This method takes a bet amount, table max, and table min, and makes the\r\n following comparisons, returning the codes as indicated:\r\n \"passed\" amt passed all of this methods tests\r\n \"high\" amt exceeds the table max\r\n \"low\" amt is below the table min\r\n \"bank\" amt + total bets exceeds the player's bank\r\n \"invalid\" table min + total bets exceeds the player's bank OR\r\n total bets = player's bank\r\n Note: This method can be used to check computer player validity using\r\n the form P.validate_bet(0, table_max, table_min). Any return other\r\n than \"passed\" indicates a character who cannot remain at the table.\r\n INPUTS: There are 3 inputs:\r\n amt (integer), required\r\n table_max (integer), required\r\n table_min (integer), required\r\n OUTPUTS: string, values \"passed\", \"high\", \"low\", \"bank\", or \"invalid\"\r\n \"\"\"\r\n # First, we need to pull Player.total_bets if it has been created.\r\n # If not, we need to set this method's bet_total to zero.\r\n if self.total_bets is None:\r\n bet_total = 0\r\n else:\r\n bet_total = self.total_bets\r\n # Next, we need to see if making this bet is even possible.\r\n if bet_total == self.bank:\r\n return \"invalid\"\r\n if (table_min + bet_total) > self.bank:\r\n return \"invalid\"\r\n # Next, we check to make sure that the amount of the bet will not\r\n # exceed the player's bank if all bets are lost.\r\n if (amt + bet_total) > self.bank:\r\n return \"bank\"\r\n # Next, we check the bet amount against the table_max. A zero\r\n # table_max will be ignored, since it makes the second test False.\r\n if amt > table_max > 0:\r\n return \"high\"\r\n # Next, we check the bet amount against the table_min. A zero\r\n # table_min will be ignored, since it makes the second test False.\r\n if table_min > amt > 0:\r\n return \"low\"\r\n # If it got to this point, amt passed all of this methods tests.\r\n return \"passed\"\r\n\r\n def create_hand(self, ante, table_max=0, table_min=0):\r\n \"\"\"\r\n This method creates an empty hand in Player.hands['one']. This is the\r\n computer player's regular hand. It requires an integer argument ante\r\n as an initial bet for this hand. This method checks calls\r\n Player.validate_bet to confirmed the following based on the return\r\n code from the validation:\r\n \"success\" bet amount has been updated with a valide amount\r\n \"high\" amt exceeds the table max\r\n \"low\" amt is below the table min\r\n \"bank\" amt + total bets exceeds the player's bank\r\n \"invalid\" table min + total bets exceeds the player's bank OR\r\n total bets = player's bank\r\n INPUTS: There are 3 inputs:\r\n amt (integer), required\r\n table_max (integer), optional, defaults to 0\r\n table_min (integer), optional, defaults to 0\r\n OUTPUTS: string, values \"success\", \"high\", \"low\", \"bank\", or \"invalid\"\r\n \"\"\"\r\n validation = self.validate_bet(ante, table_max, table_min)\r\n if validation == \"passed\":\r\n self.hands['one'] = Hand(ante)\r\n self.update_total_bets()\r\n return \"success\"\r\n else:\r\n return validation\r\n\r\n def create_split_hand(self, ante, which_hand, start_card):\r\n \"\"\"\r\n This method requires three arguments. It needs an ante, which can be\r\n the bet on the ariginal hand which now is a pair. It needs to know\r\n which of the two hands it is creating, the split hand in\r\n PLayer.hands['one'] or PLayer.hands['two']. It also needs a card from\r\n the pair being split up to make the first card in this new split hand.\r\n INPUTS: ante, integer (required), which_hand, string (required, must\r\n be either 'one' or 'two'), start_card, Card or Ace (required)\r\n OUTPUTS: none. All changes take place inside the Player object.\r\n Note: This method does not check the validity of the new ante amount.\r\n It relies on the calling method(s) to validate the amount before\r\n invoking this method.\r\n \"\"\"\r\n self.hands[which_hand] = SplitHand(start_card, ante)\r\n self.update_total_bets()\r\n\r\n def add_card_to_hand(self, card, which_hand='one'):\r\n \"\"\"\r\n This method adds a card to an existing hand. When split hands exist,\r\n this should be specified, as it defauled to 'one', the regular hand.\r\n This method returns True if the hand is still viable, False otherwise.\r\n INPUTS: card, a Card or Ace object (required), which_hand, string\r\n (optional, must be 'one' or 'two', defaults to 'one')\r\n OUTPUTS: boolean, True if the hand is still viable, False otherwise.\r\n This method also changes the hand and its attributes.\r\n \"\"\"\r\n self.hands[which_hand].receive_card(card)\r\n return not self.hands[which_hand].busted\r\n\r\n def split_check(self):\r\n \"\"\"\r\n This method checks to see if regular hand has a pair. It does it by\r\n returning the value of Player.hands['one'].has_pair. This method might\r\n not be needed for the text or the pygame versions.\r\n INPUTS: none, it uses the player object\r\n OUTPUTS: boolean, True of there is a pair, False otherwise\r\n \"\"\"\r\n if self.hands['one']:\r\n if type(self.hands['one']) == Hand:\r\n return self.hands['one'].has_pair\r\n # Either the first hand does not exist or the type is a subtype of\r\n # Hand object. So, had_pair is not an attribute. We need to default to\r\n # False.\r\n return False\r\n\r\n def split_hand(self, table_max=0, table_min=0):\r\n \"\"\"\r\n This method determines if the computer player can actually make another\r\n ante on a new hand first, using Player.validate_bet(). If \"invalid\" is\r\n returned, it warn the human player that no split hand be created due to\r\n the table min and the computer player's remaining bank. If it gets\r\n past that point, it will ask the human player if they want to split\r\n the pair that is showing into two hands. If not, it will return the\r\n code \"declined\". If so, the method coverts the pair into split hands.\r\n This method removes the original hand, separates the pair of cards,\r\n creates a new SplitHand in hands['one'] and copies over the original\r\n bet to that hand. Next, it takes the second card in the pair, prompts\r\n the User for a bet on this player's new split hand, and creates a new\r\n SplitHand from the second card and bet amount in the hands['two']\r\n position. It calls Player.validate_bet() to check the validity of the\r\n bet while interacting with the human player. If it is not possible\r\n INPUTS: two optional integers\r\n table_max (integer), optional (defaults to 0)\r\n table_min (integer), optional (defaults to 0)\r\n User is promppted for an integer value as a bet on the new split\r\n hand if the computer player can make such a bet.\r\n OUTPUTS: string with volues as follows:\r\n \"success\" the pair was split into two hands and both have bets\r\n \"declined\" the player declined to split the pair\r\n \"impossible\" the player's bank could not cover the table min for\r\n the new hand\r\n \"\"\"\r\n # First, we need to check to see if the computer player's bank has\r\n # enough money in it to cover the table minimum. We can do that using\r\n # the Player.validate_bet() method.\r\n result = self.validate_bet(0, table_max, table_min)\r\n if result == \"passed\":\r\n print(f\"Player {self.name} can cover a new bet for a split hand.\")\r\n else:\r\n print(f\"Player {self.name} cannot cover the bet for a split hand.\")\r\n return \"impossible\"\r\n # The computer player can cover a bet on the new hand. So, we need to\r\n # ask the human player if they want ot split the pair.\r\n answer = \"\"\r\n while answer not in ('y', 'n'):\r\n answer = input(\"Would you like to split the pair into new hands? (yes/no)\").lower()[0]\r\n if answer not in ('y', 'n'):\r\n print(\"Invalid response. Please answer yes/no or y/n.\")\r\n print(\"This game ignores copitalization\")\r\n continue\r\n elif answer == 'y':\r\n break\r\n else: # answer = 'n'\r\n print(\"Spilting the pair has been declined.\")\r\n return \"declined\"\r\n # The pair will be split into two hands. We need to extract the\r\n # following data from the original hand: the bet amount and both cards.\r\n orig_bet = self.hands['one'].bet_amt\r\n card_1 = self.hands['one'].cards[0]\r\n card_2 = self.hands['one'].cards[1]\r\n # Now, we need to create the first split hand.\r\n self.create_split_hand(orig_bet, 'one', card_1)\r\n # Before we can make the second split hand, we need a bet amount for\r\n # it. We will prompt the User for the amount, then run the method\r\n # Player.validate_bet() to make sure that the player's bet is not\r\n # incorrect.\r\n while True:\r\n # The human player may need a reminder of the table min and max, if\r\n # they exist. So, we will check for them and print reminders.\r\n if table_max != 0:\r\n print(f\"The maximum bet at this table is ${table_max}.\")\r\n else:\r\n print(\"There is no maximum bet at this table.\")\r\n if table_min != 0:\r\n print(f\"The minimum bet at this table is ${table_min}.\")\r\n else:\r\n print(\"There is no minimum bet at this table.\")\r\n new_bet = input(\"Please enter a bet for the new hand: \")\r\n # Since the User might enter a non-integer, we need to check the\r\n # data type.\r\n try:\r\n new_bet_amt = int(new_bet)\r\n except TypeError:\r\n print(f\"{new_bet} is not a number.\")\r\n continue\r\n else:\r\n # Now, we need to run Player.validate_bet() to see if this bet\r\n # is valid or not. The possible results are \"passed\", \"high\",\r\n # \"low\", \"bank\", or \"invalid\". \"invalid\" bets do not take the\r\n # new bet into consideration and were tested for at the\r\n # beginning of this method.\r\n result = self.validate_bet(new_bet_amt, table_max, table_min)\r\n if result == \"passed\":\r\n break\r\n elif result == 'high':\r\n print(f\"${new_bet_amt} is more than the table maximum bet.\")\r\n elif result == 'low':\r\n print(f\"${new_bet_amt} is less than the table minimum bet.\")\r\n elif result == 'bank':\r\n print(f\"${new_bet_amt} would overrun your available bank of ${self.bank}.\")\r\n # No other results are possible.\r\n # Since it got to this point, the bet amount needs to be reentered.\r\n print(\"Please try again.\")\r\n # Now that we are out of the while loop, We can create the second\r\n # split hand now. Then, we will update the total bets attribute.\r\n self.create_split_hand(new_bet_amt, 'two', card_2)\r\n self.update_total_bets()\r\n print(\"Your new split hand has been created.\")\r\n return \"success\"\r\n\r\n def update_total_bets(self):\r\n \"\"\"\r\n This method scans through the PLayer object, including the Hand objects\r\n it contains, looking for bets that exist. It tabulates all of the bets\r\n and updates the Player.tatal_bets attribute with new amount.\r\n INPUTS: none\r\n OUTPUTS: none\r\n \"\"\"\r\n # Initialize the bet total.\r\n bet_total = 0\r\n # First, we check the insurance bet, since it resides outside of the\r\n # Hand objects. Objects and attributes are set to None when they do not\r\n # exist.\r\n if self.insurance_bet:\r\n bet_total += self.insurance_bet\r\n # Now, we check each hand to see if it exists. If so, it must have a\r\n # bet attribute assigned to it.\r\n for hand in ('one', 'two'):\r\n if self.hands[hand] is not None:\r\n bet_total += self.hands[hand].bet_amt\r\n self.total_bets = bet_total\r\n\r\n def update_bet(self, amt, which_hand='one', table_max=0, table_min=0):\r\n \"\"\"\r\n This method validates the ammount that a bet has been raised. If it is\r\n an amount that meets the rules, it apply the change and return\r\n \"success\". It uses the method Player.validate_bet to determine if the\r\n raise amount causes any problems, returning the code it gets back\r\n generally. There is an extra check that it makes, determining if the\r\n raise is more than double the original bet amount, as this breaks the\r\n rules of blackjack.\r\n This method calls Player.validate_bet() to perform all, but the raise\r\n amount test.\r\n Note: Players cannot raise their bet on a given hand more than the\r\n original amount they anted up before the cards are dealt.\r\n Note: To test if the player can raise or make a bet currently, use\r\n the form Player.update_bet(0, hand, table_max, table_min).\r\n INPUTS: There are 3 inputs:\r\n amt (integer), required\r\n which_hand (string, 'one' or 'two'), optional, defaults to 'one'\r\n table_max (integer), optional, defaults to 0\r\n table_min (integer), optional, defaults to 0\r\n OUTPUTS: string, values are:\r\n \"success\" bet amount has been updated with a valid amount\r\n \"high\" amt + current bet exceeds the table max\r\n \"bet\" amt exceeds the original bet\r\n \"bank\" amt + total bets exceeds the player's bank\r\n \"invalid\" table min + total bets exceeds the player's bank OR\r\n total bets = player's bank\r\n \"\"\"\r\n raised_bet = amt + self.hands[which_hand].bet_amt\r\n # Player.validate_bet() generates the following return values:\r\n # \"passed\", \"high\", \"low\", \"bank\", or \"invalid\". This will cover most\r\n # of the conditions that we might run into. A \"low\" result is not\r\n # possible simply because the hand already had a valid bet on it before\r\n # the option to raise the bet came along. \"invalid\" is also not a\r\n # possible return because, again, there is a valid bet and \"invalid\"\r\n # would have prevented the play from getting this far.\r\n result = self.validate_bet(raised_bet, table_max, table_min)\r\n if result != \"passed\":\r\n return result\r\n # Now, it is possible that the player kept the value under the table\r\n # maximum, but it is still too high because it is more than double the\r\n # ante (original bet). Blackjack forbids that.\r\n if amt > self.hands[which_hand].bet_amt:\r\n return \"bet\"\r\n # Ok, the raise amt is valid. We need to add it to the original bet\r\n # for this hand and, then, recalculate PLayer.total_bets.\r\n self.hands[which_hand].bet_amt += amt\r\n self.update_total_bets()\r\n return \"success\"\r\n\r\n def create_insurance_bet(self, amt, table_max=0, table_min=0):\r\n \"\"\"\r\n Insurance bets are subject to the table max and min values, just like\r\n any other bet. So, we can use Player.validate_bet to check if this amt\r\n meets the criteria. The codes this method returns are the same as the\r\n ones it gets from Player.validate_bet() if the bet is a bad amount.\r\n INPUTS: There are 3 inputs:\r\n amt (integer), required\r\n table_max (integer), optional, defaults to 0\r\n table_min (integer), optional, defaults to 0\r\n OUTPUTS: string, values are as follows:\r\n \"success\" bet amount has been updated with a valide amount\r\n \"high\" amt exceeds the table max\r\n \"low\" amt is below the table min\r\n \"bank\" amt + total bets exceeds the player's bank\r\n \"invalid\" table min + total bets exceeds the player's bank OR\r\n total bets = player's bank\r\n \"\"\"\r\n result = self.validate_bet(amt, table_max, table_min)\r\n if result != \"passed\":\r\n return result\r\n else:\r\n self.insurance_bet = amt\r\n self.update_total_bets()\r\n return \"success\"\r\n\r\n def clear_hand(self, which_hand):\r\n \"\"\"\r\n This method checks to see if the specified hand exists. If so, it will\r\n attempt to set it None. Successful removal of the specified hand is\r\n returned via a code string. A nonexistent hand will return a code as\r\n well. An invalid hand choice also returns a code.\r\n Note: This method is needed for end_round().\r\n INPUTS: which_hand (string), valid values are 'one' or 'two', no\r\n default value\r\n OUTPUTS: string, values are as follows:\r\n 'missing' hand specified did not exist\r\n 'invalid' hand specified is not 'one' or 'two'\r\n 'success' hand was found and set to None\r\n \"\"\"\r\n if which_hand != 'one' or which_hand != 'two':\r\n return 'invalid'\r\n if self.hands[which_hand] is None:\r\n return 'missing'\r\n # Getting to this point means that the hand exists. We need to set it\r\n # to None.\r\n self.hands[which_hand] = None\r\n # A failure to reomve the hand should not happen, but we handle this\r\n # slim possibility just in case.\r\n if self.hands[which_hand] is None:\r\n return 'success'\r\n else:\r\n return 'failure'\r\n\r\n def end_round(self, table_min=0):\r\n \"\"\"\r\n This method clears the player objects hands, total_bets, and insurance\r\n bet (if any still exist). After that is done, this method calls the\r\n validate_bet(0, 0, table_min) to determine if the player can continue\r\n to the next round. If not, it returns False; if so, it returns True.\r\n INPUTS: table_min (integer), no default value\r\n OUTPUTS: boolean, True (player can continue), False (player will be\r\n eliminated if not withdrawn)\r\n Note: This method does not prompt the human player to perform any\r\n actions. Drawing from the player's reserve or withdrawing this\r\n player from the table is left to other code.\r\n \"\"\"\r\n for hand in ('one', 'two'):\r\n self.clear_hand(hand)\r\n # We do not need the codes here since we are simply clearing data.\r\n self.insurance_bet = None\r\n self.total_bets = 0\r\n # All of these attributes have been reset. Now, we need to check the\r\n # validity of the player. Player.validate_bet() has a form that will\r\n # return 'passed' or 'invalid' if the player cannot meet table mins.\r\n if self.validate_bet(0, 0, table_min) == 'passed':\r\n return True\r\n else:\r\n return False\r\n"} {"blob_id": "d48c8557fcffe93d8453b64aad9112cc0871586a", "repo_name": "alieu93/Comp-Simulation-Assignments", "path": "/Assignment 1/Assign1_Part2A.py", "length_bytes": 2179, "score": 3.796875, "int_score": 4, "content": "#Name: Adam Lieu\r\n#Student ID: 100451790\r\n#Description:\r\n#Part 2A of Assignment 1, simulate the spread of an infectious disease\r\n\r\n# Constant Spread Rate: 0.15\r\n# Fatality rate: 0.025\r\n# Recovery rate: 0.15\r\n\r\nimport itertools as it\r\nimport numpy as np\r\nimport scipy as sp\r\nimport pylab as pl\r\nimport matplotlib.pyplot as plt\r\nimport random\r\n\r\ndef simulateDay(numContacts, numInfected, numPeople):\r\n #For each susceptible person (not infected, dead, or recovered)\r\n #infectionRate = spreadProb * numContacts * numInfected / numPeople\r\n #For each infected person:\r\n #deathProb should be something between 1 and 0\r\n #Return:\r\n # - Number of fatalities\r\n # - Number of infected people\r\n # - Number of Recovered people\r\n # - Number of Susceptible people\r\n\r\n #numContacts - Times a typical person come into contact with people\r\n #numPeople - total population\r\n\r\n spreadProb = 0.15\r\n deathProb = 0.025\r\n recoverProb = 0.15\r\n\r\n numRecovered = 0\r\n numDeath = 0\r\n\r\n #Simulate if the susceptible person becomes infected\r\n infectionRate = (spreadProb * numContacts * numInfected) / numPeople\r\n print infectionRate\r\n\r\n #Number of susceptible people\r\n numOfSusPeople = numPeople - numInfected\r\n #rand = random.random()\r\n\r\n #Simulate if suspectible person gets infected or not\r\n\r\n for i in range(numOfSusPeople):\r\n rand = random.random()\r\n if rand < infectionRate:\r\n numInfected += 1\r\n numOfSusPeople -= 1\r\n\r\n\r\n\r\n #Simulate if infected person recovers or dies\r\n for i in range(numInfected):\r\n rand = random.random()\r\n if rand < deathProb:\r\n # patient dies\r\n numPeople -= 1\r\n numInfected -= 1\r\n numDeath += 1\r\n else:\r\n if rand < recoverProb:\r\n # patient recovers\r\n numInfected -= 1\r\n numRecovered += 1\r\n\r\n return numDeath, numInfected, numRecovered, numOfSusPeople\r\n\r\n\r\nD, I, R, S = simulateDay(5, 20, 100)\r\n\r\nprint \"deaths:\"\r\nprint D\r\nprint \"infected:\"\r\nprint I\r\nprint \"recovered:\"\r\nprint R\r\nprint \"susceptible:\"\r\nprint S\r\nprint \"check:\"\r\nprint D + I + R + S"} {"blob_id": "46524b7a879e5b13645253a624f0f446039d4e33", "repo_name": "superMC5657/leetcode-py", "path": "/dfs/117.py", "length_bytes": 2981, "score": 4.03125, "int_score": 4, "content": "# -*- coding: utf-8 -*-\n# !@time: 2020-10-16 13:48:17\n# !@author: superMC @email: 18758266469@163.com\n# !@question title: populating-next-right-pointers-in-each-node-ii\n\n# \u7ed9\u5b9a\u4e00\u4e2a\u4e8c\u53c9\u6811 \n# \n# struct Node {\n# int val;\n# Node *left;\n# Node *right;\n# Node *next;\n# } \n# \n# \u586b\u5145\u5b83\u7684\u6bcf\u4e2a next \u6307\u9488\uff0c\u8ba9\u8fd9\u4e2a\u6307\u9488\u6307\u5411\u5176\u4e0b\u4e00\u4e2a\u53f3\u4fa7\u8282\u70b9\u3002\u5982\u679c\u627e\u4e0d\u5230\u4e0b\u4e00\u4e2a\u53f3\u4fa7\u8282\u70b9\uff0c\u5219\u5c06 next \u6307\u9488\u8bbe\u7f6e\u4e3a NULL\u3002 \n# \n# \u521d\u59cb\u72b6\u6001\u4e0b\uff0c\u6240\u6709 next \u6307\u9488\u90fd\u88ab\u8bbe\u7f6e\u4e3a NULL\u3002 \n# \n# \n# \n# \u8fdb\u9636\uff1a \n# \n# \n# \u4f60\u53ea\u80fd\u4f7f\u7528\u5e38\u91cf\u7ea7\u989d\u5916\u7a7a\u95f4\u3002 \n# \u4f7f\u7528\u9012\u5f52\u89e3\u9898\u4e5f\u7b26\u5408\u8981\u6c42\uff0c\u672c\u9898\u4e2d\u9012\u5f52\u7a0b\u5e8f\u5360\u7528\u7684\u6808\u7a7a\u95f4\u4e0d\u7b97\u505a\u989d\u5916\u7684\u7a7a\u95f4\u590d\u6742\u5ea6\u3002 \n# \n# \n# \n# \n# \u793a\u4f8b\uff1a \n# \n# \n# \n# \u8f93\u5165\uff1aroot = [1,2,3,4,5,null,7]\n# \u8f93\u51fa\uff1a[1,#,2,3,#,4,5,7,#]\n# \u89e3\u91ca\uff1a\u7ed9\u5b9a\u4e8c\u53c9\u6811\u5982\u56fe A \u6240\u793a\uff0c\u4f60\u7684\u51fd\u6570\u5e94\u8be5\u586b\u5145\u5b83\u7684\u6bcf\u4e2a next \u6307\u9488\uff0c\u4ee5\u6307\u5411\u5176\u4e0b\u4e00\u4e2a\u53f3\u4fa7\u8282\u70b9\uff0c\u5982\u56fe B \u6240\u793a\u3002 \n# \n# \n# \n# \u63d0\u793a\uff1a \n# \n# \n# \u6811\u4e2d\u7684\u8282\u70b9\u6570\u5c0f\u4e8e 6000 \n# -100 <= node.val <= 100 \n# \n# \n# \n# \n# \n# \n# Related Topics \u6811 \u6df1\u5ea6\u4f18\u5148\u641c\u7d22 \n# \ud83d\udc4d 306 \ud83d\udc4e 0\nimport collections\nfrom typing import List\n\n\ndef createtree(l):\n if l[0]:\n root = Node(l[0])\n nodes = [root]\n id = 1\n while nodes and id < len(l):\n node = nodes[0] # \u4f9d\u6b21\u4e3a\u6bcf\u4e2a\u8282\u70b9\u5206\u914d\u5b50\u8282\u70b9\n node.left = Node(l[id]) if l[id] else None\n nodes.append(node.left)\n node.right = Node(l[id + 1]) if id < len(l) - 1 and l[id + 1] else None\n nodes.append(node.right)\n id += 2 # \u6bcf\u6b21\u53d6\u51fa\u4e24\u4e2a\u8282\u70b9\n nodes.pop(0)\n return root\n else:\n return None\n\n\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\n# leetcode submit region begin(Prohibit modification and deletion)\n\"\"\"\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\n\nclass Solution:\n def connect(self, root: 'Node') -> 'Node':\n if not root:\n return None\n queue = [root]\n while queue:\n next_queue = []\n for i in range(len(queue)):\n if queue[i].left:\n next_queue.append(queue[i].left)\n if queue[i].right:\n next_queue.append(queue[i].right)\n if i == len(queue) - 1:\n queue[i].next = None\n else:\n queue[i].next = queue[i + 1]\n queue = next_queue\n return root\n\n\n# leetcode submit region end(Prohibit modification and deletion)\nl = [1, 2, 3, 4, 5, None, 7]\nroot = createtree(l)\nSolution().connect(root)\n"} {"blob_id": "cc9b10d3099686db8426b09c877069717dc48fea", "repo_name": "MarcoDSilva/MIT6001x-Introduction-to-Computer-Science-and-Programming-in-Python", "path": "/week2/payingDebtBisectionSearch.py", "length_bytes": 1629, "score": 3.890625, "int_score": 4, "content": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jun 15 15:07:34 2020\n\nwrite a program that calculates the minimum fixed monthly payment needed \nin order pay off a credit card balance within 12 months\nwith Bisection Search to make the program faster\n\n@author: MarcoSilva\n\"\"\"\n\n#this function isn't needed per se, but for clarity I prefer to use it\ndef roundNum(num):\n ''' \n num : int or float\n returns: float w 2 decimal case number.\n '''\n return round(num, 2)\n\n#these 2 variables are used by the tester\nbalance = 320000\nannualInterestRate = 0.2\n\nmonthly_interest = (annualInterestRate) / 12.0\nlower_bound = roundNum(balance / 12)\nupper_bound = roundNum((balance * ((1 + monthly_interest) * 12)) / 12.0)\n\nmin_payment = roundNum((lower_bound + upper_bound / 2))\nfound = True\n\n#we loop 'til we find the value in the margin specified (0.1 in this case)\nwhile(found):\n temp_balance = balance \n \n # calculate the balance after the payment and the interest\n for month in range(1,13):\n temp_balance -= min_payment\n temp_balance += (monthly_interest * temp_balance)\n \n # if the balance is negative or positive (higher than our margin)\n # we specify new values to the bounds\n if temp_balance < 0.1:\n upper_bound = min_payment\n elif temp_balance > 0.1:\n lower_bound = min_payment \n \n # if both bounds are below our margin, we found the minimum value required\n # to pay the debt in 1 year\n if abs(upper_bound - lower_bound) <= 0.01:\n break\n \n min_payment = roundNum((lower_bound + upper_bound) / 2)\n\nprint('Lowest Payment: ' + str(min_payment))"} {"blob_id": "28392b79fdf48638e99764e6a5fa8b5096136be5", "repo_name": "uchenna-j-edeh/dailly_problems", "path": "/sorting_algorithm/heap_sort.py", "length_bytes": 1096, "score": 3.703125, "int_score": 4, "content": "\"\"\"\nGiven the following arrays, write a heapsort algo to sort it\nA = [9, 1, 5, 6, 3, 4, 9, 0, 20]\n\"\"\"\nclass HeapSort:\n def __init__(self):\n self.arr = [-1]\n self.idx = 0\n\n def add_node(self, elem):\n if self.idx == 1: # build root\n self.arr.append(elem)\n self.idx = self.idx + 1\n return\n\n self.idx = self.idx + 1\n self.arr.append(elem)\n self.add_node_helper( self.idx)\n\n def add_node_helper(self, i):\n if i == 1:\n return\n\n p_index = 0\n if i % 2:\n p_index = (i - 1) // 2\n else:\n p_index = i // 2\n\n print(\"parent index is \", i, self.arr, p_index)\n if self.arr[p_index] < self.arr[i]:\n self.arr[p_index], self.arr[i] = self.arr[i], self.arr[p_index]\n self.add_node_helper(p_index)\n return\n\n def find_max(self):\n max_index = self.arr[1]\n self.arr[i]\n self.idx = self.idx - 1\n\n\n \n \n\nA = [9, 1, 5, 6, 3, 4, 9, 0, 20]\n\nHS = HeapSort()\nfor i in A:\n HS.add_node(i)\n\nprint(HS.arr)\n\n"} {"blob_id": "c610229f48a6a0405161d7da695484b1adb18f6c", "repo_name": "tonyli1121/Project_euler_scripts", "path": "/27._Quadratic_primes.py", "length_bytes": 672, "score": 3.578125, "int_score": 4, "content": "#15mins\r\nimport time\r\nfrom math import sqrt\r\n\r\ndef is_prime(num):\r\n if num<0:\r\n return False\r\n for x in range(2,int(sqrt(num)+1)):\r\n if num%x==0:\r\n return False\r\n return True\r\n\r\nstart = time.time()\r\n\r\nans = 1\r\nlongest = 0\r\n\r\n\r\nfor b in range(-1000,1001):\r\n if b>-41 and b<41:\r\n continue\r\n elif not is_prime(abs(b)):\r\n continue\r\n for a in range(-999,1000):\r\n n = 0\r\n length = 0\r\n while is_prime((n**2)+(a*n)+b):\r\n length+=1\r\n n+=1\r\n if length > longest:\r\n longest = length\r\n ans = a*b\r\n\r\n \r\nprint(ans)\r\n\r\nprint(time.time() - start)\r\n"} {"blob_id": "d1c9d0dcc0b3d87ef5d5f69a995d9a254bb82054", "repo_name": "jerry-git/pychoir", "path": "/pychoir/logical.py", "length_bytes": 3160, "score": 3.5625, "int_score": 4, "content": "from typing import Any, Callable\n\nfrom pychoir.core import Matchable, Matcher\n\n\nclass And(Matcher):\n \"\"\"A Matcher checking that the compared value matches *all* the passed :class:`Matchable` s.\n\n :param matchers: The value(s) and/or matcher(s) to compare against.\n\n Usage:\n >>> from pychoir import And, IsInstance, HasLength, StartsWith\n >>> 5 == And(IsInstance(int), 5)\n True\n >>> 'abc' == And(StartsWith('a'), HasLength(3))\n True\n >>> 4 == And(IsInstance(int), 5)\n False\n \"\"\"\n def __init__(self, *matchers: Matchable):\n super().__init__()\n self.matchers = matchers\n\n def _matches(self, other: Any) -> bool:\n return all(self.nested_match(matcher, other) for matcher in self.matchers)\n\n def _description(self) -> str:\n return ', '.join(map(repr, self.matchers))\n\n\nAllOf = And\n\n\nclass Or(Matcher):\n \"\"\"A Matcher checking that the compared value matches *at least one of* the passed :class:`Matchable` s.\n\n :param matchers: The value(s) and/or matcher(s) to compare against.\n\n Usage:\n >>> from pychoir import Or, IsInstance, StartsWith\n >>> 5 == Or(IsInstance(int), 5)\n True\n >>> 'abc' == Or(StartsWith('abc'), StartsWith('def'))\n True\n >>> '4' == Or(IsInstance(int), 5)\n False\n \"\"\"\n def __init__(self, *matchers: Matchable):\n super().__init__()\n self.matchers = matchers\n\n def _matches(self, other: Any) -> bool:\n return any(self.nested_match(matcher, other) for matcher in self.matchers)\n\n def _description(self) -> str:\n return ', '.join(map(repr, self.matchers))\n\n\nAnyOf = Or\n\n\nclass Not(Matcher):\n \"\"\"A Matcher checking that the compared value matches *none of* the passed :class:`Matchable` s.\n\n :param matchers: The value(s) and/or matcher(s) to compare against.\n\n Usage:\n >>> from pychoir import Not, IsInstance, StartsWith\n >>> 5 == Not(IsInstance(str))\n True\n >>> 'abc' == Not(StartsWith('abc'), StartsWith('def'))\n False\n >>> 4 == Not(IsInstance(str), 5)\n True\n \"\"\"\n def __init__(self, *matchers: Matchable):\n super().__init__()\n self.matchers = matchers\n\n def _matches(self, other: Any) -> bool:\n return not any(self.nested_match(matcher, other, expect_mismatch=True) for matcher in self.matchers)\n\n def _description(self) -> str:\n return ', '.join(map(repr, self.matchers))\n\n\nIsNoneOf = Not\n\n\nclass ResultsTrueFor(Matcher):\n \"\"\"A Matcher checking that the compared value results :code:`True` when given to the passed function(s).\n\n :param conditions: The functions to check against.\n\n Usage:\n >>> from pychoir import ResultsTrueFor\n >>> 5 == ResultsTrueFor(bool)\n True\n >>> 'abc' == ResultsTrueFor(lambda x: x[2] == 'c')\n True\n \"\"\"\n def __init__(self, *conditions: Callable[[Any], bool]):\n super().__init__()\n self.conditions = conditions\n\n def _matches(self, other: Any) -> bool:\n return all(condition(other) for condition in self.conditions)\n\n def _description(self) -> str:\n return ', '.join(map(repr, self.conditions))\n"} {"blob_id": "38138acf432b99c3c9d2732374534fb4e23b57d2", "repo_name": "Benign/DataStructure", "path": "/07AVL/AVL_python.py", "length_bytes": 39175, "score": 3.546875, "int_score": 4, "content": "#\uc790\ub8cc\uad6c\uc870 \ud55c\uc625\uc601 \uad50\uc218\ub2d8 11\uc8fc\ucc28 \uc2e4\uc2b5\uacfc\uc81c\n#23 \ud2b8\ub9ac ADT \uc2e4\uc2b5 \uacfc\uc81c\n#\ucd5c\uc885 \uc791\uc131\uc77c: 2020.05.31(\uc77c)\n#2019312481 \uc2ec\uaddc\ud604\n\n#\uc124\uba85\ud574\uc8fc\uc2e0\ub300\ub85c \uc704\ub85c \uacc4\uc18d \ub9cc\ub4e4\uc5b4\ub098\uac00\ub294 \ubc29\uc2dd\uc774 \uc544\ub2c8\ub77c, \ub8e8\ud2b8 \ub178\ub4dc\uc77c \uacbd\uc6b0\ub97c \ub530\ub85c \ubd84\ub9ac\ud558\uc5ec\n#\uc790\uc2dd \ub178\ub4dc\ub4e4\uc744 \u007f\uc870\uc815\ud558\ub294 \ubc29\uc2dd\uc73c\ub85c \uad6c\ud604\ud558\uc600\uc2b5\ub2c8\ub2e4. \uc2e4\ud589 \uacb0\uacfc\uc758 \ucc28\uc774\ub294 \uc5c6\uc2b5\ub2c8\ub2e4.\n\nclass Node:\n def __init__(self, value, height, parent=None): #\uc0dd\uc131\uc790\n self.type = 2 #type 2\uba74 \uac12 1\uac1c \uc790\uc2dd 2\uac1c, type 3\uc774\uba74 \uac12 2\uac1c \uc790\uc2dd 3\uac1c\n self.data = [value, None, None] #\ucd5c\ub300 3\uac1c\uc758 data (\ub098\ub204\uae30 \uc804)\n self.child = [None, None, None, None] #\ucd5c\ub300 4\uac1c\uc758 \uc790\uc2dd\ub178\ub4dc (\ub098\ub204\uae30 \uc804)\n self.height = height\n self.parent = parent\n\n def push(self, data): #\uc774\ubbf8 \uc874\uc7ac\ud558\ub294 \ub178\ub4dc\uc5d0 \ub370\uc774\ud130 \ub123\uae30\n if data == None:\n return\n if self.type == 2:\n self.type = 3\n if self.data[0] == None:\n self.data[0] = data\n else:\n self.data[0], self.data[1] = sorted([data, self.data[0]])\n elif self.type == 3:\n self.type = 4\n if self.data[1] == None:\n self.data[0], self.data[1] = sorted([data, self.data[0]])\n else:\n self.data[0], self.data[1], self.data[2] = sorted([data, self.data[0], self.data[1]])\n\n def split(self): #\ub178\ub4dc\ub97c \ub098\ub220\uc57c \ud558\ub294 \uacbd\uc6b0. \ud55c \ub178\ub4dc\uc5d0 \uac12\uc774 3\uac1c \uc774\uc0c1\uc77c\ub54c \uc2e4\ud589\ub428.\n if self.type == 2 or self.type == 3: #\ub098\ub20c \ud544\uc694 \uc5c6\uc74c\n return\n if self.parent == None: #\ub8e8\ud2b8 \ub178\ub4dc\uc778 \uacbd\uc6b0 (\ubd80\ubaa8\ub178\ub4dc \uc5c6\ub294 \uacbd\uc6b0)\n lChild = Node(self.data[0], (self.height)+1, self)\n rChild = Node(self.data[2], (self.height)+1, self)\n lChild.child[0], lChild.child[1] = self.child[0], self.child[1]\n rChild.child[0], rChild.child[1] = self.child[2], self.child[3]\n if lChild.child[0] != None:\n lChild.child[0].parent = lChild\n if lChild.child[1] != None:\n lChild.child[1].parent = lChild\n if rChild.child[0] != None:\n rChild.child[0].parent = rChild\n if rChild.child[1] != None:\n rChild.child[1].parent = rChild\n self.type = 2\n self.data[0], self.data[1], self.data[2] = self.data[1], None, None\n self.child[0], self.child[1], self.child[2], self.child[3] = lChild, rChild, None, None\n if self.child[0] != None:\n self.child[0].parent = self\n if self.child[1] != None:\n self.child[1].parent = self\n \n elif self.parent.type == 2: #\ubd80\ubaa8\ub178\ub4dc\uac00 \uac12\uc774 \ud558\ub098\uc778 \uacbd\uc6b0\n if self == self.parent.child[0]: #\uc67c\ucabd \uc790\uc2dd\uc778 \uacbd\uc6b0\n mChild = Node(self.data[2], self.height, self.parent) #\uac00\uc6b4\ub370 \uc790\uc2dd \uc0dd\uc131\n mChild.child[0], mChild.child[1] = self.child[2], self.child[3]\n if mChild.child[0] != None:\n mChild.child[0].parent = mChild\n if mChild.child[1] != None:\n mChild.child[1].parent = mChild\n self.parent.push(self.data[1]) #\uac00\uc6b4\ub370 \uac12\uc740 \uc62c\ub824\ubcf4\ub0b4\uae30\n self.parent.child[0], self.parent.child[1], self.parent.child[2] = self.parent.child[0], mChild, self.parent.child[1]\n self.type = 2\n self.child[0], self.child[1], self.child[2], self.child[3] = self.child[0], self.child[1], None, None\n if self.child[0] != None:\n self.child[0].parent = self\n if self.child[1] != None:\n self.child[1].parent = self\n self.data[0], self.data[1], self.data[2] = self.data[0], None, None\n \n elif self == self.parent.child[1]:\n mChild = Node(self.data[0], self.height, self.parent)\n mChild.child[0], mChild.child[1] = self.child[0], self.child[1]\n if mChild.child[0] != None:\n mChild.child[0].parent = mChild\n if mChild.child[1] != None:\n mChild.child[1].parent = mChild\n self.parent.push(self.data[1])\n self.parent.child[0], self.parent.child[1], self.parent.child[2] = self.parent.child[0], mChild, self.parent.child[1]\n self.type = 2\n self.child[0], self.child[1], self.child[2], self.child[3] = self.child[2], self.child[3], None, None\n if self.child[0] != None:\n self.child[0].parent = self\n if self.child[1] != None:\n self.child[1].parent = self\n self.data[0], self.data[1], self.data[2] = self.data[2], None, None\n \n elif self.parent.type == 3:\n if self == self.parent.child[0]: #\uac00\uc7a5 \uc67c\ucabd \uc790\uc2dd\n newNode = Node(self.data[2], self.height, self.parent) #\uc81c\uc77c \ud070 \uac12 \uc8fc\uae30\n newNode.child[0], newNode.child[1] = self.child[2], self.child[3]\n if newNode.child[0] != None:\n newNode.child[0].parent = newNode\n if newNode.child[1] != None:\n newNode.child[1].parent = newNode\n self.parent.push(self.data[1])\n self.parent.child[0], self.parent.child[1], self.parent.child[2], self.parent.child[3] = self.parent.child[0], newNode, self.parent.child[1], self.parent.child[2]\n self.type = 2\n self.child[0], self.child[1], self.child[2], self.child[3] = self.child[0], self.child[1], None, None\n if self.child[0] != None:\n self.child[0].parent = self\n if self.child[1] != None:\n self.child[1].parent = self\n self.data[0], self.data[1], self.data[2] = self.data[0], None, None\n \n elif self == self.parent.child[1]: #\uac00\uc6b4\ub370 \uc790\uc2dd\n newNode = Node(self.data[2], self.height, self.parent) #\uc81c\uc77c \ud070 \uac12 \uc8fc\uae30\n newNode.child[0], newNode.child[1] = self.child[2], self.child[3]\n if newNode.child[0] != None:\n newNode.child[0].parent = newNode\n if newNode.child[1] != None:\n newNode.child[1].parent = newNode\n self.parent.push(self.data[1])\n self.parent.child[0], self.parent.child[1], self.parent.child[2], self.parent.child[3] = self.parent.child[0], self.parent.child[1], newNode, self.parent.child[2]\n self.type = 2\n self.child[0], self.child[1], self.child[2], self.child[3] = self.child[0], self.child[1], None, None\n if self.child[0] != None:\n self.child[0].parent = self\n if self.child[1] != None:\n self.child[1].parent = self\n self.data[0], self.data[1], self.data[2] = self.data[0], None, None\n \n elif self == self.parent.child[2]: #\uac00\uc7a5 \uc624\ub978\ucabd \uc790\uc2dd\n newNode = Node(self.data[0], self.height, self.parent) #\uc81c\uc77c \uc791\uc740 \uac12 \uc8fc\uae30\n newNode.child[0], newNode.child[1] = self.child[2], self.child[3]\n if newNode.child[0] != None:\n newNode.child[0].parent = newNode\n if newNode.child[1] != None:\n newNode.child[1].parent = newNode\n self.parent.push(self.data[1])\n self.parent.child[0], self.parent.child[1], self.parent.child[2], self.parent.child[3] = self.parent.child[0], self.parent.child[1], newNode, self.parent.child[2]\n self.type = 2\n self.child[0], self.child[1], self.child[2], self.child[3] = self.child[2], self.child[3], None, None\n if self.child[0] != None:\n self.child[0].parent = self\n if self.child[1] != None:\n self.child[1].parent = self\n self.data[0], self.data[1], self.data[2] = self.data[2], None, None\n \n \n def insert(self, data):\n if data == None:\n return\n if self.child[0] == None: #\uc790\uc2dd \uc5c6\uc74c = \ub9ac\ud504\ub178\ub4dc\n self.push(data)\n self.split()\n \n elif self.type == 2:\n if data < self.data[0]:\n self.child[0].insert(data)\n else:\n self.child[1].insert(data)\n \n elif self.type == 3:\n if data < self.data[0]:\n self.child[0].insert(data)\n elif data > self.data[1]:\n self.child[2].insert(data)\n else:\n self.child[1].insert(data)\n\n def insertVal(self, data):\n if data == None:\n return\n self.push(data)\n self.split()\n \n def find(self, data, mode): #mode 1\uc774\uba74 \ucd9c\ub825\n if self.child[0] == None: #\uc790\uc2dd \uc5c6\uc74c = \ub9ac\ud504\ub178\ub4dc\n if data in self.data:\n return self\n else:\n return None\n \n elif self.type == 2:\n if data in self.data:\n return self\n elif data < self.data[0]:\n if mode == 1:\n print(\"-Left\", end=\"\")\n return self.child[0].find(data, mode)\n else:\n if mode == 1:\n print(\"-Right\", end=\"\")\n return self.child[1].find(data, mode)\n \n elif self.type == 3:\n if data in self.data:\n return self\n elif data < self.data[0]:\n if mode == 1:\n print(\"-Left\", end=\"\")\n return self.child[0].find(data, mode)\n elif data > self.data[1]:\n if mode == 1:\n print(\"-Middle\", end=\"\")\n return self.child[2].find(data, mode)\n else:\n if mode == 1:\n print(\"-Right\", end=\"\")\n return self.child[1].find(data, mode)\n\n def check(self):\n if self.type == 4:\n self.split()\n return\n else:\n return\n \n def deleteValue(self, target):\n if self.data[0] == target:\n self.data[0], self.data[1], self.data[2] = self.data[1], self.data[2], None\n elif self.data[1] == target:\n self.data[0], self.data[1], self.data[2] = self.data[0], self.data[2], None\n if self.type == 3:\n if self.data[2] == target:\n self.data[2] = None\n \nclass TTT: #two-three tree\n def __init__(self): #\uc0dd\uc131\uc790\n self.root = None\n \n def is_empty(self):\n if self.root == None:\n return True\n else:\n return False\n \n def searchValue(self, target, mode):\n if self.is_empty() == True:\n return None\n else:\n return self.root.find(target, mode)\n\n def isNode(self, target):\n tmp = Node(None, 0)\n tmp = self.searchValue(target, 0)\n if tmp is None:\n return False\n else:\n return True\n\n def checkTree(self):\n if self.is_empty() == True:\n return\n sub_tree1 = TTT()\n sub_tree2 = TTT()\n sub_tree3 = TTT()\n sub_tree1.root = self.root.child[0]\n sub_tree2.root = self.root.child[1]\n sub_tree3.root = self.root.child[2]\n self.root.check()\n if (sub_tree1.root == None) and (sub_tree2.root == None) and (sub_tree3.root == None):\n return\n if sub_tree1.root != None:\n sub_tree1.checkTree()\n if sub_tree2.root != None:\n sub_tree2.checkTree()\n if sub_tree3.root != None:\n sub_tree3.checkTree()\n self.root.check()\n\n def InsertNode(self, data):\n if self.is_empty() == True:\n self.root = Node(data, 0)\n elif self.isNode(data) == True: #\ud574\ub2f9 \uac12\uc744 \uac00\uc9c4 \ub178\ub4dc\uac00 \uc774\ubbf8 \uc874\uc7ac\n print(\"ERROR: Two Three Tree Cannot Have 2 Nodes With Same Value.\")\n return\n else:\n self.root.insert(data)\n self.checkTree()\n\n def printTree(self):\n if(self.root is None):\n print(\"Tree is Empty.\", end=\"\")\n return\n sub_tree1 = TTT()\n sub_tree2 = TTT()\n sub_tree3 = TTT()\n if self.root.type == 2: #\uac12 1\uac1c, \uc790\uc2dd 2\uac1c\n print(\"%d\"%(self.root.data[0]), end=\"\")\n sub_tree1.root = self.root.child[0]\n sub_tree2.root = None\n sub_tree3.root = self.root.child[1]\n else: #\uac12 2\uac1c, \uc790\uc2dd 3\uac1c\n print(\"(%d,%d)\"%(self.root.data[0], self.root.data[1]), end=\"\")\n sub_tree1.root = self.root.child[0]\n sub_tree2.root = self.root.child[1]\n sub_tree3.root = self.root.child[2]\n if (sub_tree1.root == None) and (sub_tree2.root == None) and (sub_tree3.root == None):\n return\n print(\"(\",end=\"\")\n print(\"(\",end=\"\")\n if sub_tree1.root != None and sub_tree1.root.data[0] != None:\n sub_tree1.printTree()\n print(\")\",end=\"\")\n print(\"(\",end=\"\")\n if sub_tree2.root != None and sub_tree2.root.data[0] != None:\n sub_tree2.printTree()\n print(\")\",end=\"\")\n print(\"(\",end=\"\")\n if sub_tree3.root != None and sub_tree3.root.data[0] != None:\n sub_tree3.printTree()\n print(\")\",end=\"\")\n print(\")\",end=\"\")\n return\n \n def fixNodeAfterDelete(self, node, parent):\n if node.data[0] != None: #\uac12\uc774 \uae30\uc874\uc5d0 \ub450\uac1c \uc774\uc0c1\uc774\uc5c8\uc73c\uba74 \uc218\uc815 \ubd88\ud544\uc694\n if node.data[1] == None:\n node.type = 2\n return\n if parent != None: #\ub8e8\ud2b8 \ub178\ub4dc \uc544\ub2cc \uacbd\uc6b0\n sib, lS, rS, mlS, mrS = None, None, None, None, None\n if (node and node.parent) != None: #leftSibling, rightSibling, mostleftSibling, mostrightSibling \uad6c\ud558\uae30\n if node.parent.type == 2:\n if node == parent.child[0]:\n rS = parent.child[1]\n else:\n lS = parent.child[0]\n elif node.parent.type == 3:\n if node == parent.child[0]:\n rS = parent.child[1]\n mrS = parent.child[2]\n elif node == parent.child[1]:\n lS = parent.child[0]\n rS = parent.child[2]\n else:\n mlS = parent.child[0]\n lS = parent.child[1]\n \n redistribute = True\n if lS != None or rS != None:\n if rS != None and (rS.type == 3 or (rS.type == 2 and mrS != None and mrS.type == 3)):\n sib = rS\n elif lS != None and (lS.type == 3 or (lS.type == 2 and mlS != None and mlS.type == 3)):\n sib = lS\n elif lS != None and lS.type == 2:\n sib = lS\n redistribute = False\n elif rS != None and rS.type == 2:\n sib = rS\n redistribute = False\n \n if redistribute == True: #redistritube \ud558\ub294 \uacbd\uc6b0\n if sib == lS: #\uc67c\ucabd \ud615\uc81c\n index = 0\n if node == parent.child[0]:\n index = 0\n elif node == parent.child[1]:\n index = 1\n elif parent.type == 3 and node == parent.child[2]:\n index = 2\n node.data[0] = parent.data[index-1]\n node.child[1], node.child[2] = node.child[0], node.child[1]\n node.child[0] = sib.child[2]\n sib.child[2] = None\n if node.child[0] != None:\n node.child[0].parent = node\n parent.data[index-1] = sib.data[1]\n sib.data[1] = None\n elif sib == rS: #\uc624\ub978\ucabd \ud615\uc81c\n index = 0\n if node == parent.child[0]:\n index = 0\n elif node == parent.child[1]:\n index = 1\n elif parent.type == 3 and node == parent.child[2]:\n index = 2\n node.data[0] = parent.data[index]\n node.child[1] = sib.child[0]\n sib.child[0], sib.child[1] = sib.child[1], sib.child[2]\n if node.child[1] != None:\n node.child[1].parent = node\n parent.data[index] = sib.data[0]\n sib.data[0] = sib.data[1]\n sib.data[1] = None\n \n next_node = sib\n\n else: #merge \ud558\ub294 \uacbd\uc6b0\n if parent.type == 2:\n p_val = parent.data[0]\n else:\n if sib == parent.child[0]:\n p_val = parent.data[0]\n elif sib == parent.child[1]:\n if sib == rS:\n p_val = parent.data[0]\n if sib == lS:\n p_val = parent.data[parent.type - 2]\n child = node.child[0]\n sib.insertVal(p_val)\n parent.deleteValue(p_val)\n \n if node == parent.child[0]:\n parent.child[0], parent.child[1], parent.child[2], parent.child[3] = parent.child[1], parent.child[2], parent.child[3], None\n elif node == parent.child[1]:\n parent.child[1], parent.child[2], parent.child[3] = parent.child[2], parent.child[3], None\n elif node == parent.child[2]:\n parent.child[2], parent.child[3] = parent.child[3], None\n elif node == parent.child[3]:\n parent.child[3] = None\n if parent.type == 3:\n parent.type = 2\n \n if node.child[0] != None:\n if child != None:\n index = 0\n if sib.child is None:\n sib.child = [None, None, None, None]\n data = child.data[0]\n for i in range(sib.type - 1):\n if i is 0:\n if data < sib.data[i]:\n index = i\n else:\n if sib.data[i - 1] < data < sib.data[i]:\n index = i\n if i == sib.type - 2:\n index = (i+1)\n if index < sib.type and sib.child[index] == None:\n sib.child[index] = child\n else:\n if index == 0:\n sib.child[0],sib.child[1],sib.child[2], sib.child[3] = child, sib.child[0], sib.child[1], sib.child[2]\n elif index == 1:\n sib.child[1], sib.child[2], sib.child[3] = child, sib.child[1], sib.child[2]\n elif index == 2:\n sib.child[2], sib.child[3] = child, sib.child[2]\n else:\n sib.child[3] = child\n if sib.type == 2:\n sib.type = 3\n child.parent = sib\n next_node = parent\n\n self.fixNodeAfterDelete(next_node, next_node.parent)\n \n else: #\ub8e8\ud2b8\ub178\ub4dc\uc778 \uacbd\uc6b0\n self.root = self.root.child[0]\n self.root.parent = None\n \n def recurfindSucc(self, node): #\uc7ac\uadc0\uc801\uc73c\ub85c \uc67c\ucabd\uc73c\ub85c \ucb49 \ub0b4\ub824\uac00\uae30\n if node.child[0] == None: #leaf node\uc778 \uacbd\uc6b0\n return node\n else:\n return self.recurfindSucc(node.child[0])\n \n def findInorderSucc(self, target, node): #Inorder Successor \ucc3e\uae30\n if node.child[0] == None: #leaf node \uc778 \uacbd\uc6b0\n return node\n newNode = node\n if node.type == 2:\n if target+1 < node.data[0]:\n newNode = node.child[0]\n elif node.data[0] < target+1:\n newNode = node.child[1]\n elif node.type == 3:\n if target+1 < node.data[0]:\n newNode = node.child[0]\n elif node.data[0] < target+1 and target+1 < node.data[1]:\n newNode = node.child[1]\n elif node.data[1] < target+1:\n newNode = node.child[2]\n return self.recurfindSucc(newNode)\n\n def countNode(self):\n if self.root is None:\n return 0\n left_tree = TTT()\n right_tree = TTT()\n mid_tree = TTT()\n left_tree.root = self.root.child[0]\n mid_tree.root = self.root.child[1]\n right_tree.root = self.root.child[2]\n lt = left_tree.countNode()\n mt = mid_tree.countNode()\n rt = right_tree.countNode()\n return (lt+mt+rt+1)\n \n def delete(self, target, node):\n if self.countNode() == 1 and node.data[1] == None:\n if node.data[0] == target:\n self.root = None\n return\n succ = self.findInorderSucc(target, node)\n if node.data[0] == target:\n node.data[0], succ.data[0] = succ.data[0], node.data[0]\n elif node.data[1] == target:\n node.data[1], succ.data[0] = succ.data[0], node.data[1]\n if node.type == 3:\n if node.data[2] == target:\n node.data[2], succ.data[0] = succ.data[0], node.data[2]\n succ.deleteValue(target)\n self.fixNodeAfterDelete(succ, succ.parent)\n \n def getChild(self, node, mode):\n if node == None:\n print(\"ERROR: Node Does Not Exist.\")\n return\n if node.type == 2:\n if mode == 'L':\n if node.child[0] == None:\n print(\"NULL\")\n else:\n print(\"%d\"%(node.child[0].data[0]), end=\"\")\n if node.child[0].data[1] != None:\n print(\", %d\"%(node.child[0].data[1]))\n else:\n print()\n if mode == 'R':\n if node.child[1] == None:\n print(\"NULL\")\n else:\n print(\"%d\"%(node.child[1].data[0]), end=\"\")\n if node.child[1].data[1] != None:\n print(\", %d\"%(node.child[1].data[1]))\n else:\n print()\n if mode == 'M':\n print(\"ERROR: This Node Does Not Have Mid Child.\")\n if node.type == 3:\n if mode == 'L':\n if node.child[0] == None:\n print(\"NULL\")\n else:\n print(\"%d\"%(node.child[0].data[0]), end=\"\")\n if node.child[0].data[1] != None:\n print(\", %d\"%(node.child[0].data[1]))\n else:\n print()\n if mode == 'M':\n if node.child[1] == None:\n print(\"NULL\")\n else:\n print(\"%d\"%(node.child[1].data[0]), end=\"\")\n if node.child[1].data[1] != None:\n print(\", %d\"%(node.child[1].data[1]))\n else:\n print()\n if mode == 'R':\n if node.child[2] == None:\n print(\"NULL\")\n else:\n print(\"%d\"%(node.child[2].data[0]), end=\"\")\n if node.child[2].data[1] != None:\n print(\", %d\"%(node.child[2].data[1]))\n else:\n print()\n return\n\n def heightofTree(self):\n if self.root is None:\n print(\"ERROR: Invalid Input.\")\n return -1\n count = 0\n current = self.root\n while (current.child[0] != None):\n current = current.child[0]\n count = count+1\n return count\n\n def clearTree(self):\n left_node = None\n left_node = self.root\n while(self.root != None):\n if self.countNode() == 1:\n self.root = None\n return\n left_node = my_TTT.root\n while(left_node.child[0] != None):\n left_node = left_node.child[0]\n self.delete(left_node.data[0], left_node)\n return\n \n def inorderTraversal(self):\n left_tree = TTT()\n mid_tree = TTT()\n right_tree = TTT()\n if self.root.child[0] != None:\n left_tree.root = self.root.child[0]\n left_tree.inorderTraversal()\n print(\"%d \"%(self.root.data[0]), end = \"\")\n if self.root.type == 3:\n if self.root.child[1] != None:\n mid_tree.root = self.root.child[1]\n mid_tree.inorderTraversal()\n if self.root.data[1] != None:\n print(\"%d \"%(self.root.data[1]), end = \"\")\n if self.root.child[2] != None:\n right_tree.root = self.root.child[2]\n right_tree.inorderTraversal()\n else:\n if self.root.child[1] != None:\n right_tree.root = self.root.child[1]\n right_tree.inorderTraversal()\n return\n \n def rightrootleftTraversal(self):\n left_tree = TTT()\n right_tree = TTT()\n mid_tree = TTT()\n if self.root.type == 2:\n if self.root.child[1] != None:\n right_tree.root = self.root.child[1]\n right_tree.rightrootleftTraversal()\n print(\"%d \"%(self.root.data[0]), end = \"\")\n if self.root.child[0] != None:\n left_tree.root = self.root.child[0]\n left_tree.rightrootleftTraversal()\n else:\n if self.root.child[2] != None:\n right_tree.root = self.root.child[2]\n right_tree.rightrootleftTraversal()\n print(\"%d \"%(self.root.data[1]), end = \"\")\n if self.root.child[1] != None:\n mid_tree.root = self.root.child[1]\n mid_tree.rightrootleftTraversal()\n print(\"%d \"%(self.root.data[0]), end = \"\")\n if self.root.child[0] != None:\n left_tree.root = self.root.child[0]\n left_tree.rightrootleftTraversal()\n return\n \n def get_min(self):\n tmp = 0\n left_tree = TTT()\n if self.root.child[0] != None:\n left_tree.root = self.root.child[0]\n tmp = left_tree.get_min()\n else:\n return (self.root.data[0])\n return tmp\n \n def get_max(self):\n tmp = 0\n right_tree = TTT()\n if self.root.type == 2:\n if self.root.child[1] != None:\n right_tree.root = self.root.child[1]\n tmp = right_tree.get_max()\n else:\n if self.root.data[1] != None:\n return (self.root.data[1])\n else:\n return (self.root.data[0])\n return tmp\n if self.root.type == 3:\n if self.root.child[2] != None:\n right_tree.root = self.root.child[2]\n tmp = right_tree.get_max()\n else:\n if self.root.data[1] != None:\n return (self.root.data[1])\n else:\n return (self.root.data[0])\n return tmp\n \n def heightofNode(self, node): #\ub098\ub9cc\uc758 \uae30\ub2a5 1\n if (self.root is None) or (node is None):\n print(\"ERROR: Invalid Input.\")\n return -1\n tmp = 0\n while (node.parent != None):\n tmp = tmp + 1\n node = node.parent\n return tmp\n \n def replace(self, node, value):\n left_tree = TTT()\n right_tree = TTT()\n if node.type == 3:\n print(\"ERROR: Can Only Change Node With One Value.\")\n return\n if node.data[0] == value:\n print(\"ERROR: Cannot Replace With Same Value.\")\n elif (node.child[0] == None) and (node.child[1] == None):\n node.data[0] = value\n elif node.child[0] == None:\n right_tree.root = self.root.child[1]\n if right_tree.get_min() > value:\n node.data[0] = value\n else:\n print(\"ERROR: New Value Has To Meet Conditions of TTT.\")\n elif node.child[1] == None:\n left_tree.root = self.root.child[0]\n if left_tree.get_max() > value:\n node.data[0] = value\n else:\n print(\"ERROR: New Value Has To Meet Conditions of TTT.\")\n else:\n right_tree.root = self.root.child[1]\n left_tree.root = self.root.child[0]\n if (left_tree.get_max() < value) and (right_tree.get_min() > value):\n node.data[0] = value\n else:\n print(\"ERROR: New Value Has To Meet Conditions of TTT.\")\n return\n \n def preorderTraversal(self):\n left_tree = TTT()\n right_tree = TTT()\n mid_tree = TTT()\n if self.root.type == 2:\n print(\"%d \"%(self.root.data[0]), end = \"\")\n if self.root.child[1] != None:\n right_tree.root = self.root.child[1]\n right_tree.preorderTraversal()\n if self.root.child[0] != None:\n left_tree.root = self.root.child[0]\n left_tree.preorderTraversal()\n else:\n if self.root.child[1] != None:\n mid_tree.root = self.root.child[1]\n mid_tree.preorderTraversal()\n print(\"%d \"%(self.root.data[1]), end = \"\")\n print(\"%d \"%(self.root.data[0]), end = \"\")\n if self.root.child[2] != None:\n right_tree.root = self.root.child[2]\n right_tree.preorderTraversal()\n if self.root.child[0] != None:\n left_tree.root = self.root.child[0]\n left_tree.preorderTraversal()\n return\n \n\nprint(\"\uba85\ub839\ubb38 \uc548\ub0b4\")\nprint(\"+\uac12: \uc774\uc9c4 \ud2b8\ub9ac \ud0d0\uc0c9 \ud2b8\ub9ac\uc758 \ub178\ub4dc \ucd94\uac00\")\nprint(\"D\uac12: \ud574\ub2f9 \ub178\ub4dc \uc0ad\uc81c\")\nprint(\"P: \ud2b8\ub9ac \ucd9c\ub825\")\nprint(\"I: Left-Root-Right \ubc29\uc2dd\uc758 \uc21c\ud68c \ucd9c\ub825\")\nprint(\"R: Right-Root-Left \ubc29\uc2dd\uc758 \uc21c\ud68c \ucd9c\ub825\")\nprint(\"E: Root-Left-Right \ubc29\uc2dd\uc758 \uc21c\ud68c \ucd9c\ub825\")\nprint(\"N: \ucd5c\uc18c\uac12 \ucd9c\ub825\")\nprint(\"X: \ucd5c\ub300\uac12 \ucd9c\ub825\")\nprint(\"F\uac12: \ub8e8\ud2b8\ubd80\ud130 \ud574\ub2f9 \ub178\ub4dc\uae4c\uc9c0 \uac00\uae30 \uc704\ud55c \uacbd\ub85c \ucd9c\ub825\")\nprint(\"G(\uac12): \ud574\ub2f9 \ub178\ub4dc\uc758 \uc624\ub978\ucabd \uc790\uc2dd \ucd9c\ub825\")\nprint(\"L(\uac12): \ud574\ub2f9 \ub178\ub4dc\uc758 \uc67c\ucabd \uc790\uc2dd \ucd9c\ub825\")\nprint(\"M(\ub178\ub4dc\uc758 \uac12\ub4e4): \ud574\ub2f9 \ub178\ub4dc\uc758 \uac00\uc6b4\ub370 \uc790\uc2dd \ucd9c\ub825\")\nprint(\"H: \ud2b8\ub9ac\uc758 \ub192\uc774 \ucd9c\ub825\")\nprint(\"O(\uac12): \ud574\ub2f9 \ub178\ub4dc\uc758 \ub192\uc774 \ucd9c\ub825\")\nprint(\"A(\uac12): \ub2e8\uc77c \uac12\uc744 \uac00\uc9c0\ub294 \ub178\ub4dc\uc5d0 \ud55c\ud574 \ub8e8\ud2b8\uc758 \uac12 \ubcc0\uacbd\")\nprint(\"#: \ub178\ub4dc \uc218 \uc13c \ub4a4 \ucd9c\ub825\")\nprint(\"C: \ud2b8\ub9ac \ucd08\uae30\ud654\")\nprint(\"&: \ud504\ub85c\uadf8\ub7a8 \uc885\ub8cc\\n\") #\uac01 \uae30\ub2a5\ubcc4 \uc124\uba85\n\nmy_TTT = TTT()\n\nwhile True:\n default_print = 1\n used = 0 #\ud55c \uba85\ub839\uc5d0\uc11c \ud55c \uac1c \uc774\uc0c1\uc758 \ubb38\uc790\ub97c \uc0ac\uc6a9\ud560 \uacbd\uc6b0 \uc911\ubcf5 \uc785\ub825 \ubc29\uc9c0\uc6a9 \ubcc0\uc218\n \n inp = input(\"\uba85\ub839\uc5b4: \") #\ubb38\uc790\uc5f4\ub85c \uba85\ub839\uc5b4 \uc785\ub825 \ubc1b\uae30\n \n if inp[0] == '&': #\uc885\ub8cc \uba85\ub839\n break\n \n for i in range(len(inp)):\n if used > 0:\n used = used - 1\n\n elif inp[i] == '+':\n if i+1 == len(inp)-1:\n used = used + 1\n if (ord(inp[i+1])>=ord('0')) and (ord(inp[i+1])<=ord('9')):\n data = int(inp[i+1])\n my_TTT.InsertNode(data)\n else:\n print(\"ERROR: Invalid Input.\")\n elif i+2 == len(inp)-1:\n used = used + 2\n if (ord(inp[i+1])>=ord('0')) and (ord(inp[i+1])<=ord('9')):\n if (ord(inp[i+2])>=ord('0')) and (ord(inp[i+2])<=ord('9')):\n data = int(inp[i+1]+inp[i+2])\n my_TTT.InsertNode(data)\n else:\n print(\"ERROR: Invalid Input.\")\n else:\n print(\"ERROR: Invalid Input.\")\n \n elif inp[i] == 'P':\n print(\"(\", end=\"\")\n my_TTT.printTree()\n print(\")\")\n default_print = 0\n \n elif inp[i] == 'I':\n my_TTT.inorderTraversal()\n print(\"\")\n default_print = 0\n \n elif inp[i] == 'R':\n my_TTT.rightrootleftTraversal()\n print(\"\")\n default_print = 0\n \n elif inp[i] == 'N':\n print(\"%d\"%(my_TTT.get_min()))\n default_print = 0\n \n elif inp[i] == 'X':\n print(\"%d\"%(my_TTT.get_max()))\n default_print = 0\n \n elif inp[i] == 'F':\n if i+1 == len(inp)-1:\n used = used + 1\n if (ord(inp[i+1])>=ord('0')) and (ord(inp[i+1])<=ord('9')):\n tmp = int(inp[i+1])\n if my_TTT.isNode(int(tmp)) == 0:\n print(\"ERROR: Node With Such Value Doesn't Exist.\")\n else:\n print(\"Root\", end=\"\")\n my_TTT.searchValue(int(tmp), 1)\n print(\"\")\n if (int(tmp)<0) or (int(tmp)>99):\n print(\"ERROR: Invalid Input.\")\n else:\n print(\"ERROR: Invalid Input.\")\n elif i+2 == len(inp)-1:\n used = used + 2\n if (ord(inp[i+1])>=ord('0')) and (ord(inp[i+1])<=ord('9')):\n if (ord(inp[i+2])>=ord('0')) and (ord(inp[i+2])<=ord('9')):\n tmp = int(inp[i+1]+inp[i+2])\n if my_TTT.isNode(int(tmp)) == 0:\n print(\"ERROR: Node With Such Value Doesn't Exist.\")\n else:\n print(\"Root\", end=\"\")\n my_TTT.searchValue(int(tmp), 1)\n print(\"\")\n if (int(tmp)<0) or (int(tmp)>99):\n print(\"ERROR: Invalid Input.\")\n else:\n print(\"ERROR: Invalid Input.\")\n else:\n print(\"ERROR: Invalid Input.\")\n default_print = 0\n\n elif inp[i] == 'D':\n if i+1 == len(inp)-1:\n used = used + 1\n if (ord(inp[i+1])>=ord('0')) and (ord(inp[i+1])<=ord('9')):\n data = int(inp[i+1])\n if my_TTT.root == None:\n print(\"ERROR: Tree Is Empty.\")\n elif my_TTT.isNode(data) == False:\n print(\"ERROR: Node With Such Value Doesn't Exist.\")\n else:\n my_TTT.delete(data, my_TTT.searchValue(data, 0))\n else:\n print(\"ERROR: Invalid Input.\")\n elif i+2 == len(inp)-1:\n used = used + 2\n if (ord(inp[i+1])>=ord('0')) and (ord(inp[i+1])<=ord('9')):\n if (ord(inp[i+2])>=ord('0')) and (ord(inp[i+2])<=ord('9')):\n data = int(inp[i+1]+inp[i+2])\n if my_TTT.root == None:\n print(\"ERROR: Tree Is Empty.\")\n elif my_TTT.isNode(data) == False:\n print(\"ERROR: Node With Such Value Doesn't Exist.\")\n else:\n my_TTT.delete(data, my_TTT.searchValue(data, 0))\n else:\n print(\"ERROR: Invalid Input.\")\n else:\n print(\"ERROR: Invalid Input.\")\n \n elif inp[i] == 'H':\n print(\"%d\"%(my_TTT.heightofTree()))\n default_print = 0\n \n elif (inp[i] == 'G') or (inp[i] == 'L') or (inp[i] == 'M'):\n tmp = inp[inp.index('(')+1:inp.index(')')].split(',')\n if my_TTT.isNode(int(tmp[0])) == 0:\n print(\"ERROR: Node With Such Value Doesn't Exist.\")\n else:\n if inp[i] == 'G':\n my_TTT.getChild(my_TTT.searchValue(int(tmp[0]), 0), 'R')\n if inp[i] == 'L':\n my_TTT.getChild(my_TTT.searchValue(int(tmp[0]), 0), 'L')\n if inp[i] == 'M':\n my_TTT.getChild(my_TTT.searchValue(int(tmp[0]), 0), 'M')\n if (int(tmp[0])<0) or (int(tmp[0])>99):\n print(\"ERROR: Invalid Input.\")\n used = used + (inp.index(')') - inp.index('(') - 1)\n default_print = 0\n \n elif inp[i] == 'O': #\ub098\ub9cc\uc758 \uae30\ub2a5 1\n tmp = inp[inp.index('(')+1:inp.index(')')]\n if my_TTT.isNode(int(tmp)) == 0:\n print(\"ERROR: Node With Such Value Doesn't Exist.\")\n if (int(tmp)<0) or (int(tmp)>99):\n print(\"ERROR: Invalid Input.\")\n else:\n print(\"Height: %d\"%my_TTT.heightofNode(my_TTT.searchValue(int(tmp), 0)))\n used = used + (inp.index(')') - inp.index('(') - 1)\n default_print = 0\n \n elif inp[i] == 'A': #\ub098\ub9cc\uc758 \uae30\ub2a5 2\n tmp = inp[inp.index('(')+1:inp.index(')')]\n if my_TTT.root == None:\n print(\"ERROR: Cannot Find Tree.\")\n elif my_TTT.isNode(int(tmp)) == 1:\n print(\"ERROR: Node With Such Value Already Exist.\")\n else:\n if (int(tmp)<0) or (int(tmp)>99):\n print(\"ERROR: Invalid Input.\")\n else:\n my_TTT.replace(my_TTT.root, int(tmp))\n used = used + (inp.index(')') - inp.index('(') - 1)\n\n elif inp[i] == 'E': #\ub098\ub9cc\uc758 \uae30\ub2a5 3\n my_TTT.preorderTraversal()\n print(\"\")\n default_print = 0\n \n elif inp[i] == '#':\n print(\"%d\"%(my_TTT.countNode()))\n default_print = 0\n \n elif inp[i] == 'C':\n my_TTT.clearTree()\n \n if default_print == 1:\n print(\"(\", end=\"\")\n my_TTT.printTree()\n print(\")\")\n else:\n default_print = 1\n"} {"blob_id": "2674737a44966cdbc051e45ac4104bd05d8e1d48", "repo_name": "tlmurphy/cs457-db", "path": "/db.py", "length_bytes": 6762, "score": 3.5625, "int_score": 4, "content": "\"\"\"\nCS 457 Mongo Clone\n\"\"\"\n\nimport sys\nimport operator\n\ndef parse_file(arg):\n \"\"\"\n Read the file\n \"\"\"\n array = []\n with open(arg, 'r') as f:\n id_count = 0\n for line in f:\n line_array = line.strip('\\r\\n ').replace(\":\", \"\").split(\" \")\n d = {'ID': str(id_count)}\n keys = line_array[0::2]\n vals = line_array[1::2]\n for i in range(0, len(keys)):\n d[keys[i]] = vals[i]\n array.append(d)\n id_count += 1\n return array\n\ndef process_find(string):\n \"\"\"\n Retrieve the condition and the fields of a find expression\n \"\"\"\n condition = \"\"\n field = \"\"\n i = 1\n while string[i] != \",\":\n condition += string[i]\n i += 1\n\n if string[i + 1] == \" \": # Skip a space if needed\n i += 1\n\n while i < len(string):\n field += string[i]\n i += 1\n\n return (condition, field[1:-1])\n\ndef process_avg(field):\n \"\"\"\n Just returns the average argument\n \"\"\"\n return field[1:-1]\n\ndef process_cond(cond):\n \"\"\"\n A list of conditional statements that have elements that\n are lists that contain the conditional tuples...ugh\n \"\"\"\n key = \"\"\n val = \"\"\n full_cond = []\n key_vals = []\n i = 1\n while i < len(cond):\n if cond[i] == '(':\n if key_vals:\n if key_vals[-1] == 'or' or key_vals[-1] == 'and':\n full_cond.append(key_vals[0:-1])\n full_cond.append(key_vals[-1])\n key_vals = []\n i += 1\n elif key.strip() == 'and' or key.strip() == 'or':\n if key_vals:\n key_vals.append(key.strip())\n else:\n full_cond.append(key.strip())\n key = \"\"\n elif cond[i] == '=' or cond[i] == '<' or cond[i] == '>':\n oper = cond[i]\n if cond[i + 1] == '>':\n oper += cond[i + 1]\n i += 2\n else:\n i += 1\n while cond[i] != ' ' and cond[i] != ')':\n val += cond[i]\n i += 1\n key_vals.append((key.strip(), oper, val))\n key = \"\"\n val = \"\"\n if cond[i] == ')':\n full_cond.append(key_vals)\n key_vals = []\n i += 1\n else:\n key += cond[i]\n i += 1\n\n return full_cond\n\ndef process_fields(fields):\n \"\"\"\n Get a list of fields\n \"\"\"\n field_list = []\n if fields == '[]': # No fields\n return field_list\n else:\n field_list = [s.strip() for s in fields[1:-1].split(',')]\n return field_list\n\ndef get_operator(op):\n # This is awesome\n return {\n '=' : operator.eq,\n '<>' : operator.ne,\n '<' : operator.lt,\n '>' : operator.gt\n }[op]\n\ndef cast(s):\n try:\n return int(s)\n except ValueError:\n return s\n\ndef perform_cond(cond, doc):\n \"\"\"\n Conditional tuple is in the form:\n (field, conditional_operator, value)\n This function isn't very readable but it's cool\n \"\"\"\n return cond[0] in doc and get_operator(cond[1])(cast(doc[cond[0]]), cast(cond[2]))\n\ndef eval_cond(cond, data):\n \"\"\"\n Evaluate the inner conditionals\n \"\"\"\n result = []\n is_and = False\n for elem in cond:\n if elem == 'and':\n is_and = True\n elif elem == 'or':\n is_and = False\n else:\n if is_and:\n result = [doc for doc in result if perform_cond(elem, doc)]\n else:\n for doc in data:\n if perform_cond(elem, doc) and doc not in result:\n result.append(doc)\n return result\n\ndef outer_join(result1, result2):\n \"\"\"\n Outer join for OR statements\n \"\"\"\n for doc in result2:\n if doc not in result1:\n result1.append(doc)\n return result1\n\ndef inner_join(result1, result2):\n \"\"\"\n Inner join for AND statements\n \"\"\"\n return [doc for doc in result1 if doc in result2]\n\ndef find_result(cond, fields, data):\n \"\"\"\n Query response\n \"\"\"\n result = []\n i = 0\n\n while i < len(cond):\n if isinstance(cond[i], list):\n result = eval_cond(cond[i], data)\n i += 1\n else:\n if cond[i] == 'or':\n if result:\n result = outer_join(result, eval_cond(cond[i + 1], data))\n else:\n result = outer_join([], eval_cond(cond[i + 1], data))\n i += 2\n else:\n if result:\n result = inner_join(result, eval_cond(cond[i + 1], data))\n else:\n result = inner_join([], eval_cond(cond[i + 1], data))\n i += 2\n\n if not cond:\n # No conditional? Then get ALL the documents\n result = data\n\n print\n if not fields:\n # Output all the fields\n for doc in result:\n for k, v in doc.items():\n print(k + \": \" + str(v)),\n print\n else:\n for doc in result:\n output = \"\"\n for field in fields:\n if field in doc:\n output += field + \": \" + str(doc[field]) + \" \"\n if output: # Sometimes nothing is returned\n print output\n print\n\ndef avg_result(field, data):\n \"\"\"\n Get the result from average\n \"\"\"\n count = 0\n my_sum = 0\n for doc in data:\n if field in doc:\n count += 1\n my_sum += cast(doc[field])\n print\n if count != 0:\n print my_sum / float(count)\n print\n\ndef process_query(query, data):\n \"\"\"\n Make sense of the query\n \"\"\"\n while query != \"exit\":\n if not query.startswith(\"db.final.\", 0, 9):\n print \"\\nThere was an error with your syntax...\\n\"\n print \"Your query: \" + query\n print \"Queries must begin with: db.final\\n\"\n else:\n operation = query[9:]\n if operation.startswith(\"find\", 0, 4):\n conditions = process_find(query[13:])[0]\n fields = process_find(query[13:])[1]\n cond_list = process_cond(conditions)\n field_list = process_fields(fields)\n find_result(cond_list, field_list, data)\n elif operation.startswith(\"avg\", 0, 3):\n field = process_avg(query[12:])\n avg_result(field, data)\n else:\n print \"\\nThat operation is not supported by this program!\\n\"\n query = raw_input(\"query: \")\n\nif __name__ == '__main__':\n DATA = parse_file(sys.argv[1])\n QUERY = raw_input(\"query: \")\n process_query(QUERY, DATA)\n print \"Exiting...\"\n"} {"blob_id": "e073eb1dd3fa449c9fa90cc2189bd252e191b2d4", "repo_name": "bhaskargharu16/CS-335-337-AIML-assignments", "path": "/Assignment_5/lab5-180050023/layers.py", "length_bytes": 17551, "score": 4.0625, "int_score": 4, "content": "'''This file contains the implementations of the layers required by your neural network\n\nFor each layer you need to implement the forward and backward pass. You can add helper functions if you need, or have extra variables in the init function\n\nEach layer is of the form - \nclass Layer():\n def __init__(args):\n *Initializes stuff*\n\n def forward(self,X):\n # X is of shape n x (size), where (size) depends on layer\n \n # Do some computations\n # Store activations_current\n return X\n\n def backward(self, lr, activation_prev, delta):\n \"\"\"\n # lr - learning rate\n # delta - del_error / del_activations_current\n # activation_prev - input activations to this layer, i.e. activations of previous layer\n \"\"\"\n # Compute gradients wrt trainable parameters\n # Update parameters\n # Compute gradient wrt input to this layer\n # Return del_error/del_activation_prev\n'''\nimport numpy as np\nimport copy\n\nclass FullyConnectedLayer:\n def __init__(self, in_nodes, out_nodes, activation):\n # Method to initialize a Fully Connected Layer\n # Parameters\n # in_nodes - number of input nodes of this layer\n # out_nodes - number of output nodes of this layer\n self.in_nodes = in_nodes\n self.out_nodes = out_nodes\n self.activation = activation # string having values 'relu' or 'softmax', activation function to use\n # Stores the outgoing summation of weights * feautres \n self.data = None\n\n # Initializes the Weights and Biases using a Normal Distribution with Mean 0 and Standard Deviation 0.1\n self.weights = np.random.normal(0,0.1,(in_nodes, out_nodes)) \n self.biases = np.random.normal(0,0.1, (1, out_nodes))\n ###############################################\n # NOTE: You must NOT change the above code but you can add extra variables if necessary \n\n def forwardpass(self, X):\n '''\n \n Arguments:\n X -- activation matrix :[n X self.in_nodes]\n Return:\n activation matrix :[n X self.out_nodes]\n '''\n # TODO\n if self.activation == 'relu':\n a = np.matmul(X,self.weights) + self.biases\n self.data = relu_of_X(a)\n return self.data\n elif self.activation == 'softmax':\n a = np.matmul(X,self.weights) + self.biases\n self.data = softmax_of_X(a)\n return self.data\n\n else:\n print(\"ERROR: Incorrect activation specified: \" + self.activation)\n exit()\n\n return None\n # END TODO \n def backwardpass(self, lr, activation_prev, delta):\n '''\n # lr - learning rate\n # delta - del_error / del_activations_current : \n # activation_prev - input activations to this layer, i.e. activations of previous layer\n '''\n\n # TODO \n if self.activation == 'relu':\n # current_layer_activation = np.matmul(activation_prev, self.weights) + self.biases\n gradient = gradient_relu_of_X(self.data, delta)\n res = np.matmul(gradient,self.weights.T)\n self.biases = self.biases - lr * np.sum(gradient, axis=0)\n self.weights = self.weights - lr * np.matmul(activation_prev.T, gradient)\n return res\n elif self.activation == 'softmax':\n # current_layer_activation = softmax_of_X(np.matmul(activation_prev, self.weights) + self.biases) \n gradient = gradient_softmax_of_X(self.data, delta)\n res = np.matmul(gradient, self.weights.T)\n self.biases = self.biases - lr * np.sum(gradient, axis=0)\n self.weights = self.weights - lr * np.matmul(activation_prev.T, gradient)\n return res\n else:\n print(\"ERROR: Incorrect activation specified: \" + self.activation)\n exit()\n # END TODO\n\ndef helper2(x, field_height, field_width, padding=1, stride=1):\n p = padding\n x_padded = np.pad(x, ((0, 0), (0, 0), (p, p), (p, p)), mode='constant')\n # k, i, j = helper1(x.shape, field_height, field_width, padding, stride)\n N = x.shape[0]\n C = x.shape[1]\n H = x.shape[2]\n W = x.shape[3]\n if (H + 2 * padding - field_height) % stride == 0 and (W + 2 * padding - field_height) % stride == 0 :\n p0 = np.tile(np.repeat(np.arange(field_height), field_width), C)\n p1 = stride * np.repeat(np.arange((H + 2 * padding - field_height) // stride + 1), (W + 2 * padding - field_width) // stride + 1)\n l0 = np.tile(np.arange(field_width), field_height * C)\n l1 = stride * np.tile(np.arange((W + 2 * padding - field_width) // stride + 1), (H + 2 * padding - field_height) // stride + 1)\n k = np.repeat(np.arange(C), field_height * field_width).reshape(-1, 1)\n cols = x_padded[:, k, p0.reshape(-1, 1) + p1.reshape(1, -1), l0.reshape(-1, 1) + l1.reshape(1, -1)]\n cols = cols.transpose(1, 2, 0).reshape(field_height * field_width * C, -1)\n return cols\n return None\n\ndef helper3(cols, x_shape, field_height=3, field_width=3, padding=1, stride=1):\n N, C, H, W = x_shape\n H_padded, W_padded = H + 2 * padding, W + 2 * padding\n x_padded = np.zeros((N, C, H_padded, W_padded), dtype=cols.dtype)\n\n # k, i, j = helper1(x_shape, field_height, field_width, padding, stride)\n if (H + 2 * padding - field_height) % stride == 0 and (W + 2 * padding - field_height) % stride == 0 :\n p0 = np.tile(np.repeat(np.arange(field_height), field_width), C)\n p1 = stride * np.repeat(np.arange((H + 2 * padding - field_height) // stride + 1), (W + 2 * padding - field_width) // stride + 1)\n l0 = np.tile(np.arange(field_width), field_height * C)\n l1 = stride * np.tile(np.arange((W + 2 * padding - field_width) // stride + 1), (H + 2 * padding - field_height) // stride + 1)\n k = np.repeat(np.arange(C), field_height * field_width).reshape(-1, 1)\n cols_reshaped = cols.reshape(C * field_height * field_width, -1, N)\n cols_reshaped = cols_reshaped.transpose(2, 0, 1)\n np.add.at(x_padded, (slice(None), k, p0.reshape(-1, 1) + p1.reshape(1, -1), l0.reshape(-1, 1) + l1.reshape(1, -1)), cols_reshaped)\n if padding == 0:\n return x_padded\n return x_padded[:, :, padding:-padding, padding:-padding]\n return None\nclass ConvolutionLayer:\n def __init__(self, in_channels, filter_size, numfilters, stride, activation):\n # Method to initialize a Convolution Layer\n # Parameters\n # in_channels - list of 3 elements denoting size of input for convolution layer\n # filter_size - list of 2 elements denoting size of kernel weights for convolution layer\n # numfilters - number of feature maps (denoting output depth)\n # stride - stride to used during convolution forward pass\n # activation - can be relu or None\n self.in_depth, self.in_row, self.in_col = in_channels\n self.filter_row, self.filter_col = filter_size\n self.stride = stride\n self.activation = activation\n self.out_depth = numfilters\n self.out_row = int((self.in_row - self.filter_row)/self.stride + 1)\n self.out_col = int((self.in_col - self.filter_col)/self.stride + 1)\n\n # Stores the outgoing summation of weights * feautres \n self.data = None\n \n # Initializes the Weights and Biases using a Normal Distribution with Mean 0 and Standard Deviation 0.1\n self.weights = np.random.normal(0,0.1, (self.out_depth, self.in_depth, self.filter_row, self.filter_col)) \n self.biases = np.random.normal(0,0.1,self.out_depth)\n \n def forwardpass(self, X):\n # INPUT activation matrix :[n X self.in_depth X self.in_row X self.in_col]\n # OUTPUT activation matrix :[n X self.out_depth X self.out_row X self.out_col]\n\n # TODO\n if self.activation == 'relu':\n self.data = (np.matmul(self.weights.reshape(self.out_depth, -1),helper2(X, self.filter_row, self.filter_col, padding=0, stride=self.stride)) + self.biases.reshape(-1,1)).reshape(self.out_depth, self.out_row, self.out_col, -1).transpose(3, 0, 1, 2)\n return relu_of_X(self.data)\n else:\n print(\"ERROR: Incorrect activation specified: \" + self.activation)\n exit()\n \n ###############################################\n # END TODO\n def backwardpass(self, lr, activation_prev, delta):\n # Input\n # lr : learning rate of the neural network\n # activation_prev : Activations from previous layer\n # delta : del_Error/ del_activation_curr\n # Output\n # new_delta : del_Error/ del_activation_prev\n \n # Update self.weights and self.biases for this layer by backpropagation\n # TODO\n\n ###############################################\n if self.activation == 'relu':\n # inp_delta = actual_gradient_relu_of_X(self.data, delta)\n # # raise NotImplementedError\n # X_col = \n del_grad = gradient_relu_of_X(self.data, delta)\n db_grad = np.sum(del_grad, axis=(0, 2, 3)) \n dW_grad = np.matmul(del_grad.transpose(1, 2, 3, 0).reshape(self.out_depth, -1), helper2(activation_prev, self.filter_row, self.filter_col, padding=0, stride=self.stride).T).reshape(self.weights.shape)\n W_reshape = self.weights.reshape(self.out_depth, -1)\n dX_cache = helper3(np.matmul(W_reshape.T, del_grad.transpose(1, 2, 3, 0).reshape(self.out_depth, -1)), activation_prev.shape, self.filter_row, self.filter_col, padding=0, stride=self.stride)\n self.biases = self.biases - lr * db_grad\n self.weights = self.weights - lr * dW_grad\n return dX_cache\n else:\n print(\"ERROR: Incorrect activation specified: \" + self.activation)\n exit()\n ###############################################\n\n # END TODO\n \nclass AvgPoolingLayer:\n def __init__(self, in_channels, filter_size, stride):\n # Method to initialize a Convolution Layer\n # Parameters\n # filter_size - list of 2 elements denoting size of kernel weights for convolution layer\n\n # NOTE: Here we assume filter_size = stride\n # And we will ensure self.filter_size[0] = self.filter_size[1]\n self.in_depth, self.in_row, self.in_col = in_channels\n self.filter_row, self.filter_col = filter_size\n self.stride = stride\n\n self.out_depth = self.in_depth\n self.out_row = int((self.in_row - self.filter_row)/self.stride + 1)\n self.out_col = int((self.in_col - self.filter_col)/self.stride + 1)\n\n\n def forwardpass(self, X):\n # print('Forward MP ')\n # Input\n # X : Activations from previous layer/input\n # Output\n # activations : Activations after one forward pass through this layer\n \n # TODO\n return np.mean(helper2(X.reshape(X.shape[0] * self.in_depth, 1, self.in_row, self.in_col), self.filter_row, self.filter_col, padding=0, stride=self.stride), axis=0).reshape(self.out_row, self.out_col, X.shape[0], self.out_depth).transpose(2, 3, 0, 1)\n # END TODO\n ###############################################\n \n def backwardpass(self, alpha, activation_prev, delta):\n # Input\n # lr : learning rate of the neural network\n # activation_prev : Activations from previous layer\n # activations_curr : Activations of current layer\n # delta : del_Error/ del_activation_curr\n # Output\n # new_delta : del_Error/ del_activation_prev\n \n # TODO\n X = helper2(activation_prev.reshape(activation_prev.shape[0] * self.in_depth, 1, self.in_row, self.in_col), self.filter_row, self.filter_col, padding=0, stride=self.stride)\n dX_grad = np.zeros(X.shape,dtype = X.dtype)\n dX_grad[:, :] = delta.transpose(2, 3, 0, 1).ravel() / (self.filter_row * self.filter_col)\n return helper3(dX_grad, (activation_prev.shape[0] * self.in_depth, 1, self.in_row, self.in_col), self.filter_row, self.filter_col, padding=0, stride=self.stride).reshape(activation_prev.shape)\n # END TODO\n ###############################################\n\n\n\nclass MaxPoolingLayer:\n def __init__(self, in_channels, filter_size, stride):\n # Method to initialize a Convolution Layer\n # Parameters\n # filter_size - list of 2 elements denoting size of kernel weights for convolution layer\n\n # NOTE: Here we assume filter_size = stride\n # And we will ensure self.filter_size[0] = self.filter_size[1]\n self.in_depth, self.in_row, self.in_col = in_channels\n self.filter_row, self.filter_col = filter_size\n self.stride = stride\n\n self.out_depth = self.in_depth\n self.out_row = int((self.in_row - self.filter_row)/self.stride + 1)\n self.out_col = int((self.in_col - self.filter_col)/self.stride + 1)\n\n\n def forwardpass(self, X):\n # print('Forward MP ')\n # Input\n # X : Activations from previous layer/input\n # Output\n # activations : Activations after one forward pass through this layer\n \n # TODO\n X_mod = helper2(X.reshape(X.shape[0] * self.in_depth, 1, self.in_row, self.in_col), self.filter_row, self.filter_col, padding=0, stride=self.stride)\n return (X_mod[np.argmax(X_mod, axis=0), range(np.argmax(X_mod, axis=0).size)]).reshape(self.out_row, self.out_col, X.shape[0], self.out_depth).transpose(2, 3, 0, 1)\n # END TODO\n ###############################################\n \n def backwardpass(self, alpha, activation_prev, delta):\n # Input\n # lr : learning rate of the neural network\n # activation_prev : Activations from previous layer\n # activations_curr : Activations of current layer\n # delta : del_Error/ del_activation_curr\n # Output\n # new_delta : del_Error/ del_activation_prev\n \n # TODO\n X = helper2(activation_prev.reshape(activation_prev.shape[0] * self.in_depth, 1, self.in_row, self.in_col), self.filter_row, self.filter_col, padding=0, stride=self.stride)\n dX_grad = np.zeros(X.shape,dtype = X.dtype) \n dX_grad[np.argmax(X, axis=0), range(np.argmax(X, axis=0).size)] = delta.transpose(2, 3, 0, 1).ravel()\n return helper3(dX_grad, (activation_prev.shape[0] * self.in_depth, 1, self.in_row, self.in_col), self.filter_row, self.filter_col, padding=0, stride=self.stride).reshape(activation_prev.shape)\n # END TODO\n ###############################################\n\n\n# Helper layer to insert between convolution and fully connected layers\nclass FlattenLayer:\n def __init__(self):\n pass\n \n def forwardpass(self, X):\n # TODO\n # print(X.shape)\n n = X.shape[0]\n return X.reshape(n,-1)\n def backwardpass(self, lr, activation_prev, delta):\n return delta.reshape(activation_prev.shape)\n # END TODO\n\n# Function for the activation and its derivative\ndef relu_of_X(X):\n\n # Input\n # data : Output from current layer/input for Activation | shape: batchSize x self.out_nodes\n # Returns: Activations after one forward pass through this relu layer | shape: batchSize x self.out_nodes\n # This will only be called for layers with activation relu\n # TODO\n mycopy = copy.deepcopy(X)\n mycopy = np.where(mycopy <= 0.0, 0.0, mycopy)\n return mycopy\n # END TODO \n \ndef gradient_relu_of_X(X, delta):\n # Input\n # Note that these shapes are specified for FullyConnectedLayers, the function also needs to work with ConvolutionalLayer\n # data : Output from next layer/input | shape: batchSize x self.out_nodes\n # delta : del_Error/ del_activation_curr | shape: batchSize x self.out_nodes\n # Returns: Current del_Error to pass to current layer in backward pass through relu layer | shape: batchSize x self.out_nodes\n # This will only be called for layers with activation relu amd during backwardpass\n \n # TODO\n mycopy = np.zeros_like(X)\n # mycopy = np.where(X > 0.0, delta,mycopy)\n # mycopy = np.where(mycopy <= 0.0,0.0,1.0) * delta\n mycopy[X > 0.0] = 1.0\n return mycopy*delta\n # END TODO\n\ndef softmax_of_X(X):\n # Input\n # data : Output from current layer/input for Activation | shape: batchSize x self.out_nodes\n # Returns: Activations after one forward pass through this softmax layer | shape: batchSize x self.out_nodes\n # This will only be called for layers with activation softmax\n \n # TODO\n exp = np.exp(X)\n return exp/np.sum(exp,axis = 1,keepdims=True)\n # END TODO \ndef gradient_softmax_of_X(X, delta):\n # Input\n # data : Output from next layer/input | shape: batchSize x self.out_nodes\n # delta : del_Error/ del_activation_curr | shape: batchSize x self.out_nodes\n # Returns: Current del_Error to pass to current layer in backward pass through softmax layer | shape: batchSize x self.out_nodes\n # This will only be called for layers with activation softmax amd during backwardpass\n # Hint: You might need to compute Jacobian first\n # TODO\n Y = np.zeros(X.shape)\n for i in range(X.shape[0]):\n vec = X[i,:].reshape(-1,1)\n Jacobian = (np.eye(X.shape[1]) * vec) - np.matmul(vec, vec.T) \n Y[i:i+1,:] = np.matmul(Jacobian, delta[i,:].reshape(-1,1)).reshape(-1)\n return Y\n # END TODO\n"} {"blob_id": "291a921692c9a110b3b84f62822396997712d6c5", "repo_name": "egalli64/pythonesque", "path": "/hr/ctci/merge_sort_test.py", "length_bytes": 591, "score": 3.578125, "int_score": 4, "content": "\"\"\"\nHackerRank Cracking the Coding Interview Merge Sort: Counting Inversions\nauthor: Manny egalli64@gmail.com\ninfo: http://thisthread.blogspot.com/2017/03/hackerrank-merge-sort-counting.html\n https://www.hackerrank.com/challenges/ctci-merge-sort\n\"\"\"\n\nimport unittest\n\nfrom hr.ctci.merge_sort import count_inversions\n\n\nclass TestSolution(unittest.TestCase):\n\n def test_provided_1(self):\n self.assertEqual(0, count_inversions([1, 1, 1, 2, 2]))\n\n def test_provided_2(self):\n self.assertEqual(4, count_inversions([2, 1, 3, 1, 2]))\n\n\nif __name__ == '__main__':\n unittest.main()\n"} {"blob_id": "3de0f7fe3e2008005e17fa3796eec8d0bf64f455", "repo_name": "zchen0211/topcoder", "path": "/python/leetcode/geometry/296_best_meeting.py", "length_bytes": 1364, "score": 4.375, "int_score": 4, "content": "\"\"\"\n296. Best Meeting Point (Hard)\n\nA group of two or more people wants to meet and minimize the total travel distance. You are given a 2D grid of values 0 or 1, where each 1 marks the home of someone in the group. The distance is calculated using Manhattan Distance, where distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|.\n\nFor example, given three people living at (0,0), (0,4), and (2,2):\n\n1 - 0 - 0 - 0 - 1\n| | | | |\n0 - 0 - 0 - 0 - 0\n| | | | |\n0 - 0 - 1 - 0 - 0\nThe point (0,2) is an ideal meeting point, as the total travel distance of 2+2+2=6 is minimal. So return 6.\n\"\"\"\n\nclass Solution(object):\n def minTotalDistance(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n m = len(grid)\n if m == 0: return 0\n n = len(grid[0])\n if n == 0: return 0\n\n pts = []\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 1: pts.append([i,j])\n \n if len(pts) == 0: return 0\n\n xs = [item[0] for item in pts]\n xs.sort()\n midx = xs[(len(pts)-1)/2]\n\n ys = [item[1] for item in pts]\n ys.sort()\n midy = ys[(len(pts)-1)/2]\n print midx, midy\n result = 0\n for item in pts:\n result += abs(item[0] - midx)\n result += abs(item[1] - midy)\n return result\n"} {"blob_id": "9291bc3e48d869c824bfb33db937c37dc69b054d", "repo_name": "gak/homeloan", "path": "/homeloan.py", "length_bytes": 3583, "score": 3.515625, "int_score": 4, "content": "#!/usr/bin/env python\n\nimport math\nfrom datetime import date, timedelta\n\nFREQ_YEARLY = 0\nFREQ_MONTHLY = 1\nFREQ_FORTNIGHTLY = 2\nFREQ_WEEKLY = 3\n\nDAYS_IN_YEAR = 365.24\n\nclass Loan:\n\n def __init__(self, principal, annual_interest_rate, years, frequency):\n self.principal = principal\n self.annual_interest_rate = annual_interest_rate\n self.years = years\n self.frequency = frequency\n self.calculate_frequency()\n self.factor = self.calculate_factor()\n\n @staticmethod\n def interval_for_frequency(freq):\n if FREQ_YEARLY:\n return DAYS_IN_YEAR\n if FREQ_MONTHLY:\n return DAYS_IN_YEAR / 12\n if FREQ_FORTNIGHTLY:\n return 14\n if FREQ_WEEKLY:\n return 7\n\n def calculate_frequency(self):\n div = DAYS_IN_YEAR / self.interval_for_frequency(self.frequency)\n self.interest_rate = self.annual_interest_rate / div\n self.periods = self.years * div\n self.periods = int(math.ceil(self.periods))\n\n @property\n def payment(self):\n return self.principal / self.factor\n\n def calculate_factor(self):\n factor = 0.\n base_rate = 1. + self.interest_rate\n denominator = base_rate\n for a in xrange(self.periods):\n factor += (1. / denominator)\n denominator *= base_rate\n return factor\n\n def get_extra_principal_paid(self, days):\n return 0\n\n def loop(self, output=False):\n\n current_period = 1\n principal = self.principal\n total_interest_paid = 0\n current_date = date.today()\n days_in_period = Loan.interval_for_frequency(self.frequency)\n days = 0\n\n while True:\n\n current_period += 1\n delta = timedelta(days=days_in_period)\n current_date += delta\n days += days_in_period\n\n interest_paid = principal * self.interest_rate\n principal_paid = self.payment - interest_paid\n\n # extra repayments?\n extra_principal_paid = self.get_extra_principal_paid(days)\n principal_paid += extra_principal_paid\n\n remaining_balance = principal - principal_paid\n\n if remaining_balance <= 0:\n break\n\n total_interest_paid += interest_paid\n\n principal = remaining_balance\n\n total_paid = interest_paid + principal_paid\n\n if output:\n print '%2i' % current_period,\n print '%10s' % current_date,\n print 'Year: %4.1f' % (days / DAYS_IN_YEAR),\n print 'interest paid: %8.2f' % interest_paid,\n print 'principal paid: %8.2f (+%5.2f)' % (principal_paid,\n extra_principal_paid),\n print 'paid: %8.2f' % total_paid,\n print 'remaining balance: %9.2f' % remaining_balance\n\n\n self.real_periods = current_period\n\n return total_interest_paid\n\n def print_info(self):\n total_interest_paid = self.loop()\n print 'Loan amount: %7i' % self.principal,\n print 'Interest rate %2.2f%%' % (self.annual_interest_rate *\n 100),\n print 'predicted repayments: %3i' % self.periods,\n print 'real repayments: %3i' % self.real_periods,\n print 'period repayment: %7.2f' % self.payment,\n print 'total interest_paid: %10.2f' % total_interest_paid\n print\n\nif __name__ == '__main__':\n loan = Loan(465000 * 0.8, 0.07, 30, FREQ_MONTHLY)\n loan.loop(False)\n loan.print_info()\n\n"} {"blob_id": "6d8b8cb688fafa39db58ea8d617969642faf979f", "repo_name": "cp4011/Algorithms", "path": "/LeetCode/49_\u5b57\u6bcd\u5f02\u4f4d\u8bcd\u5206\u7ec4.py", "length_bytes": 1262, "score": 4.0, "int_score": 4, "content": "\"\"\"\u7ed9\u5b9a\u4e00\u4e2a\u5b57\u7b26\u4e32\u6570\u7ec4\uff0c\u5c06\u5b57\u6bcd\u5f02\u4f4d\u8bcd\u7ec4\u5408\u5728\u4e00\u8d77\u3002\u5b57\u6bcd\u5f02\u4f4d\u8bcd\u6307\u5b57\u6bcd\u76f8\u540c\uff0c\u4f46\u6392\u5217\u4e0d\u540c\u7684\u5b57\u7b26\u4e32\u3002\n\u793a\u4f8b: \u8f93\u5165: [\"eat\", \"tea\", \"tan\", \"ate\", \"nat\", \"bat\"],\n\u8f93\u51fa:\n[\n [\"ate\",\"eat\",\"tea\"],\n [\"nat\",\"tan\"],\n [\"bat\"]\n]\n\u8bf4\u660e\uff1a \u6240\u6709\u8f93\u5165\u5747\u4e3a\u5c0f\u5199\u5b57\u6bcd\u3002 \u4e0d\u8003\u8651\u7b54\u6848\u8f93\u51fa\u7684\u987a\u5e8f\u3002\n\"\"\"\n\n''' \u6392\u5e8f\u6570\u7ec4\u5206\u7c7b\n\u5f53\u4e14\u4ec5\u5f53\u5b83\u4eec\u7684\u6392\u5e8f\u5b57\u7b26\u4e32\u76f8\u7b49\u65f6\uff0c\u4e24\u4e2a\u5b57\u7b26\u4e32\u662f\u5b57\u6bcd\u5f02\u4f4d\u8bcd\u3002\n\u7ef4\u62a4\u4e00\u4e2a\u6620\u5c04 ans : {String -> List}\uff0c\u5176\u4e2d\u6bcf\u4e2a\u952e K \u662f\u4e00\u4e2a\u6392\u5e8f\u5b57\u7b26\u4e32\uff0c\u6bcf\u4e2a\u503c\u662f\u521d\u59cb\u8f93\u5165\u7684\u5b57\u7b26\u4e32\u5217\u8868\u3002\n\u5728 Java \u4e2d\uff0c\u6211\u4eec\u5c06\u952e\u5b58\u50a8\u4e3a\u5b57\u7b26\u4e32\u3002 \u5728 Python \u4e2d\uff0c\u6211\u4eec\u5c06\u952e\u5b58\u50a8\u4e3a\u6563\u5217\u5316\u5143\u7ec4\uff0c\u4f8b\u5982\uff0c('c', 'o', 'd', 'e')\u3002\n'''\n\n\nclass Solution(object):\n def groupAnagrams(self, strs):\n import collections\n ans = collections.defaultdict(list) # list.append()\n for s in strs:\n ans[str(sorted(s))].append(s) # sorted()\u8fd4\u56de\u7684\u662flist\u5217\u8868\uff0c\u4e0d\u80fd\u4f5c\u4e3a\u952e \u88abhash\u3002\u53ef\u4ee5\u8f6c\u6210\u5b57\u7b26\u4e32str()\u6216\u8005\u5143\u7ec4tuple()\n return list(ans.values()) # \u5fc5\u987blist()\u8f6c\u5316\uff0c\u5b9e\u73b0dict_values([['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']])\n\n\nprint(Solution().groupAnagrams([\"eat\", \"tea\", \"tan\", \"ate\", \"nat\", \"bat\"]))\n"} {"blob_id": "e0b027675b4876b90e591bf5aea23b68e3daf678", "repo_name": "haztecaso/paralela21", "path": "/filosofos/filosofos_sem_1.py", "length_bytes": 1305, "score": 3.8125, "int_score": 4, "content": "#!/usr/bin/env python3\n\"\"\"\nAdri\u00e1n Lattes Grassi, 11 de Marzo de 2021\n\nPrimer intento de soluci\u00f3n del problema de los fil\u00f3sofos usando sem\u00e1foros. Cada\nfil\u00f3sofo coge primero el tenedor de la izquierda, por lo que si todos los\nfilosofos han cogido un tenedor, se puede entrar en deadlock.\n\"\"\"\n\nfrom multiprocessing import Process, Lock, current_process\nfrom time import sleep\nfrom random import random\n\nK = 1000\nspeed = 10000\n\ncurrent_philosopher = lambda: current_process().name\n\ndef think():\n print(f\"{current_philosopher()} thinking.\")\n sleep(random()/speed)\n\ndef eat():\n print(f\"{current_philosopher()} eating.\")\n sleep(random()/speed)\n\ndef live(forks, index):\n for i in range(K):\n think()\n\n print(f\"{current_philosopher()} grabs left fork.\")\n forks[index].acquire()\n print(f\"{current_philosopher()} grabs right fork.\")\n forks[(index+1)%5].acquire()\n\n eat()\n\n forks[index].release()\n forks[(index+1)%5].release()\n print(f\"{current_philosopher()} finished eating.\")\n\nif __name__ == \"__main__\":\n forks = [Lock() for _ in range(5)]\n philosophers =[Process(target=live, name=f\"Philosopher {i}\",\\\n args=(forks, i)) for i in range(5)]\n\n for f in philosophers:\n f.start()\n for f in philosophers:\n f.join()\n"} {"blob_id": "ab9ac1e63661e4eb9fef39924a4e474563aa074d", "repo_name": "schlogl2017/kmers_genomes", "path": "/kmer_palindrome_stats.py", "length_bytes": 7717, "score": 3.84375, "int_score": 4, "content": "#!usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\nimport math\nfrom collections import defaultdict\nimport pandas as pd\n\ndef get_expected_values(kmer_list, kmer_counts):\n \"\"\"Calculates the expected value of all palindrome kmers in a sequence.\n Inputs:\n pal_lst = list of palindromes (str)\n counts = dictionary of kmer counts\n Output:\n expected - dictionary with expected values for all palindromes.\n The expected values are calculated as:\n E(C(W)) = C(W1-Wn-1) * C(W2-Wn) / C(W2-Wn-1)\n \"\"\"\n expected = defaultdict(float)\n for kmer in kmer_list:\n suf = kmer_counts[kmer[1:]]\n pre = kmer_counts[kmer[:-1]]\n mid = kmer_counts[kmer[1:-1]]\n # to catch the divide by zero error\n if mid == 0:\n expected[kmer] = 0.0\n else:\n ex = (suf * pre) / mid\n expected[kmer] = expected.get(kmer, 0.0) + ex\n return expected\n\n\ndef get_z_scores(kmer_list, kmer_counts, expected_kmers, len_seq):\n \"\"\"Calculates the z_score of all palindromes.\n Input:\n palindrome_lst = list of palindromes (str)\n counts = dictionary of kmer counts\n expected = dictionary of kmer expected values\n length_sequence = length of sequence (int)\n Output:\n z_score dictionary where key are palindromes and values are the calculated z_score (float)\n The z_scores are calculated as:\n Z(W) = (C(W)) - E(C(W)) / sigma(W)\n And sigma as:\n sigma(W) = sqrt(E(C(W))) * (1 - E(C(W)/N))\n \"\"\"\n z_score = defaultdict(float)\n for kmer in kmer_list:\n if expected_kmers[kmer] == 0.0:\n z_score[kmer] = 0.0\n else:\n sigma = math.sqrt(expected_kmers[kmer]) * (1 - expected_kmers[kmer] / (2 * len_seq))\n z = (kmer_counts[kmer] - expected_kmers[kmer]) / sigma\n z_score[kmer] = z_score.get(kmer, 0.0) + z\n return z_score\n\n\ndef get_pvalues(kmer_list, z_score_kmers):\n \"\"\"Calculates the p_value of all palindromes.\n Input:\n palindrome_lst - list of palindromes (str)\n z_score - a dictionary with palindromes z_scores (float)\n Output:\n a palindrome p_value dictionary.\n For probability of getting a z-value larger than t\n P(z > t) = erfc(t/sqrt(2))/2\n For probability of getting a z-value smaller than t\n P(z > t) = erfc(-t/sqrt(2))/2\n \"\"\"\n p_values = defaultdict(float)\n for kmer in kmer_list:\n if z_score_kmers[kmer] < 0.0:\n under = math.erfc(-z_score_kmers[kmer] / math.sqrt(2)) / 2\n p_values[kmer] = p_values.get(kmer, 0.0) + under\n else:\n over = math.erfc(z_score_kmers[kmer] / math.sqrt(2)) / 2\n p_values[kmer] = p_values.get(kmer, 0.0) + over\n return p_values\n\n\ndef get_evalues(kmer_list, p_value_kmers):\n \"\"\"Calculates the e_value of all palindrome kmers.\n Inputs:\n palindrome_lst - list of palindromes (str)\n p_value - a dictionary where key are the palindromes (str) and the value are p_value (float)\n Output:\n The e_value as a dictionary where the key are the palindrome (str)\n and value are e_value (float).\n \"\"\"\n e_value = defaultdict(float)\n num_tests = len(kmer_list)\n for kmer in kmer_list:\n p = p_value_kmers[kmer] * num_tests\n e_value[kmer] = e_value.get(kmer, 0.0) + p\n return e_value\n\n\ndef get_scores(kmer_list, kmer_counts, expected_kmers):\n \"\"\"Calculates de kmer escore and its expected frequency in the genome.\n Inputs:\n kmer_list - list substring of length k\n kmer_counts - a dictionary with kmer and it counts\n expected_kmers - a dictionary with kmer and it expected counts\n Output:\n scores - a dictionary with kmers and it scores, calculated as:\n S = obs - exp / obs + exp\n \"\"\"\n scores = defaultdict(float)\n for kmer in kmer_list:\n if expected_kmers[kmer] == 0.0 or kmer_counts[kmer] == 0.0:\n scores[kmer] = 0.0\n else:\n scr = (kmer_counts[kmer] - expected_kmers[kmer]) / (kmer_counts[kmer] + expected_kmers[kmer])\n scores[kmer] = scores.get(kmer, 0.0) + scr\n return scores\n\n\ndef get_new_scores(kmer_list, kmer_counts, expected_kmers):\n \"\"\"Calculates de kmer escore and its expected frequency in the genome.\n Inputs:\n kmer_list - list substring of length k\n kmer_counts - a dictionary with kmer and it counts\n expected_kmers - a dictionary with kmer and it expected counts\n Output:\n scores - a dictionary with kmers and it scores, calculated as:\n S = obs - exp / obs + exp\n \"\"\"\n scores = defaultdict(float)\n for kmer in kmer_list:\n scores[kmer] = scores.get(kmer, 0.0)\n if expected_kmers[kmer] == 0.0 or kmer_counts[kmer] == 0.0:\n scores[kmer] = 0.0\n else:\n scr = kmer_counts[kmer] / (kmer_counts[kmer] + expected_kmers[kmer])\n scores[kmer] = scores.get(kmer, 0.0) + scr\n return scores\n\n\ndef get_odds_ratio(kmer_list, kmer_freqs):\n ors = defaultdict(float)\n for kmer in kmer_list:\n midf = kmer_freqs[kmer[1:-1]]\n pref = kmer_freqs[kmer[:-1]]\n suff = kmer_freqs[kmer[1:]]\n kmf = kmer_freqs[kmer]\n # to catch the divide by zero error\n if midf == 0.0 or kmf == 0.0 or pref == 0.0 or suff == 0.0:\n ors[kmer] = ors.get(kmer, 0.0)\n else:\n od = (kmf * midf) / (pref * suff)\n ors[kmer] = ors.get(kmer, 0.0) + od\n return ors\n\n\ndef get_difference(kmer_list, kmer_counts, expected_kmers):\n diff = defaultdict(float)\n for kmer in kmer_list:\n d = kmer_counts[kmer] - expected_kmers[kmer]\n diff[kmer] = diff.get(kmer, 0.0) + d\n return diff\n\n\ndef get_log_odds(kmer_list, kmer_counts, expected_kmers):\n log_ods = defaultdict(float)\n for kmer in kmer_list:\n log_ods[kmer] = log_ods.get(kmer, 0.0)\n if kmer_counts[kmer] == 0.0 or expected_kmers[kmer] == 0.0:\n log_ods[kmer] = 0.0\n else:\n lod = math.log(kmer_counts[kmer] / expected_kmers[kmer])\n log_ods[kmer] += lod\n return log_ods\n\n\ndef get_kmer_statistics(kmer_list,\n kmer_counts,\n kmer_expected,\n kmer_z_scores,\n kmer_e_values,\n kmer_odds_ratios,\n kmer_diffs,\n kmer_scores,\n kmer_new_scores,\n kmer_log_odds):\n \"\"\"\"\"\"\n stats = []\n for kmer in kmer_list:\n obs = kmer_counts[kmer]\n exp = kmer_expected[kmer]\n z_scr = kmer_z_scores[kmer]\n e_val = kmer_e_values[kmer]\n odds = kmer_odds_ratios[kmer]\n diff = kmer_diffs[kmer]\n scr = kmer_scores[kmer]\n nscr = kmer_new_scores[kmer]\n lod = kmer_log_odds[kmer]\n stats.append((kmer,\n obs,\n exp,\n z_scr,\n e_val,\n odds,\n diff,\n scr,\n nscr,\n lod))\n return stats\n\ndef get_dataframe_from_kmer_alldata(dir_out, filename, k, kmerdata):\n df = pd.DataFrame(kmerdata, columns=[\"kmer\",\n \"Observed\",\n \"Expected\",\n \"Z_score\",\n \"Evalues\",\n \"Odds\",\n \"Diff\",\n \"Scores\",\n \"NScores\",\n \"Log_odds\"])\n df.to_csv(f\"{dir_out}/{filename}_{k}_.csv\")\n"} {"blob_id": "6085718145db5beee58e22993df1dcf184cfeda0", "repo_name": "ideaqiwang/leetcode", "path": "/DynamicProgramming/120_Triangle.py", "length_bytes": 1618, "score": 3.859375, "int_score": 4, "content": "'''\n120. Triangle\n\nGiven a triangle array, return the minimum path sum from top to bottom.\n\nFor each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row.\n\nExample 1:\nInput: triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]\nOutput: 11\nExplanation: The triangle looks like:\n 2\n 3 4\n 6 5 7\n4 1 8 3\nThe minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above).\n\nExample 2:\nInput: triangle = [[-10]]\nOutput: -10\n'''\n\nclass Solution1:\n def minimumTotal(self, triangle: List[List[int]]) -> int:\n self.memo = {}\n self.minSum = sys.maxsize\n return self.dfs(triangle, 0, 0, 0)\n \n def dfs(self, triangle, row, col, path):\n m = len(triangle)\n if row == m:\n return 0\n \n if (row, col) in self.memo:\n return self.memo[(row, col)]\n \n left = self.dfs(triangle, row+1, col, path)\n right = self.dfs(triangle, row+1, col+1, path)\n \n self.memo[(row, col)] = min(left, right)+triangle[row][col]\n return self.memo[(row, col)]\n\nclass Solution2:\n # Dynamic Programming: Bottom-Up\n def minimumTotal(self, triangle: List[List[int]]) -> int:\n belowRow = triangle[-1]\n n = len(triangle)\n for r in range(n-2, -1, -1):\n curRow = []\n for c in range(r+1):\n smallestBelow = min(belowRow[c], belowRow[c+1])\n curRow.append(triangle[r][c]+smallestBelow)\n belowRow = curRow\n return belowRow[0]"} {"blob_id": "e06ace56adaa42c063441be92b459e7f1fdfe0ea", "repo_name": "T-Santos/Daily-Coding-Problems", "path": "/9_DCP.py", "length_bytes": 1341, "score": 4.1875, "int_score": 4, "content": "'''\nGiven a list of integers, write a function that returns the\nlargest sum of non-adjacent numbers.\n\nFor example:\n[2, 4, 6, 8] should return 12, since we pick 4 and 8. \n[5, 1, 1, 5] should return 10, since we pick 5 and 5.\n'''\n#from math import abs\n\ndef largest_sum_1(numbers):\n\t# O(N^2) solution - nested loops\n\n\tif not numbers:\n\t\treturn 0\n\n\tif len(numbers) <= 2:\n\t\treturn 0\n\n\tlargest = 0\n\n\tfor num_1_pos, num_1 in enumerate(numbers[:-2]):\n\n\t\tfor num_2 in numbers[num_1_pos+2:]:\n\n\t\t\tlargest = num_1 + num_2 if num_1 + num_2 > largest else largest\n\n\treturn largest\n\ndef largest_sum(numbers):\n\t# O(nlogn) - for the sort\n\n\tif not numbers:\n\t\treturn 0\n\tif len(numbers) <= 2:\n\t\treturn 0\n\n\tsort_pos = sorted(\n\t\t[(number,position) for position,number in enumerate(numbers)],\n\t\treverse = True,\n\t\tkey = lambda x: x[0])\n\n\tlargest = sort_pos[0]\n\tsecond_largest = sort_pos[1] if abs(sort_pos[0][1] - sort_pos[1][1]) > 1 else sort_pos[2]\n\n\treturn largest[0] + second_largest[0]\n\ndef unit_tests():\n\n\tassert largest_sum([]) == 0\n\tassert largest_sum([1,2]) == 0\n\tassert largest_sum([1,1,1]) == 2\n\tassert largest_sum([1,2,3]) == 4\n\tassert largest_sum([2,4,6,8]) == 12\n\tassert largest_sum([5,1,1,5]) == 10\n\tassert largest_sum([2,8,3,8]) == 16\n\tassert largest_sum([5,4,3,2,1]) == 8\n\tprint(\"PASS\")\n\ndef main():\n\tunit_tests()\n\nif __name__ == '__main__':\n\tmain()"} {"blob_id": "b218e5765e3e7ca41b86b8e2854bcc632de5f8ef", "repo_name": "BroadbentJim/BL4CKJ4CK", "path": "/Shared Functions/Posh Folder/BasicStrategy.py", "length_bytes": 8539, "score": 3.53125, "int_score": 4, "content": "import random\nimport time, timeit\nimport numpy as np\n\n\nplayer_wins = 0\ndealer_wins = 0\nsplit_player_wins = 0\nsplit_dealer_wins = 0\nglobal hardtotal\nhardtotal = False\n\n\nDeck=[]\nPhand=[]\nPhand2=[]\nDhand=[]\nstrategy=[]\n\ndef new_deck():\n\n one_suit=[2,3,4,5,6,7,8,9,10,\"J\", \"Q\", \"K\", \"A\"] #One suit\n q = 0\n while q < 24: #6 decks of 4 suits\n for i in one_suit:\n Deck.append(i)\n q +=1\n random.shuffle(Deck) #Randomly shuffle the hand\n\ndef initial_hit(hand):\n card = Deck.pop(0) #Set card to be first card in deck and remove it\n hand.append(card)\n\ndef hit(hand):\n card = Deck.pop(0)\n hand.append(card)\n strategy.append(\"Hit\")\n\ndef split(hand):\n card = hand.pop(0)\n Phand2.append(card)\n hit(Phand)\n hit(Phand2)\n\ndef double(hand):\n hit(hand)\n #wager = 2 * wager\n\ndef stay():\n strategy.append(\"Stay\")\n return\n\ndef deal():\n initial_hit(Phand)\n initial_hit(Dhand)\n initial_hit(Phand)\n initial_hit(Dhand)\n\ndef bust(hand):\n if score(hand) > 21:\n return \"\"\n else:\n return \"not \"\n\ndef score(hand):\n \"\"\"\n Score Function\n This function changes the global hardtotal\n hardtotal is changed here as this function evaluates whether or not they are hardtotals\n Parameters: hand\n hand: this is the hand ARRAY for which the score is being evaluated.\n returns value of the hand\n \"\"\"\n global hardtotal\n #Create empty holder variables and reset hardtotal\n total = 0\n Aces = 0\n hardtotal = True\n for cards in hand:#iterate through every card in the hand array\n if cards == \"J\" or cards == \"Q\" or cards == \"K\":#if the card is a Jack, Queen, Kind\n total += 10#The score of the hand is increased by 10\n elif cards == \"A\":#If the card is an Ace\n total += 11\n Aces += 1\n hardtotal = False#Hardtotal is changed to reflect that the hand contains an Ace\n else:\n total += cards #Otherwise just add the numerical value of the card to the total\n\n while Aces > 0 and total > 21: #If the total would cause the player to bust and there are ace(s)\n total -= 10#Take the Ace to be worth 1\n Aces -= 1#Decrement the number of aces\n if Aces == 0:#If no aces or all aces taken to be 1\n hardtotal = True#The hand is a hardtotal\n\n return total\n\n\ndef basic_strategy(Pand, Dand): #Basic Strategy\n \"\"\"\n Basic Player Strategy\n This function takes 3 arguments.\n Pand: Current player hand\n Pand2: Alternate player hand\n Dand: Dealer hand\n\n This function will apply certain logic to the players decision\n \"\"\"\n global hardtotal\n if split_style(Pand, Dand) == True:\n #If split_style says to split, split\n split(Pand)\n elif hardtotal == False:# NOT Hardtotal logic\n if score(Pand) < 18:#if score of hand is less than 18\n hit(Pand)\n elif score(Pand) == 18 and score([Dand[0]]) > 8:\n #if score of hand is 18 and score of dealer's card > 8\n hit(Pand)\n else:\n stay()\n elif hardtotal == True:#hardtotal logic\n if score(Pand) < 12:\n hit(Pand)\n elif score(Pand) < 17 and score([Dand[0]]) > 6:\n hit(Pand)\n elif score(Pand) == 12 and score([Dand[0]]) < 4:\n hit(Pand)\n else:\n stay()\n\ndef split_style(Pand, Dand):\n \"\"\"\n This function decides whether the player should split or not\n It takes exactly 3 arguments\n Pand which should be the current player hand\n Pand2 the other player hand\n Dand which is the dealer hand\n\n It will then follow some predefined rules and choose whether to split\n\n The function will return a Boolean on whether the player should split\n True means split. False means don't split\n\n\n\"\"\"\n if Pand[0] == Pand[1] and len(Phand2) == 0:#If player hasn't split and the two cards of the hand are same\n if Pand[0] == 'A':#If the card is an Ace\n return True\n elif Pand[0] == 8:\n return True\n elif (Pand[0] == 2 or Pand[0] == 3 or Pand[0] == 7) and score([Dand[0]]) < 8:\n #If the card is 2/3/7 and the score of the dealer's card is less than 8\n return True\n elif Pand[0] == 6 and score([Dand[0]]) < 7:\n #If card is 6 and dealer's card is less than 7\n return True\n elif Pand[0] == 9 and score([Dand[0]]) < 10 and score([Dand[0]]) != 7:\n #If card is 9 and dealer's card is less than 10 but not 7\n return True\n elif Phand[0] == 4 and score([Dand[0]]) < 7 and score([Dand[0]]) > 4:\n #if score is 4 and dealer's card is between 4 and 7\n return True\n else:\n return False\n\n\n\ndef dealer(wanted):\n while score(Dhand) < wanted:\n hit(Dhand)\n\ndef compare(hand1, hand2): #True means Hand1 has won, False means hand2 has won.\n\n if score(hand1) == 21 and len(hand1) == 2:\n if score(hand2) == 21 and len(hand2) == 2:\n return 1\n else:\n return 1.5\n\n if score(hand1) <= 21 and score(hand2) > 21:\n return 1\n elif score(hand1) > 21 and score(hand2) <= 21:\n return 0\n elif score(hand1) > score(hand2) and score(hand1)<= 21:\n\n return 1\n else:\n return 0\n\ndef game(loop):\n global Deck, Phand, Phand2, Dhand\n player_wins = dealer_wins = split_player_wins = split_dealer_wins = 0\n start_time = time.time()\n new_deck()\n\n for _ in range(loop):\n Phand = []\n Dhand = []\n Phand2 = []\n deal()\n basic_strategy(Phand, Dhand)\n if len(Phand2) > 0:\n basic_strategy(Phand2, Dhand)\n dealer(17)\n if compare(Phand, Dhand) == 1:\n player_wins += 1\n elif compare(Phand, Dhand) == 1.5:\n player_wins += 1.5\n else:\n dealer_wins += 1\n if len(Phand2) > 0:\n if compare(Phand2, Dhand) == 1:\n split_player_wins += 1\n elif compare(Phand2, Dhand) == 1.5:\n split_player_wins += 1.5\n else:\n split_dealer_wins += 1\n if len(Deck) <= 52:\n new_deck()\n\n finish_time = time.time()\n elapsed_time = finish_time - start_time\n split_games = split_player_wins + split_dealer_wins\n total_games = loop + split_games\n total_player_wins = player_wins + split_player_wins\n total_dealer_wins = dealer_wins + split_dealer_wins\n net_gain_abs = total_player_wins - total_dealer_wins #abs is short for absolute\n net_gain_per = net_gain_abs / total_dealer_wins\n win_rate = round(total_player_wins / total_games * 100, 2)\n #Calculate how many times the player did each move\n hits = strategy.count(\"Hit\")\n stays = strategy.count(\"Stay\")\n splits = strategy.count(\"Split\")\n doubles = strategy.count(\"Doubles\")\n\n dictionary = {'Total Games': total_games,\n 'Total player wins': total_player_wins,\n 'Total dealer wins': total_dealer_wins,\n 'Percentage netgain': net_gain_per,\n 'Percentage winrate': win_rate,\n \"Strategy\": strategy,\n \"Time\": elapsed_time, }\n return dictionary\n\ndef simulations(loop):\n gains = []\n start_time = time.time()\n for i in range(99):\n gains.append(game(loop)[\"Percentage netgain\"])\n dictionary = game(loop)\n finish_time = time.time()\n elapsed_time = finish_time - start_time\n dictionary[\"Time\"] = elapsed_time\n gains.append(dictionary[\"Percentage netgain\"])\n\n dictionary[\"Gainz\"] = gains\n #print(dictionary)\n return dictionary\n\n#Debugging code\ndef wrapper(func, *args, **kwargs):\n #Used for timeit with functions with arguments\n def wrapped():#Create a subfunction\n return func(*args, **kwargs)\n return wrapped#Return that subfunction\n\nif __name__ == \"__main__\":\n # sims = int(input(\"Please input the number of times you would like to loop \"))\n # dictionary = game(sims)\n # print(\"Time taken: \", dictionary[\"Time Taken\"])\n # print(\"Netgain: \", round(dictionary[\"Percentage netgain\"], 2), \"%\")\n # print(\"Winrate: \", dictionary[\"Percentage winrate\"], \"%\")\n # print(\"Times hit: \", dictionary[\"Strategy\"].count(\"Hit\"))\n # print(\"Total games\", dictionary[\"Total Games\"])\n wrapped = wrapper(game, 10000) #Create a function that will be tested\n print(timeit.timeit(wrapped, number=100))#Go through the function wrapped 100 times and print the total time\n"} {"blob_id": "892c5a36bd85ff17e1a73bc40e62577da98178d7", "repo_name": "Mfk98/Artificial_Intelligence-TDT4136", "path": "/Assignment 5/CSP-backtracking.py", "length_bytes": 10575, "score": 3.875, "int_score": 4, "content": "#!/usr/bin/python3\nimport copy\nimport itertools\nfrom tkinter import *\n\n__author__ = \"Henrik H\u00f8iness\"\n\n\nclass CSP:\n\t\"\"\"\n\tClass for representing a Constraint Satisfaction Problem - in this task Sudoku\n\t\"\"\"\n\tdef __init__(self):\n\t\t# self.variables is a list of the variable names in the CSP\n\t\tself.variables = []\n\n\t\t# self.domains[i] is a list of legal values for variable i\n\t\tself.domains = {}\n\n\t\t# self.constraints[i][j] is a list of legal value pairs for\n\t\t# the variable pair (i, j)\n\t\tself.constraints = {}\n\n\t\t# Number of backtracks done in CSP.backtracking_search()\n\t\tself.backtracking_number = 0\n\n\t\t# Number of failed backtracks done in CSP.backtracking_search()\n\t\tself.failed_backtracking_number = 0\n\n\tdef add_variable(self, name, domain):\n\t\t\"\"\"\n\t\tAdd a new variable to the CSP. 'name' is the variable name\n\t\tand 'domain' is a list of the legal values for the variable.\n\t\t\"\"\"\n\t\tself.variables.append(name)\n\t\tself.domains[name] = list(domain)\n\t\tself.constraints[name] = {}\n\n\tdef get_all_possible_pairs(self, a, b):\n\t\t\"\"\"\n\t\tGet a list of all possible pairs (as tuples) of the values in\n\t\tthe lists 'a' and 'b', where the first component comes from list\n\t\t'a' and the second component comes from list 'b'.\n\t\t\"\"\"\n\t\treturn itertools.product(a, b)\n\n\tdef get_all_arcs(self):\n\t\t\"\"\"\n\t\tGet a list of all arcs/constraints that have been defined in\n\t\tthe CSP. The arcs/constraints are represented as tuples (i, j),\n\t\tindicating a constraint between variable 'i' and 'j'.\n\t\t\"\"\"\n\t\treturn [(i, j) for i in self.constraints for j in self.constraints[i]]\n\n\tdef get_all_neighboring_arcs(self, var):\n\t\t\"\"\"\n\t\tGet a list of all arcs/constraints going to/from variable\n\t\t'var'. The arcs/constraints are represented as in get_all_arcs().\n\t\t\"\"\"\n\t\treturn [(i, var) for i in self.constraints[var]]\n\n\tdef add_constraint_one_way(self, i, j, filter_function):\n\t\t\"\"\"\n\t\tAdd a new constraint between variables 'i' and 'j'. The legal\n\t\tvalues are specified by supplying a function 'filter_function',\n\t\tthat returns True for legal value pairs and False for illegal\n\t\tvalue pairs. This function only adds the constraint one way,\n\t\tfrom i -> j. You must ensure that the function also gets called\n\t\tto add the constraint the other way, j -> i, as all constraints\n\t\tare supposed to be two-way connections!\n\t\t\"\"\"\n\t\tif j not in self.constraints[i]:\n\t\t\t# First, get a list of all possible pairs of values between variables i and j\n\t\t\tself.constraints[i][j] = self.get_all_possible_pairs(self.domains[i], self.domains[j])\n\n\t\t# Next, filter this list of value pairs through the function\n\t\t# 'filter_function', so that only the legal value pairs remain\n\t\tself.constraints[i][j] = list(filter(lambda value_pair: filter_function(*value_pair), self.constraints[i][j]))\n\n\tdef add_all_different_constraint(self, variables):\n\t\t\"\"\"\n\t\tAdd an Alldiff constraint between all of the variables in the\n\t\tlist 'variables'.\n\t\t\"\"\"\n\t\tfor (i, j) in self.get_all_possible_pairs(variables, variables):\n\t\t\tif i != j:\n\t\t\t\tself.add_constraint_one_way(i, j, lambda x, y: x != y)\n\n\tdef backtracking_search(self):\n\t\t\"\"\"\n\t\tThis functions starts the CSP solver and returns the found\n\t\tsolution.\n\t\t\"\"\"\n\t\t# Make a so-called \"deep copy\" of the dictionary containing the\n\t\t# domains of the CSP variables. The deep copy is required to\n\t\t# ensure that any changes made to 'assignment' does not have any\n\t\t# side effects elsewhere.\n\t\tassignment = copy.deepcopy(self.domains)\n\n\t\t# Run AC-3 on all constraints in the CSP, to weed out all of the\n\t\t# values that are not arc-consistent to begin with\n\t\tself.inference(assignment, self.get_all_arcs())\n\n\t\t# Setting initial values for tracking backtracking\n\t\tself.backtracking_number = 1\n\t\tself.failed_backtracking_number = 0\n\n\t\t# Call backtrack with the partial assignment 'assignment'\n\t\treturn self.backtrack(assignment)\n\n\tdef backtrack(self, assignment):\n\t\t\"\"\"\n\t\tThe function 'Backtrack' based on the pseudocode in the\n\t\ttextbook.\n\n\t\tThe function is called recursively, with a partial assignment of\n\t\tvalues 'assignment'. 'assignment' is a dictionary that contains\n\t\ta list of all legal values for the variables that have *not* yet\n\t\tbeen decided, and a list of only a single value for the\n\t\tvariables that *have* been decided.\n\n\t\tWhen all of the variables in 'assignment' have lists of length\n\t\tone, i.e. when all variables have been assigned a value, the\n\t\tfunction should return 'assignment'. Otherwise, the search\n\t\tshould continue. When the function 'inference' is called to run\n\t\tthe AC-3 algorithm, the lists of legal values in 'assignment'\n\t\tshould get reduced as AC-3 discovers illegal values.\n\t\t\"\"\"\n\n\t\t# Returning assignment when all assignments have length one\n\t\tif sum(len(domain) for domain in assignment.values()) == len(assignment):\n\t\t\treturn assignment\n\n\t\tvariable = self.select_unassigned_variable(assignment)\n\t\tfor value in assignment[variable]:\n\t\t\tassignment_cp = copy.deepcopy(assignment)\n\t\t\tassignment_cp[variable] = value\n\t\t\tif self.inference(assignment_cp, self.get_all_arcs()):\n\t\t\t\t# Found inference calling backtrack recursively\n\t\t\t\tself.backtracking_number += 1\n\t\t\t\tresult = self.backtrack(assignment_cp)\n\t\t\t\tif result:\n\t\t\t\t\treturn result\n\n\t\t# Backtracking failed\n\t\tself.failed_backtracking_number += 1\n\t\treturn\n\n\tdef select_unassigned_variable(self, assignment):\n\t\t\"\"\"\n\t\tThe function 'Select-Unassigned-Variable' based on the pseudocode\n\t\tin the textbook. Should return the name of one of the variables\n\t\tin 'assignment' that have not yet been decided, i.e. whose list\n\t\tof legal values has a length greater than one.\n\t\t\"\"\"\n\t\t# Assuming that at least one item has two or more legal values\n\t\t# Choosing the variable with the least amount of possible values\n\t\treturn min(assignment.keys(),key=lambda var: float(\"inf\") if len(assignment[var]) < 2 else len(assignment[var]))\n\n\tdef inference(self, assignment, queue):\n\t\t\"\"\"\n\t\tThe function 'AC-3' based on the pseudocode in the textbook.\n\t\t'assignment' is the current partial assignment, that contains\n\t\tthe lists of legal values for each undecided variable. 'queue'\n\t\tis the initial queue of arcs that should be visited.\n\t\t\"\"\"\n\t\twhile queue:\n\t\t\txi, xj = queue.pop(0)\n\t\t\tif self.revise(assignment, xi, xj):\n\t\t\t\tif not assignment[xi]:\n\t\t\t\t\treturn False\n\t\t\t\tfor xk, _ in self.get_all_neighboring_arcs(xi):\n\t\t\t\t\tif xk != xj:\n\t\t\t\t\t\tqueue.append((xk, xi))\n\t\treturn True\n\n\tdef revise(self, assignment, xi, xj):\n\t\t\"\"\"\n\t\tThe function 'Revise' is based from the pseudocode in the textbook.\n\t\t'assignment' is the current partial assignment, that contains\n\t\tthe lists of legal values for each undecided variable. 'xi' and\n\t\t'xj' specifies the arc that should be visited. If a value is\n\t\tfound in variable xi's domain that doesn't satisfy the constraint\n\t\tbetween xi and xj, the value should be deleted from xi's list of\n\t\tlegal values in 'assignment'.\n\t\t\"\"\"\n\t\trevised = False\n\n\t\tfor x in assignment[xi]:\n\t\t\tarcs = list(self.get_all_possible_pairs([x], assignment[xj]))\n\t\t\tif not sum(arc in self.constraints[xi][xj] for arc in arcs):\n\t\t\t\trevised = True\n\t\t\t\tassignment[xi].remove(x) if x in assignment[xi] else None\n\n\t\treturn revised\n\n\ndef create_sudoku_csp(filename):\n\t\"\"\"\n\tInstantiate a CSP representing the Sudoku board found in the text\n\tfile named 'filename' in the current directory.\n\t\"\"\"\n\tcsp = CSP()\n\tboard = list(map(lambda x: x.strip(), open(filename, 'r')))\n\n\tfor row in range(9):\n\t\tfor col in range(9):\n\t\t\tif board[row][col] == '0':\n\t\t\t\tcsp.add_variable('{}-{}'.format(row, col), map(str, range(1, 10)))\n\t\t\telse:\n\t\t\t\tcsp.add_variable('{}-{}'.format(row, col), [board[row][col]])\n\n\tfor row in range(9):\n\t\tcsp.add_all_different_constraint(['{}-{}'.format(row, col) for col in range(9)])\n\tfor col in range(9):\n\t\tcsp.add_all_different_constraint(['{}-{}'.format(row, col) for row in range(9)])\n\tfor box_row in range(3):\n\t\tfor box_col in range(3):\n\t\t\tcells = []\n\t\t\tfor row in range(box_row * 3, (box_row + 1) * 3):\n\t\t\t\tfor col in range(box_col * 3, (box_col + 1) * 3):\n\t\t\t\t\tcells.append('{}-{}'.format(row, col))\n\t\t\tcsp.add_all_different_constraint(cells)\n\n\treturn csp\n\n\ndef print_sudoku_solution(solution):\n\t\"\"\"\n\tConvert the representation of a Sudoku solution as returned from\n\tthe method CSP.backtracking_search(), into a human readable\n\trepresentation.\n\t\"\"\"\n\tfor row in range(9):\n\t\tfor col in range(9):\n\t\t\tprint(solution['{}-{}'.format(row, col)][0], end=\" \")\n\t\t\tif col == 2 or col == 5:\n\t\t\t\tprint('|', end=\" \"),\n\t\tprint()\n\t\tif row == 2 or row == 5:\n\t\t\tprint('------+-------+------')\n\n\ndef draw_board(solution, backtracking_number, failed_backtracking_number, boardname=\"\"):\n\t\"\"\"\n\tMethod for drawing sudoku board with solution from CSP-backtracking with kTinker\n\t\"\"\"\n\trec_size = 35\n\twidth = 9 * rec_size + 3\n\theight = 9 * rec_size + 3\n\n\tdrawer = Tk()\n\tdrawer.winfo_toplevel().title(\"Solved {}\".format(boardname))\n\twindow = Canvas(drawer, width=width, height=height)\n\n\tdef exit_tkinter():\n\t\tdrawer.destroy()\n\n\tdef stop_solving():\n\t\tglobal solving\n\t\tsolving = False\n\t\tdrawer.destroy()\n\n\tfor row in range(9):\n\t\tfor col in range(9):\n\t\t\tx = row + 0.1\n\t\t\ty = col + 0.1\n\n\t\t\t# Drawing thicker lines on certain rows and columns\n\t\t\tcol_space = 1 if col == 3 or col == 6 else 0\n\t\t\trow_space = 1 if row == 3 or row == 6 else 0\n\n\t\t\twindow.create_rectangle(y * rec_size + col_space, x * rec_size + row_space, y * rec_size + rec_size,\n\t\t\t\t\t\t\t\t\tx * rec_size + rec_size,\n\t\t\t\t\t\t\t\t\tfill=\"white\")\n\n\t\t\twindow.create_text(y * rec_size + 0.5 * rec_size, x * rec_size + 0.5 * rec_size,\n\t\t\t\t\t\t\t fill=\"black\", font=\"Times 20 italic bold\", text=(solution['{}-{}'.format(row, col)][0]))\n\n\tnext_button = Button(drawer, text=\"Solve next board\",\n\t\t\t\t\t\t width=30, command=exit_tkinter, height=2)\n\tstop_button = Button(drawer, text=\"Stop solving\",\n\t\t\t\t\t\t width=30, command=stop_solving, height=2)\n\n\tlabel1 = Label(drawer, text=\"Number of backtracks: {}\".format(backtracking_number))\n\tlabel2 = Label(drawer, text=\"Number of failed backtracks: {}\".format(failed_backtracking_number))\n\n\twindow.pack()\n\tlabel1.pack()\n\tlabel2.pack()\n\tnext_button.pack()\n\tstop_button.pack()\n\n\tdrawer.mainloop()\n\n\ndef main():\n\tboard_paths = [(\"Easy\", \"sudokus/easy.txt\"),\n\t\t\t\t (\"Medium\", \"sudokus/medium.txt\"),\n\t\t\t\t (\"Hard\", \"sudokus/hard.txt\"),\n\t\t\t\t (\"Very hard\", \"sudokus/veryhard.txt\"),\n\t\t\t\t (\"Worlds Toughest 2012\", \"sudokus/worldstoughest2012.txt\")]\n\tfor filepath in board_paths:\n\t\tif solving:\n\t\t\tprint(\"> Solving {}\".format(filepath[0]), end=\"\\n\\n\")\n\t\t\tcsp = create_sudoku_csp(filepath[1])\n\t\t\tsolution = csp.backtracking_search()\n\t\t\tdraw_board(solution, csp.backtracking_number, csp.failed_backtracking_number, filepath[0])\n\n\tif not solving:\n\t\tprint(\"Stopped solving\")\n\nsolving = True\nmain()\n"} {"blob_id": "5a8f94b0dfff76c2bc3396fd5e0b27f690a9c6a2", "repo_name": "riya-mistry/AdvancedAlgorithms", "path": "/randomized_quicksort.py", "length_bytes": 556, "score": 3.859375, "int_score": 4, "content": "import random\ncount=0\ndef quicksort(A,p,r):\n\t\n\tif p < r:\n\t\tq = partition(A,p,r)\n\t\tquicksort(A,p,q-1)\n\t\tquicksort(A,q,r)\n\t\t\n\t\t\ndef partition(A,p,r):\n\tglobal count\n\tindex = (random.randrange(p,r+1))\n\tA[index] , A[r] = A[r],A[index]\n\t\n\tx = A[r]\n\ti = p-1\n\n\tfor j in range(p,r):\n\t\tif A[j] <= x :\n\t\t\tcount+=1\n\t\t\ti += 1\n\t\t\tA[i],A[j] = A[j],A[i]\n\tA[i+1],A[r] = A[r] , A[i+1]\n\t\n\treturn i+1\n\t\n\n\n\n\nif __name__ == \"__main__\":\n\tarray = []\n\tfor i in range(1000):\n\t\tarray.append(i)\n\tquicksort(array,0,len(array)-1)\n\tprint(\"comparisons are \" + str(count))\n\t#print(array)\n"} {"blob_id": "f48286e9678fb96b9251c00080ace2f1de297957", "repo_name": "HaochenW/Leetcode-answer", "path": "/algorithm3. Longest Substring Without Repeating Characters/python_solution_1.py", "length_bytes": 2176, "score": 3.5625, "int_score": 4, "content": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Aug 1 21:34:52 2019\n\n@author: haochen01.wang\n\"\"\"\n\n\n'''\nedition I: \nIdea: If the next character not appear in the record string, then we will add the character into record string;\n If the next character appear in the record string, then we will discard the first character in the record string, then add the next character;\nresults: wrong;\nsituation: \"pwwkew\"\nwhy\uff1f\uff1a The sequence must be started from the repeated position, not the start position;\n Besides, we must record the longest string before the next character\n \nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n tmp_str = ''\n i = 0\n while i < len(s):\n if s[i] in tmp_str:\n tmp_str = tmp_str[1::] + s[i]\n else:\n tmp_str = tmp_str + s[i]\n i = i + 1\n return len(tmp_str)\n'''\n\n'''\nedition II: changed from edition I\nresult: faster than 74.06% of Python3 online submissions for Longest Substring Without Repeating Characters.\n less than 5.09% of Python3 online submissions for Longest Substring Without Repeating Characters.\n'''\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n tmp_str = ''\n i = 0\n max_len = 0\n while i < len(s):\n if s[i] in tmp_str:\n pos = tmp_str.index(s[i])\n if len(tmp_str) > max_len: # record the maximum length\n max_len = len(tmp_str)\n tmp_str = tmp_str[pos+1::] + s[i] # make the new string from the next character of the repeated character\n else:\n tmp_str = tmp_str + s[i] \n i = i + 1\n \n if len(tmp_str) > max_len:\n max_len = len(tmp_str)\n \n return max_len\n \n\ns = \"pwwkew\"\ntest = Solution()\nlength = test.lengthOfLongestSubstring(s)\n\n\n'''\n\u601d\u8def\u8bf4\u660e\uff1a\u5176\u5b9e\u6838\u5fc3\u7684\u60f3\u6cd5\u5c31\u662f\uff0c\u5f53\u626b\u63cf\u8fc7\u540e\u8fd9\u4e2a\u4f4d\u7f6e\u7684\u5b50\u4e32\u540e\uff0c\u540e\u9762\u7684\u5b50\u4e32\u53ef\u4ee5\u7528\u524d\u9762\u7684\u6700\u957f\u5b50\u4e32\u8fed\u4ee3\u5f97\u5230\uff1b\u53ea\u9700\u8981\u8bb0\u5f55\u4e0b\u6765\u957f\u5ea6\u6700\u957f\u7684\u5b50\u4e32\u5373\u53ef\uff1b\u6709\u70b9\u7c7b\u4f3c\u4e8e\u52a8\u6001\u89c4\u5212\u7684\u60f3\u6cd5\uff0c\u628a\u95ee\u9898\u62c6\u89e3\uff1b\n'''"} {"blob_id": "07888666c44f64154ce806323818feb08db34870", "repo_name": "Pabloo22/Algoritmos", "path": "/ackerman_function.py", "length_bytes": 1292, "score": 3.953125, "int_score": 4, "content": "\"\"\"\r\nFrom Wikipedia:\r\nIn computability theory, the Ackermann function, named after Wilhelm Ackermann, \r\nis one of the simplest and earliest-discovered examples of a total computable \r\nfunction that is not primitive recursive. All primitive recursive functions are \r\ntotal and computable, but the Ackermann function illustrates that not all total \r\ncomputable functions are primitive recursive. After Ackermann's publication \r\nof his function (which had three nonnegative integer arguments), many authors \r\nmodified it to suit various purposes, so that today \"the Ackermann function\" \r\nmay refer to any of numerous variants of the original function. One common \r\nversion, the two-argument Ackermann\u2013P\u00e9ter function, is defined as follows \r\nfor nonnegative integers m and n:\r\n\r\nA(0, n) = n + 1\r\nA(m, 0) = A(m - 1, 1)\r\nA(m, n) = A(m - 1, A(m, n - 1))\r\n\"\"\"\r\n\r\ndef ackermann_function_v1(m, n):\r\n\r\n\tif m == 0:\r\n\t\treturn n + 1\r\n\telif n == 0:\r\n\t\treturn ackermann_function_v1(m - 1, 1)\r\n\telse:\r\n\t\treturn ackermann_function_v1(m -1, ackermann_function_v1(m, n -1))\r\n\r\n\r\ndef ackermann_function_v2(m, n):\r\n\r\n\tstack = [m]\r\n\r\n\twhile stack:\r\n\t\tif stack[-1] == 0:\r\n\t\t\tstack.pop()\r\n\t\t\tn += 1\r\n\t\telif n == 0:\r\n\t\t\tstack[-1] -= 1\r\n\t\t\tn = 1\r\n\t\telse:\r\n\t\t\tstack.append(stack[-1])\r\n\t\t\tstack[-2] -= 1\r\n\t\t\tn -= 1\r\n\r\n\treturn n\r\n"} {"blob_id": "2d4512bd301c67402d8fbc8e305a1eec11c21d06", "repo_name": "VCloser/CodingInterviewChinese2-python", "path": "/56_01_NumbersAppearOnce.py", "length_bytes": 1408, "score": 4.15625, "int_score": 4, "content": "\"\"\"\n\u4ece\u5934\u5230\u5c3e\u4e00\u6b21\u5f02\u6216\u6570\u7ec4\u4e2d\u7684\u6bcf\u4e00\u4e2a\u6570\u5b57\uff0c\u90a3\u4e48\u6700\u7ec8\u5f97\u5230\u7684\u7ed3\u679c\u5c31\u662f\u4e24\u4e2a\u53ea\u51fa\u73b0\u4e00\u6b21\u7684\u6570\u7ec4\u7684\u5f02\u6216\u7ed3\u679c\u3002\u56e0\u4e3a\u5176\u4ed6\u6570\u5b57\u90fd\u51fa\u73b0\u4e86\u4e24\u6b21\uff0c\u5728\u5f02\u6216\u4e2d\u5168\u90e8\u62b5\u6d88\u4e86\u3002\n\u7531\u4e8e\u4e24\u4e2a\u6570\u5b57\u80af\u5b9a\u4e0d\u4e00\u6837\uff0c\u90a3\u4e48\u5f02\u6216\u7684\u7ed3\u679c\u80af\u5b9a\u4e0d\u4e3a0\uff0c\u4e5f\u5c31\u662f\u8bf4\u8fd9\u4e2a\u7ed3\u679c\u6570\u7ec4\u7684\u4e8c\u8fdb\u5236\u8868\u793a\u81f3\u5c11\u6709\u4e00\u4e2a\u4f4d\u4e3a1\u3002\n\u6211\u4eec\u5728\u7ed3\u679c\u6570\u7ec4\u4e2d\u627e\u5230\u7b2c\u4e00\u4e2a\u4e3a1\u7684\u4f4d\u7684\u4f4d\u7f6e\uff0c\u8bb0\u4e3a\u7b2cn\u4f4d\u3002\n\u73b0\u5728\u6211\u4eec\u4ee5\u7b2cn\u4f4d\u662f\u4e0d\u662f1\u4e3a\u6807\u51c6\u628a\u5143\u6570\u7ec4\u4e2d\u7684\u6570\u5b57\u5206\u6210\u4e24\u4e2a\u5b50\u6570\u7ec4\uff0c\u7b2c\u4e00\u4e2a\u5b50\u6570\u7ec4\u4e2d\u6bcf\u4e2a\u6570\u5b57\u7684\u7b2cn\u4f4d\u90fd\u662f1\uff0c\u800c\u7b2c\u4e8c\u4e2a\u5b50\u6570\u7ec4\u4e2d\u6bcf\u4e2a\u6570\u5b57\u7684\u7b2cn\u4f4d\u90fd\u662f0\u3002\n\n\"\"\"\n\ndef find_nums_appear_once(arr):\n if not arr or len(arr)<2:\n return []\n\n res = 0\n\n for i in arr:\n res = res^i\n\n index = find_first_bit_is_1(res)\n\n num1 = 0\n num2 = 0\n\n for i in arr:\n if is_bit_1(i,index):\n num1 = num1^i\n else:\n num2 = num2^i\n\n return num1,num2\n\n\ndef find_first_bit_is_1(num):\n \"\"\"\n \u627e\u5230num\u7684\u4e8c\u8fdb\u5236\u4f4d\u4e2d\u6700\u53f3\u8fb9\u662f1\u7684\u4f4d\u7f6e\n \"\"\"\n index_of_bit = 0\n while num != 0 and num & 1 == 0:\n num = num >> 1\n index_of_bit += 1\n return index_of_bit\n\ndef is_bit_1(num,index):\n \"\"\"\n \u5224\u65ad\u7b2cindex\u4f4d\u662f\u4e0d\u662f1\n \"\"\"\n num = num>>index\n return num&1\n\n\nif __name__ == \"__main__\":\n print(find_nums_appear_once([-8, -4, 3, 6, 3, -8, 5, 5]))"} {"blob_id": "0470fc7a2972be7c1cdca78bc5a040d3b9a61079", "repo_name": "xiaohuanlin/Algorithms", "path": "/Leetcode/115. Distinct Subsequences.py", "length_bytes": 1985, "score": 3.6875, "int_score": 4, "content": "'''\nGiven two strings s and t, return the number of distinct subsequences of s which equals t.\n\nA string's subsequence is a new string formed from the original string by deleting some (can be none) of the characters without disturbing the remaining characters' relative positions. (i.e., \"ACE\" is a subsequence of \"ABCDE\" while \"AEC\" is not).\n\nThe test cases are generated so that the answer fits on a 32-bit signed integer.\n\n \n\nExample 1:\n\nInput: s = \"rabbbit\", t = \"rabbit\"\nOutput: 3\nExplanation:\nAs shown below, there are 3 ways you can generate \"rabbit\" from S.\nrabbbit\nrabbbit\nrabbbit\nExample 2:\n\nInput: s = \"babgbag\", t = \"bag\"\nOutput: 5\nExplanation:\nAs shown below, there are 5 ways you can generate \"bag\" from S.\nbabgbag\nbabgbag\nbabgbag\nbabgbag\nbabgbag\n \n\nConstraints:\n\n1 <= s.length, t.length <= 1000\ns and t consist of English letters.\n'''\n\nfrom typing import *\nfrom pprint import pprint\n\nimport unittest\n\nclass Solution:\n def numDistinct(self, s: str, t: str) -> int:\n # dp[i][j] means starting test from s[i:] and t[j:]\n dp = [[0 for _ in range(len(t))] for _ in range(len(s) + 1)]\n for i in range(len(s) - 1, -1, -1):\n dp[i][len(t) - 1] = dp[i + 1][len(t) - 1]\n if s[i] == t[-1]:\n dp[i][len(t) - 1] += 1\n\n for i in range(len(s) - 1, -1, -1):\n for j in range(len(t) - 2, -1, -1):\n dp[i][j] = dp[i + 1][j]\n if s[i] == t[j]:\n dp[i][j] += dp[i + 1][j + 1]\n return dp[0][0]\n\n\nclass TestSolution(unittest.TestCase):\n def test_case(self):\n examples = (\n ((\"rabbbit\", \"rabbit\"), 3),\n ((\"babgbag\", \"bag\"), 5),\n )\n for first, second in examples:\n self.assert_function(first, second)\n\n def assert_function(self, first, second):\n self.assertEqual(Solution().numDistinct(*first), second,\n msg=\"first: {}; second: {}\".format(first, second))\n\n\nunittest.main()\n\n"} {"blob_id": "394963fe90050b0465886d49ce9646fc730f679b", "repo_name": "rlucas7/scipy", "path": "/scipy/stats/_survival.py", "length_bytes": 3886, "score": 3.625, "int_score": 4, "content": "from dataclasses import make_dataclass\nimport numpy as np\nfrom ._censored_data import CensoredData\n\n\n__all__ = ['ecdf']\n\n\nECDFResult = make_dataclass('ECDFResult', ['x', 'cdf', 'sf'])\n\n\ndef ecdf(sample):\n \"\"\"Empirical cumulative distribution function of a sample.\n\n The empirical cumulative distribution function (ECDF) is a step function\n estimate of the CDF of the distribution underlying a sample.\n\n Parameters\n ----------\n sample : 1D array_like or `stats.CensoredData`\n Besides array_like, instances of `stats.CensoredData` containing\n uncensored observations are supported. Currently, instances of\n `stats.CensoredData` with censored data will result in a\n ``NotImplementedError``, but future support for left-censored,\n right-centered, and interval-censored data is planned.\n\n Returns\n -------\n An object with the following attributes.\n\n x : ndarray\n The unique values at which the ECDF changes.\n cdf : ndarray\n The values of the ECDF corresponding with `x`.\n sf : ndarray\n The empirical survival function, the complement of the ECDF.\n\n Notes\n -----\n When each observation of the sample is a precise measurement, the ECDF\n steps up by ``1/len(sample)`` at each of the observations.\n\n When observations are lower bounds, upper bounds, or both upper and lower\n bounds, the data is said to be \"censored\", and `sample` may be provided as\n an instance of `stats.CensoredData`.\n\n For right-censored data, the ECDF is given by the Kaplan-Meier estimator\n [1]_; other forms of censoring are not supported at this time.\n\n References\n ----------\n .. [1] Conover, William Jay. Practical nonparametric statistics. Vol. 350.\n John Wiley & Sons, 1999.\n\n .. [2] Kaplan, Edward L., and Paul Meier. \"Nonparametric estimation from\n incomplete observations.\" Journal of the American statistical\n association 53.282 (1958): 457-481.\n\n Examples\n --------\n As in the example from [1]_ page 79, five boys were selected at random from\n those in a single high school. Their one-mile run times were recorded as\n follows.\n\n >>> sample = [6.23, 5.58, 7.06, 6.42, 5.20] # one-mile run times (minutes)\n\n The empirical distribution function, which approximates the distribution\n function of one-mile run times of the population from which the boys were\n sampled, is calculated as follows.\n\n >>> from scipy import stats\n >>> res = stats.ecdf(sample)\n >>> res.x\n array([5.2 , 5.58, 6.23, 6.42, 7.06])\n >>> res.cdf\n array([0.2, 0.4, 0.6, 0.8, 1. ])\n\n To plot the result as a step function:\n\n >>> import numpy as np\n >>> import matplotlib.pyplot as plt\n >>> ax = plt.subplot()\n >>> ax.step(np.insert(res.x, 0, 4), np.insert(res.cdf, 0, 0), where='post')\n >>> ax.set_xlabel('One-Mile Run Time (minutes)')\n >>> ax.set_ylabel('Empirical CDF')\n >>> plt.show()\n\n \"\"\"\n if not isinstance(sample, CensoredData):\n try: # takes care of input standardization/validation\n sample = CensoredData(uncensored=sample)\n except ValueError as e:\n message = str(e).replace('uncensored', 'sample')\n raise type(e)(message) from e\n\n if sample.num_censored() == 0:\n res = _ecdf_uncensored(sample._uncensor())\n else:\n # Support censoring in follow-up PRs\n message = (\"Currently, only uncensored data is supported.\")\n raise NotImplementedError(message)\n return res\n\n\ndef _ecdf_uncensored(sample):\n sample = np.sort(sample)\n x, counts = np.unique(sample, return_counts=True)\n\n # [1].81 \"the fraction of [observations] that are less than or equal to x\n cdf = np.cumsum(counts) / sample.size\n\n # [1].89 \"the relative frequency of the sample that exceeds x in value\"\n sf = 1 - cdf\n\n return ECDFResult(x, cdf, sf)\n"} {"blob_id": "71f8184d228f28a0c2c1f65e1ba7719610d2ad25", "repo_name": "arnabs542/interview-notes", "path": "/notes/algo-ds-practice/problems/tree/traversals/diagonal.py", "length_bytes": 626, "score": 3.859375, "int_score": 4, "content": "\"\"\"\nPrint the diagonal traversal of a tree.\n\"\"\"\nfrom ds.tree.binary_tree import BinaryTreeNode as Node\n\n\ndef dfs(root: Node, dist, diagonals):\n if root is None:\n return\n diagonal = diagonals.get(dist, [])\n diagonal.append(root)\n diagonals[dist] = diagonal\n # CAREFUL - We need to go to left first!\n dfs(root.left, dist + 1, diagonals)\n dfs(root.left, dist, diagonals)\n\n\ndef diagonal_traversal(root: Node):\n diagonals = {}\n dfs(root, 0, diagonals)\n diagonals_sorted = []\n for dist in sorted(diagonals.keys()):\n diagonals_sorted.append(diagonals[dist])\n return diagonals_sorted\n"} {"blob_id": "00c6b3a3f8e31dbca539bbbed2d1d2ac7daaafaf", "repo_name": "RobinVercruysse/AdventOfCode", "path": "/2019/day2/Day2.py", "length_bytes": 1087, "score": 3.546875, "int_score": 4, "content": "from typing import List\nfrom sys import exit\n\n\ndef get_result(intcodes: List[int]):\n ptr = 0\n while int(intcodes[ptr]) != 99:\n intcode = intcodes[ptr]\n if intcode == 1:\n ptr1 = intcodes[ptr + 1]\n ptr2 = intcodes[ptr + 2]\n ptr3 = intcodes[ptr + 3]\n intcodes[ptr3] = intcodes[ptr1] + intcodes[ptr2]\n ptr += 4\n elif intcode == 2:\n ptr1 = intcodes[ptr + 1]\n ptr2 = intcodes[ptr + 2]\n ptr3 = intcodes[ptr + 3]\n intcodes[ptr3] = intcodes[ptr1] * intcodes[ptr2]\n ptr += 4\n return intcodes[0]\n\n\noriginal_list = []\nwith open('input') as fp:\n line = fp.readline()\n for code in line.strip().split(','):\n original_list.append(int(code))\nfor noun in range(0, 100):\n for verb in range(0, 100):\n temp_list = original_list.copy()\n temp_list[1] = noun\n temp_list[2] = verb\n result = get_result(temp_list)\n if result == 19690720:\n print('found it: ' + str(noun) + ' & ' + str(verb))\n exit(0)\n"} {"blob_id": "7f2e5421102e147539195599070dbdc7aed7ec73", "repo_name": "zefaxet/school-stuff", "path": "/CSC/470/Assignment 1.py", "length_bytes": 11440, "score": 3.796875, "int_score": 4, "content": "# Name: Edward Auttonberry\n# CWID: 102-48-286\n# DATE: 12/5/2018\n# Assignment 1 -- 3-D Transformations and Perspective Projection\n# Desc: This produces a wire-frame 3D square pyramid on a tkinter canvas\n# \tBasic uniform scaling, translation, and rotation transformations can be applied to the object at uniform intervals\n# \tand will be visibly applied in real time\n\nimport math\nfrom tkinter import *\n\ncanvas_width = 400\ncanvas_height = 400\nd = 500\n\n# ***************************** Initialize Pyramid Object ***************************\n# Definition of the five underlying points\napex = [0, 50, 100]\nbase1 = [-50, -50, 50]\nbase2 = [50, -50, 50]\nbase3 = [50, -50, 150]\nbase4 = [-50, -50, 150]\n\n# Definition of the five polygon faces using the meaningful point names\n# Polys are defined in counter clockwise order when viewed from the outside\nfrontpoly = [apex, base1, base2]\nrightpoly = [apex, base2, base3]\nbackpoly = [apex, base3, base4]\nleftpoly = [apex, base4, base1]\nbottompoly = [base4, base3, base2, base1]\n\n# Definition of the object\npyramid = [bottompoly, frontpoly, rightpoly, backpoly, leftpoly]\n\n# Definition of the Pyramid's underlying point cloud. No structure, just the points.\npyramid_point_cloud = [apex, base1, base2, base3, base4]\n# ************************************************************************************\n\n\n# This function resets the pyramid to its original size and location in 3D space\n# Note that shortcuts like \"apex = [0,50,100]\" will not work as they build new\n# structures rather than modifying the existing Pyramid / PyramidPointCloud\ndef reset_pyramid():\n\t# The pyramid object is a list whose elements are references to sub-lists\n\t# These sub-lists are used in the other methods. This method will not replace the sub-lists, but will instead\n\t# \tmodify the existing references by replacing the current values with the values that were present when the\n\t# \tprogram began.\n\tapex[0] = 0\n\tapex[1] = 50\n\tapex[2] = 100\n\tbase1[0] = -50\n\tbase1[1] = -50\n\tbase1[2] = 50\n\tbase2[0] = 50\n\tbase2[1] = -50\n\tbase2[2] = 50\n\tbase3[0] = 50\n\tbase3[1] = -50\n\tbase3[2] = 150\n\tbase4[0] = -50\n\tbase4[1] = -50\n\tbase4[2] = 150\n\n\n# This function translates an object by some displacement. The displacement is a 3D\n# vector so the amount of displacement in each dimension can vary.\ndef translate(object, displacement):\n\t# Add the displacement vector to each point in the pyramid's point cloud\n\tfor point in object:\n\t\tpoint[0] += displacement[0]\n\t\tpoint[1] += displacement[1]\n\t\tpoint[2] += displacement[2]\n\n\t\n# This function performs a simple uniform scale of an object assuming the object is\n# centered at the origin. The scalefactor is a scalar.\ndef scale(object, scale_factor):\n\t# Take each point in the point cloud and multiply the components by the scale factor\n\tfor point in object:\n\t\tpoint[0] *= scale_factor\n\t\tpoint[1] *= scale_factor\n\t\tpoint[2] *= scale_factor\n\n\n# This function performs a rotation of an object about the Z axis (from +X to +Y)\n# by 'degrees', assuming the object is centered at the origin. The rotation is CCW\n# in a LHS when viewed from -Z [the location of the viewer in the standard postion]\ndef rotate_z(object, degrees):\n\t# Take the xy projection of each point and apply the rotation to the resulting plane's axes\n\t# Python's trig functions take radian inputs\n\t# Input stays positive to preserve counter-clockwise rotation\n\tfor point in object:\n\t\tx = point[0]\n\t\ty = point[1]\n\t\tpoint[0] = x * math.cos(math.radians(degrees)) - y * math.sin(math.radians(degrees))\n\t\tpoint[1] = x * math.sin(math.radians(degrees)) + y * math.cos(math.radians(degrees))\n\t\n\t\n# This function performs a rotation of an object about the Y axis (from +Z to +X)\n# by 'degrees', assuming the object is centered at the origin. The rotation is CW\n# in a LHS when viewed from +Y looking toward the origin.\ndef rotate_y(object, degrees):\n\t# Take the xz projection of each point and apply the rotation to the resulting plane's axes\n\t# Python's trig functions take radian inputs\n\t# Input should be negated to produce clockwise rotation on positive values\n\tdegrees *= -1\n\tfor point in object:\n\t\tx = point[0]\n\t\tz = point[2]\n\t\tpoint[0] = x * math.cos(math.radians(degrees)) - z * math.sin(math.radians(degrees))\n\t\tpoint[2] = x * math.sin(math.radians(degrees)) + z * math.cos(math.radians(degrees))\n\n\n# This function performs a rotation of an object about the X axis (from +Y to +Z)\n# by 'degrees', assuming the object is centered at the origin. The rotation is CW\n# in a LHS when viewed from +X looking toward the origin.\ndef rotate_x(object, degrees):\n\t# Take the yz projection of each point and apply the rotation to the resulting plane's axes\n\t# Python's trig functions take radian inputs\n\t# Input should be negated to produce clockwise rotation on positive values\n\tdegrees *= -1\n\tfor point in object:\n\t\tz = point[2]\n\t\ty = point[1]\n\t\tpoint[2] = z * math.cos(math.radians(degrees)) - y * math.sin(math.radians(degrees))\n\t\tpoint[1] = z * math.sin(math.radians(degrees)) + y * math.cos(math.radians(degrees))\n\n\n# The function will draw an object by repeatedly callying drawPoly on each polygon in the object\ndef draw_object(object):\n\t# Draw each face of the pyramid individually\n\tfor poly in object:\n\t\tdraw_poly(poly)\n\n\n# This function will draw a polygon by repeatedly callying drawLine on each pair of points\n# making up the object. Remember to draw a line between the last point and the first.\ndef draw_poly(poly):\n\t# Assuming the points are aligned in an order that would traverse the polygon's perimeter, draw points between each\n\t# duple of consecutive points in the polygon\n\t# The modulo guarantees that the last point will connect to the first point\n\tpoints = len(poly)\n\tfor i in range(points):\n\t\tdraw_line(poly[i], poly[(i + 1) % points])\n\n\n# Project the 3D endpoints to 2D point using a perspective projection implemented in 'project'\n# Convert the projected endpoints to display coordinates via a call to 'convertToDisplayCoordinates'\n# draw the actual line using the built-in create_line method\ndef draw_line(start, end):\n\t# for the start and end points, calculate their projections and convert those points to points representative of the\n\t# \ttkinter canvas layout, then draw the line\n\tstart_display = convert_to_display_coordinates(project(start))\n\tend_display = convert_to_display_coordinates(project(end))\n\tw.create_line(start_display[0], start_display[1], end_display[0], end_display[1])\n\n\n# This function converts from 3D to 2D (+ depth) using the perspective projection technique. Note that it\n# will return a NEW list of points. We will not want to keep around the projected points in our object as\n# they are only used in rendering\ndef project(point):\n\t# Calculate the projection of the point on the display surface based on an assumed perspective distance from the\n\t# \tviewport, d, and the z position of the point\n\tps = []\n\tfor axis in point:\n\t\tps.append(d*axis/(d + point[2]))\n\treturn ps\n\n\n# This function converts a 2D point to display coordinates in the tk system. Note that it will return a\n# NEW list of points. We will not want to keep around the display coordinate points in our object as \n# they are only used in rendering.\ndef convert_to_display_coordinates(point):\n\t# Based on the dimensions of the canvas, calculate the coordinates on the canvas that match the two-dimensional\n\t# \tcartesian coordinates of the point\n\torigin_x = canvas_width / 2\n\torigin_y = canvas_height / 2\n\tdisplay_coordinate = [point[0] + origin_x, origin_y - point[1]] # y = 0 is top\n\treturn display_coordinate\n\t\n\n# **************************************************************************\n# Everything below this point implements the interface\ndef reset():\n\tw.delete(ALL)\n\treset_pyramid()\n\tdraw_object(pyramid)\n\n\ndef larger():\n\tw.delete(ALL)\n\tscale(pyramid_point_cloud, 1.1)\n\tdraw_object(pyramid)\n\n\ndef smaller():\n\tw.delete(ALL)\n\tscale(pyramid_point_cloud, .9)\n\tdraw_object(pyramid)\n\n\ndef forward():\n\tw.delete(ALL)\n\ttranslate(pyramid_point_cloud, [0, 0, 5])\n\tdraw_object(pyramid)\n\n\ndef backward():\n\tw.delete(ALL)\n\ttranslate(pyramid_point_cloud, [0, 0, -5])\n\tdraw_object(pyramid)\n\n\ndef left():\n\tw.delete(ALL)\n\ttranslate(pyramid_point_cloud, [-5, 0, 0])\n\tdraw_object(pyramid)\n\n\ndef right():\n\tw.delete(ALL)\n\ttranslate(pyramid_point_cloud, [5, 0, 0])\n\tdraw_object(pyramid)\n\n\ndef up():\n\tw.delete(ALL)\n\ttranslate(pyramid_point_cloud, [0, 5, 0])\n\tdraw_object(pyramid)\n\n\ndef down():\n\tw.delete(ALL)\n\ttranslate(pyramid_point_cloud, [0, -5, 0])\n\tdraw_object(pyramid)\n\n\ndef x_plus():\n\tw.delete(ALL)\n\trotate_x(pyramid_point_cloud, 5)\n\tdraw_object(pyramid)\n\n\ndef x_minus():\n\tw.delete(ALL)\n\trotate_x(pyramid_point_cloud, -5)\n\tdraw_object(pyramid)\n\n\ndef y_plus():\n\tw.delete(ALL)\n\trotate_y(pyramid_point_cloud, 5)\n\tdraw_object(pyramid)\n\n\ndef y_minus():\n\tw.delete(ALL)\n\trotate_y(pyramid_point_cloud, -5)\n\tdraw_object(pyramid)\n\n\ndef z_plus():\n\tw.delete(ALL)\n\trotate_z(pyramid_point_cloud, 5)\n\tdraw_object(pyramid)\n\n\ndef z_minus():\n\tw.delete(ALL)\n\trotate_z(pyramid_point_cloud, -5)\n\tdraw_object(pyramid)\n\n\nroot = Tk()\nouterframe = Frame(root)\nouterframe.pack()\n\nw = Canvas(outerframe, width=canvas_width, height=canvas_height)\ndraw_object(pyramid)\nw.pack()\n\ncontrolpanel = Frame(outerframe)\ncontrolpanel.pack()\n\nresetcontrols = Frame(controlpanel, height=100, borderwidth=2, relief=RIDGE)\nresetcontrols.pack(side=LEFT)\n\nresetcontrolslabel = Label(resetcontrols, text=\"Reset\")\nresetcontrolslabel.pack()\n\nresetButton = Button(resetcontrols, text=\"Reset\", fg=\"green\", command=reset)\nresetButton.pack(side=LEFT)\n\nscalecontrols = Frame(controlpanel, borderwidth=2, relief=RIDGE)\nscalecontrols.pack(side=LEFT)\n\nscalecontrolslabel = Label(scalecontrols, text=\"Scale\")\nscalecontrolslabel.pack()\n\nlargerButton = Button(scalecontrols, text=\"Larger\", command=larger)\nlargerButton.pack(side=LEFT)\n\nsmallerButton = Button(scalecontrols, text=\"Smaller\", command=smaller)\nsmallerButton.pack(side=LEFT)\n\ntranslatecontrols = Frame(controlpanel, borderwidth=2, relief=RIDGE)\ntranslatecontrols.pack(side=LEFT)\n\ntranslatecontrolslabel = Label(translatecontrols, text=\"Translation\")\ntranslatecontrolslabel.pack()\n\nforwardButton = Button(translatecontrols, text=\"FW\", command=forward)\nforwardButton.pack(side=LEFT)\n\nbackwardButton = Button(translatecontrols, text=\"BK\", command=backward)\nbackwardButton.pack(side=LEFT)\n\nleftButton = Button(translatecontrols, text=\"LF\", command=left)\nleftButton.pack(side=LEFT)\n\nrightButton = Button(translatecontrols, text=\"RT\", command=right)\nrightButton.pack(side=LEFT)\n\nupButton = Button(translatecontrols, text=\"UP\", command=up)\nupButton.pack(side=LEFT)\n\nupButton = Button(translatecontrols, text=\"DN\", command=down)\nupButton.pack(side=LEFT)\n\nrotationcontrols = Frame(controlpanel, borderwidth=2, relief=RIDGE)\nrotationcontrols.pack(side=LEFT)\n\nrotationcontrolslabel = Label(rotationcontrols, text=\"Rotation\")\nrotationcontrolslabel.pack()\n\nxPlusButton = Button(rotationcontrols, text=\"X+\", command=x_plus)\nxPlusButton.pack(side=LEFT)\n\nxMinusButton = Button(rotationcontrols, text=\"X-\", command=x_minus)\nxMinusButton.pack(side=LEFT)\n\nyPlusButton = Button(rotationcontrols, text=\"Y+\", command=y_plus)\nyPlusButton.pack(side=LEFT)\n\nyMinusButton = Button(rotationcontrols, text=\"Y-\", command=y_minus)\nyMinusButton.pack(side=LEFT)\n\nzPlusButton = Button(rotationcontrols, text=\"Z+\", command=z_plus)\nzPlusButton.pack(side=LEFT)\n\nzMinusButton = Button(rotationcontrols, text=\"Z-\", command=z_minus)\nzMinusButton.pack(side=LEFT)\n\nroot.mainloop()\n"} {"blob_id": "79ac298fc6ca642592eb169d07d091c8fd475a1a", "repo_name": "CoderXv/LeetCodePy", "path": "/PascalTriangle.py", "length_bytes": 1974, "score": 4.28125, "int_score": 4, "content": "# --- Introduction ---\n\"\"\"\n\tGiven numRows, generate the first numRows of Pascal's triangle.\n\tFor example, given numRows = 5.\n\tReturn:\n\t[\n\t\t [1],\n\t\t[1,1],\n\t [1,2,1],\n\t [1,3,3,1],\n\t [1,4,6,4,1]\n\t]\n\"\"\"\n\n# --- Solution ---\n\"\"\"\n\t- This triangle is named YangHui triangle in China.\n\t- It shows the combination's result as :\n\tC(0,0)\n\tC(1,0),C(1,1)\n\tC(2,0),C(2,1),C(2,2)\n\tC(3,0),C(3,1),C(3,2),C(3,3)\n\tC(4,0),C(4,1),C(4,2),C(4,3),C(4,4)\n\tC(5,0),C(5,1),C(5,2),C(5,3),C(5,4),C(5,5)\n\t- The C(n,k) function is:\n\tC(n,k) = n! / k! * (n-k)!\n\tn! is the factorial of n.\n\tpermutation in Chinese Pinyin is Pai-lie.\n\"\"\"\n\n# --- Code ---\nimport math\nclass Solution(object):\n def generate(self, numRows):\n \"\"\"\n :type numRows: int\n :rtype: List[List[int]]\n \"\"\"\n\t\tif numRows == 0:\n\t\t\treturn = []\n\t\tresult = []\n\t\tfor row in xrange(0, numRows):\n\t\t\tcur_row = []\n\t\t\tfor col in xrange(0, row + 1):\n\t\t\t\t# row!\n\t\t\t\tf_row = math.factorial(row)\n\t\t\t\t# col!\n\t\t\t\tf_col = math.factorial(col)\n\t\t\t\t# (row-col)!\n\t\t\t\tf_row_sub_col = math.factorial(row-col)\n\t\t\t\t# C(row, col)\n\t\t\t\tnumber = f_row / f_col * f_row_sub_col\n\t\t\t\tcur_row.append(number)\n\t\t\tresult.append(cur_row)\n\t\t\t\n# --- One more thing ---\n# There's also a smart method, by using map function.\n\"\"\"\n\t- map(function, sequence) calls function(item) for each of the sequence's items\n\tand returns a list of the return values.\n\t- More than one sequence may be passed; the function must then have as many\n\targuments as there are sequence (or None if some sequence is shorter than another).\n\t- the current row of the triangle can be made by offset sum of the previous row.\n\t- E.g:\n\t 0 1 3 3 1\n\t +1 3 3 1 0\n\t -----------\n\t 1 4 6 4 1\n\"\"\"\nclass Solution(object):\n def generate(self, numRows):\n \"\"\"\n :type numRows: int\n :rtype: List[List[int]]\n \"\"\"\n\t\tresult = [[1]]\n\t\tfor i in range(1,numRows):\n\t\t\treult += [map(lambda x,y: x+y, [0]+result[-1], result[-1]+[0])]\n\t\treturn result[:numRows]\n\n\t\t\t\t\n\t\t\t\t\n\t\t\n"} {"blob_id": "53934f1b1645d147841985e09f7ee40c80d2cf94", "repo_name": "vedadeepta/Tic-Tac-Toe", "path": "/LookAhead.py", "length_bytes": 1857, "score": 3.734375, "int_score": 4, "content": "from random import randint\n\npos = -1\n\ndef checkWin(board):\n\n\ti=0\n\n\twhile i < len(board):\n\n\t\tif(board[i] != 'n' and board[i] == board[i+1] and board[i] == board[i+2] and board[i+1] == board[i+2]):\n\t\t\t\n\t\t\treturn True\n\n\t\ti = i + 3\n\n\t\n\t#columns\n\ti=0\n\twhile i < 3:\n\n\t\tif(board[i] != 'n' and board[i] == board[i+3] and board[i] == board[i+6] and board[i+3] == board[i+6]):\n\n\t\t\treturn True\n\n\t\ti = i + 1\n\t\n\t#diagonals\n\t\n\tif(board[0] != 'n' and board[0] == board[4] and board[0] == board[8] and board[4] == board[8]):\n\n\t\treturn True\n\t\n\telif(board[2] != 'n' and board[2] == board[4] and board[2] == board[6] and board[4] == board[6]):\n\n\t\treturn True\n\n\telse:\n\n\t\treturn False\n\ndef checkScore(board,player):\n\n\tif(checkWin(board)):\n\n\t\tif(player == 0):\n\t\t\treturn 1\n\t\telse:\n\t\t\treturn -1\n\telse:\n\n\t\tfor i in board:\n\t\t\tif(i == 'n'):\n\t\t\t\treturn 10\n\n\t\treturn 0\n\n\t\ndef minimax(board,player):\n\n\tscore = checkScore(board,(player + 1) % 2)\n\n\tif( score == 0 or score == 1 or score == -1):\n\t\treturn score\n\n\telse:\n\n\t\tmoves = []\n\t\tscoreList = []\n\t\n\t\tfor i in xrange(9):\n\t\n\t\t\tif (board[i] == 'n'):\n\t\t\t\tmoves.append(i)\n\t\n\t\tfor i in moves:\n\t\n\t\t\tif (player == 0):\n\t\t\t\tboard[i] = 'o'\n\t\t\telse:\n\t\t\t\tboard[i] = 'x'\n\t\n\t\t\ttemp= minimax(board,(player + 1) % 2)\n\t\t\tscoreList.append(temp)\n\t\t\tboard[i] = 'n'\n\t\n\t\tif(player == 0):\n\t\t\tglobal pos \n\t\t\tpos = moves[scoreList.index(max(scoreList))]\n\t\t\treturn max(scoreList)\n\t\t\t#return max(scoreList), moves[len(scoreList) - scoreList[::-1].index(max(scoreList)) - 1]\n\t\telse:\n\t\t\tglobal pos \n\t\t\tpos = moves[scoreList.index(min(scoreList))]\n\t\t\treturn min(scoreList)\n\t\t\t#return min(scoreList), moves[len(scoreList) - scoreList[::-1].index(min(scoreList)) - 1]\n\ndef checkEmpty(board):\n\n\tfor i in board:\n\t\tif(i != 'n'):\n\t\t\treturn False\n\treturn True\n\ndef getPos(board,player):\n\n\tif(checkEmpty(board)):\n\t\treturn randint(0,8)\n\n\n\tminimax(board,player)\n\n\treturn pos\n"} {"blob_id": "a9c5dd611855f655328bf3486b0851f641c24afc", "repo_name": "AndJM/Dynamic-Programming", "path": "/spelling correction/load_and_print.py", "length_bytes": 2908, "score": 3.703125, "int_score": 4, "content": "\"\"\"Some tools for measuring the edit distance of two strings\"\"\"\n\nimport string\nfrom timeit import default_timer\nfrom tools import *\n\n\ndef edit_distance(seq_x, seq_y):\n \"\"\"\n The dissimilarity of two strings (the minimum number of single character\n insertions, deletions, and substiutions to transform one string into\n another) is calculated using the similarity of the two strings.\n\n The values below are such that the score from the resulting global\n alignment yields the edit distance.\n \"\"\"\n diag_score = 2\n off_diag_score = 1\n dash_score = 0\n a = set(seq_x) | set(seq_y)\n sm = build_scoring_matrix(a, diag_score, off_diag_score, dash_score)\n am = compute_alignment_matrix(seq_x, seq_y, sm, 'global')\n s, *rest = compute_global_alignment(seq_x, seq_y, sm, am)\n return len(seq_x) + len(seq_y) - s\n\n\ndef read_words(filename):\n \"\"\"Load word list from the file and return list of strings.\"\"\"\n # word_file = urllib2.urlopen(filename)\n with open(filename) as word_file:\n words = word_file.read()\n word_list = words.split('\\n')\n word_list = word_list[:-1]\n print(\"Loaded\", len(word_list), \"words.\")\n return word_list\n\n\ndef check_spelling(checked_word, dist, word_list):\n \"\"\"\n Iterate through 'word_list' and returns the set of words that are within\n an edit distance 'dist' of the string 'checked_word'.\n \"\"\"\n result = set([])\n for word in word_list:\n if edit_distance(checked_word, word) <= dist:\n result.add(word)\n return result\n\n\ndef example1():\n words = read_words('assets_scrabble_words3.txt')\n print(check_spelling(\"humble\", 1, words))\n print(check_spelling(\"firefly\", 2, words))\n\n\ndef quick_check(checked_word, word_list, dist=1):\n \"\"\"\n Return words of edit distance 1 or 2 from checked_word in word_list.\n\n Adapted from P. Norvig 'How to Write a Spelling Corrector' 2007\n http://norvig.com/spell-correct.html\n \"\"\"\n word_set = set(word_list)\n\n def edit_one(word):\n alphabet = string.ascii_lowercase\n splits = [(word[:k], word[k:]) for k in range(len(word)+1)]\n deletions = [L + R[1:] for L, R in splits]\n insertions = [L + a + R for L, R in splits for a in alphabet]\n substitutions = [L + a + R[1:] for L, R in splits for a in alphabet]\n return set(deletions + insertions + substitutions)\n\n def edit_two(word):\n return set([word2 for word1 in edit_one(word) for word2 in edit_one(word1)])\n\n if dist == 1:\n return [word for word in edit_one(checked_word) if word in word_list]\n elif dist == 2:\n return [word for word in edit_two(checked_word) if word in word_list]\n\n\ndef example2():\n words = read_words('assets_scrabble_words3.txt')\n print(quick_check(\"humble\", words))\n print(quick_check(\"firefly\", words))\n\n\nif __name__ == '__main__':\n # example1()\n example2()\n exit()\n"} {"blob_id": "9cf7bb2c61c8524682299e568006470484d77b57", "repo_name": "gdc3000/bradfield-ds-algorithms", "path": "/roman_numeral.py", "length_bytes": 8053, "score": 3.921875, "int_score": 4, "content": "\"\"\"\nGoal: Cultivating the problem solving process\n\nCourse structure:\n 1) Pre-work: Do and send (not optional). Send directly to Elliot.\n 2) Live practice in the session. Reserve the right to call by name.\n 3) Post-work: optional (do at own pace, maybe months after course)\n\n\"Problem-solving is not a spectator sport. Need to put in a lot of practice.\"\n\nWarm-up problem\n-Historian\n-Someone handed you lots stack of documents with roman numerals\n-Only moves forward XVII (17). E.g. IX (9)not going to happen. Would be VIIII instead.\n-Symbols:\n -M 1000\n -D 500\n -C 100\n -L 50\n -X 10\n -V 5\n -I 1\n\nEdge cases:\n-Lower case input -> assume not\n-Could be out of order or invalid -> assume not\n-Should I throw an exception if an invalid roman numeral is passed? - Yes\n-Program passed single string? -> assume it is\n\nApproach:\n-Check if it is a valid roman numeral\n-Parse string letter by letter. Use dictionary to store values of each letter. \nLookup value in dictionary and add to counter. Return counter when done parsing\ninput phrase.\n\"\"\"\n\ndef convert_roman_numeral(numeral):\n total = 0\n numeral_dict = {\n 'M':1000,\n 'D':500,\n 'C':100,\n 'L':50,\n 'X':10,\n 'V':5,\n 'I':1\n }\n for letter in numeral:\n if letter in numeral_dict:\n total += numeral_dict[letter]\n return total\n\n\"\"\"\nReflection: Thoughts on process:\n-Write conditions\n -Assumptions\n -Data needed\n-Consider data structures that could help\n-Speak to someone (\"rubber duck\")\n-Think about test cases\n-Write all the edge cases that I think of\n-Start by thinking about small examples (reduce problems)\n-Think about related problems that you've solved before\n -\"more problems you do, the better you'll be\"\n-Think of different ways to solve every problem\n -\"Any problem has a bunch of solutions... it frees you... you don't have to find magic\n password that interviewer has in mind.\"\n -Try pushing yourself to find a very different approach, rather than tweaking approach\n -First solution is almost always not optimized\n-Polya's comment: \"all people, including brilliant mathematiciains go through this process\"... all problem-solving is bumbling\n\nOther solutions where similar to mine.\n\"\"\"\n\n\"\"\"\nNext problem: society has new rule there can be subtractive pairs.\n E.g. IX, represents 9\n\n If a smaller number comes before a larger number, then treat it as \"subtractive pair\"\n E.g. I < X, so treat I as subtraction\n Unless TWO NUMBERS handle as subtractive pair\n Otherwise, numbers must go bigger to smaller. \n\n Not all pairs are allowed. Precisely:\n -I can preceede V or X\n -X can precede L, C\n -C can precede D or M.\n\n Can assume that given roman numerals are valid.\n\nApproach:\n -assume valid roman numeral is passed\n -initialize counter\n -initialize dictionaries needed\n -loop through string letter by letter:\n -if not on last letter, check if given letter is less than next letter\n -if true:\n -make sure next letter is in list of valid letters. Create a dictionary where\n the valid next letters are associated with each letter. Throw an exception if\n either key is not in this dictionary or if next letter is not valid.\n -subtract current letter\n -if false:\n -add current letter\n\nQuestions I would ask:\n\"\"\"\ndef convert_roman_numeral_2(numeral):\n total = 0\n numeral_dict = {\n 'M':1000,\n 'D':500,\n 'C':100,\n 'L':50,\n 'X':10,\n 'V':5,\n 'I':1\n }\n valid_next_letter = {\n 'I':['V','X'],\n 'X':['L','C'],\n 'C':['D','M']\n }\n for i, letter in enumerate(numeral):\n if i == len(numeral) - 1:\n total += numeral_dict[letter]\n else:\n next_letter = numeral[i+1]\n if numeral_dict[letter] < numeral_dict[next_letter]:\n assert next_letter in valid_next_letter[letter]\n total -= numeral_dict[letter]\n else:\n total += numeral_dict[letter]\n return total\n\n\"\"\"\nReflection:\n-Important to worry about boundary condition since checking both next letter and current letter\n-Two solutions: Grouping into two versus look ahead.\n-Recursive ideas?\n-Check with \"slicer\" to handle edge case in Python (e.g. string[i+1:i+2])\n-Another idea:\n -List with tuples with valid pairs\n -Include both 1-letter (X) and 2-letter (XC) numerals in list\n -One outer loop goes through all numerals\n -Peel off numerals in order that match (s.startswith)\n -Add value to result\n -User slicer to increment list s = s[len(numeral):]\n -Return value\n\"\"\"\ndef convert_roman_numeral_3(numeral):\n total = 0\n s=numeral\n numeral_list = [\n ('M',1000),\n ('CM',900),\n ('D',500),\n ('CD',400),\n ('C',100),\n ('XC',90),\n ('L',50),\n ('XL',40),\n ('X',10),\n ('IX',9),\n ('V',5),\n ('IV',4),\n ('I',1)\n ]\n for i in numeral_list:\n num, val = i\n while s.startswith(num):\n total += val\n s = s[len(num):]\n return total\n\n\n\"\"\"\nChallenge problem: Let's say that given numeral. Convert shortest possible.\n e.g. IIIII -> V\n\nProblem: Given a roman numeral, shorten it.\n\nEdge cases:\n -What if you get passed more than two values in a row that are lower than the next one.\n -> Assume this won't happen\n -Assume input can't be greater than 3000\n\nApproach:\n -Define list of values for all roman numerals and subtracted pairs (1000 to 1)\n -Accept input \"long\" roman numeral\n -For each roman numeral in the list, count the number appearing in the input (starting with the\n highest letter). If there are more than 4+ occurences of this letter and it is I,X,C or M, then \n replace it with the next largest number up. If there are more than 2+ occurence of other numbers, \n then replace it with the next letter up the numeral list.\n -Edge case: If you encounter two \"subtracted pairs\" in a row, this won't work.\n -\n\n\"\"\"\nimport math\ndef short_roman_numeral(numeral):\n numeral_list = [\n ('M',1000),\n ('CM',900),\n ('D',500),\n ('CD',400),\n ('C',100),\n ('XC',90),\n ('L',50),\n ('XL',40),\n ('X',10),\n ('IX',9),\n ('V',5),\n ('IV',4),\n ('I',1)\n ]\n output = ''\n numeral_count = len(numeral_list)-1\n\n #iterate through whole range\n for i in range(numeral_count, 0, -4):\n #count total value of symbols in group\n val_sum = 0\n for j in range(i, i-4, -1):\n sym, val = numeral_list[j]\n sym_length = len(sym)\n while numeral.endswith(sym):\n numeral = numeral[:-sym_length]\n val_sum += val\n\n #bump any amount over ten up to the next tier, append to end of numeral\n ten_sym, ten_val = numeral_list[i-4]\n ten_count = val_sum // ten_val\n val_sum = val_sum % ten_val\n numeral = numeral + ten_count * ten_sym\n \n #append write combo of symbols to output for remaining val_sum\n append = ''\n for j in range(i-3,i+1,1):\n sym, val = numeral_list[j]\n append_count = val_sum // val\n val_sum = val_sum % val\n append += sym * append_count\n \n output = append + output\n\n #append Ms to output\n sym, val = numeral_list[0]\n sym_length = len(sym)\n while numeral.endswith(sym):\n numeral = numeral[:-sym_length]\n output = sym + output\n\n return output\n \nassert short_roman_numeral('MDLXIIIII') == 'MDLXV'\nassert short_roman_numeral('MDLXIIII') == 'MDLXIV'\nassert short_roman_numeral('MDLXIIIIIIIII') == 'MDLXIX'\nassert short_roman_numeral('MDLXXXXXIIIIIIIII') == 'MDCIX'\nassert short_roman_numeral('MDLXXXXXIVIV') == 'MDCVIII'\nassert short_roman_numeral('MCMDDDD') == 'MMMCM'\nassert short_roman_numeral('MCMDDDDIVIV') == 'MMMCMVIII'"} {"blob_id": "225b65f009d4dee9f12427950b5613802885a6af", "repo_name": "holsapple/descriptive-statistics", "path": "/final_project.py", "length_bytes": 7587, "score": 4.375, "int_score": 4, "content": "\"\"\" Intro to Descriptive Statistics - Final Project\n\nThis project simulates drawing three cards from a standard deck of cards,\nand generates the corresponding sampling distribution.\n\n - Raymond W. Holsapple\n - last update: Sep 3, 2017\n\n\"\"\"\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom scipy import stats\n\n# card value order: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King\ncardvalues = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]\n# Spades (1-13), Diamonds (14-26), Clubs (27-39), Hearts (40-52)\nvaluemap = {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10, 11: 10, 12: 10, 13: 10,\n 14: 1, 15: 2, 16: 3, 17: 4, 18: 5, 19: 6, 20: 7, 21: 8, 22: 9, 23: 10, 24: 10, 25: 10, 26: 10,\n 27: 1, 28: 2, 29: 3, 30: 4, 31: 5, 32: 6, 33: 7, 34: 8, 35: 9, 36: 10, 37: 10, 38: 10, 39: 10,\n 40: 1, 41: 2, 42: 3, 43: 4, 44: 5, 45: 6, 46: 7, 47: 8, 48: 9, 49: 10, 50: 10, 51: 10, 52: 10}\ngenerate_figs = False\n\n\ndef drawcards(n):\n draw = np.random.choice(np.arange(1, 53), size=n, replace=False)\n return sum([valuemap[card] for card in draw])\n\n\ndef popdistribution():\n pophistvalues = []\n pophistbins = np.arange(2, 31) + 0.5\n for i in np.arange(1, 51):\n for j in np.arange(i+1, 52):\n for k in np.arange(j+1, 53):\n pophistvalues.append(sum([valuemap[i], valuemap[j], valuemap[k]]))\n populationdist = np.histogram(pophistvalues, bins=np.arange(3, 31))\n mu = np.mean(pophistvalues)\n popmed = np.median(pophistvalues)\n sigma = np.std(pophistvalues)\n print()\n print('The mean of the population is', mu)\n print('The median of the population is', popmed)\n print('The population standard deviation is', sigma)\n print()\n if generate_figs:\n plt.figure()\n plt.hist(pophistvalues, pophistbins, normed=1, edgecolor='black', linewidth=0.5, facecolor='red')\n plt.xlabel('3-Card Draw Value')\n plt.ylabel('Relative Frequency')\n plt.title('3-Card Draw Experiment Histogram')\n plt.xticks(np.arange(3, 31), fontsize=6)\n plt.savefig('population_distribution.png', dpi=1000)\n return populationdist\n\n\ndef meansampdist(n, numberdraws, numberexperiments):\n samplemeans = []\n for k in range(n):\n sample = []\n for j in range(numberexperiments):\n sample.append(drawcards(numberdraws))\n samplemeans.append(np.mean(sample))\n meanofmeans = np.mean(samplemeans)\n stdofmeans = np.std(samplemeans, ddof=1)\n print()\n print('The mean of the sample means is', meanofmeans)\n print('The standard deviation of the sample means is', stdofmeans)\n print()\n if generate_figs:\n plt.figure()\n plt.hist(samplemeans, bins='auto', normed=1, edgecolor='black', linewidth=0.5, facecolor='blue')\n plt.xlabel('Sample Mean')\n plt.ylabel('Relative Frequency')\n plt.title('Sampling Distribution of Sample Means')\n plt.savefig('sampling_dist_sample_means.png', dpi=1000)\n return meanofmeans, stdofmeans\n\nif __name__ == '__main__':\n\n # 1. First, create a histogram depicting the relative frequencies of the card values.\n histvalues = cardvalues * 4\n histbins = np.arange(11) + 0.5\n if generate_figs:\n plt.figure()\n plt.hist(cardvalues, histbins, normed=1, edgecolor='black', linewidth=0.5, facecolor='green')\n plt.xlabel('Card Value')\n plt.ylabel('Relative Frequency')\n plt.title('Card Value Histogram')\n plt.xticks(np.arange(1, 11))\n plt.savefig('card_values_hist.png', dpi=1000)\n # Comment the line below if you don't want the population histogram and parameters.\n populationdist = popdistribution()\n\n # 2. Now, we will get samples for a new distribution. To obtain a single sample, shuffle your deck of cards and draw\n # three cards from it. (You will be sampling from the deck without replacement.) Record the cards that you have drawn\n # and the sum of the three cards\u2019 values. Replace the drawn cards back into the deck and repeat this sampling procedure\n # a total of at least thirty times.\n numdraws = 3\n numexpinsample = 30\n sample = []\n for k in range(numexpinsample):\n sample.append(drawcards(numdraws))\n\n # 3. Let\u2019s take a look at the distribution of the card sums. Report descriptive statistics for the samples you have drawn.\n # Include at least two measures of central tendency and two measures of variability.\n samplemean = np.mean(sample)\n samplemedian = np.median(sample)\n samplestd = np.std(sample, ddof=1)\n samplesem = stats.sem(sample)\n print()\n print('The mean of the sample is', samplemean)\n print('The median of the sample is', samplemedian)\n print('The sample standard deviation is', samplestd)\n print('The standard error of the mean is', samplesem)\n print()\n\n # 4. Create a histogram of the sampled card sums you have recorded. Compare its shape to that of the original distribution.\n # How are they different, and can you explain why this is the case?\n # print(sample)\n samplebins = np.arange(2, 31) + 0.5\n if generate_figs:\n plt.figure()\n plt.hist(sample, samplebins, normed=1, edgecolor='black', linewidth=0.5, facecolor='purple')\n plt.xlabel('3-Card Draw Value')\n plt.ylabel('Relative Frequency')\n plt.title('3-Card Draw Sample Histogram')\n plt.xticks(np.arange(3, 31), fontsize=6)\n plt.savefig('sample_distribution.png', dpi=1000)\n # Comment the line below if you don't want to simulate a sampling distribution of the mean.\n meanofmeans, stdofmeans = meansampdist(50, numdraws, numexpinsample)\n\n # 5. Make some estimates about values you will get on future draws.\n # Within what range will you expect approximately 90% of your draw values to fall? (<--- I think this question is ambiguous or should be worded better.)\n # What is the approximate probability that you will get a draw value of at least 20? Make sure you justify how you obtained your values.\n # I'm going to approach this part of the project in two ways. First, I am going to answer the question as if we are talking about probabilities\n # regarding the mean of a sample the same size as I chose in the variable 'numexpinsample'. The sampling distribution of sample means will be approximately\n # normally distributed, but the underlying distribution will not be. As the problem is worded it seems to me as if it is asking to make inferences about\n # a single draw of 3 cards, which is a sample of size 1. To answer the questions from that perspective, we need to use the actual distribution of the\n # experiment or at least use an approximation to that distribution by performing the experiment many times. I have computed the actual discreet distribution\n # so I will use that to answer the questions as well.\n leftz = stats.norm.ppf(0.05)\n rightz = -leftz\n lower90lim = (leftz * stdofmeans) + meanofmeans\n upper90lim = (rightz * stdofmeans) + meanofmeans\n print()\n print('The probability that the mean of a sample of size', numexpinsample, 'will be between', lower90lim, 'and', upper90lim, 'is 0.9 or 90%')\n z20 = (20 - meanofmeans) / stdofmeans\n prob_atleast_20 = 1 - stats.norm.cdf(z20)\n print('The probability that the mean of a sample of size', numexpinsample, 'will be at least 20 is', prob_atleast_20)\n print()\n draw_prob_atleast_20 = sum(populationdist[0][16::])/sum(populationdist[0])\n print('The probability that a single draw of 3 cards will result in a sum of at least 20 is', draw_prob_atleast_20)"} {"blob_id": "7cb013fd0d22370360e46c26bdcdc8a6dacda1f7", "repo_name": "sunyi1001/leetcode", "path": "/jianzhioffer/\u4e8c\u53c9\u641c\u7d22\u6811\u540e\u5e8f\u904d\u5386.py", "length_bytes": 757, "score": 3.5, "int_score": 4, "content": "class Solution:\n def validateStackSequences(self, nums):\n\n length = len(nums)\n\n if length == 0:\n return False\n\n root = nums[-1]\n i = 0\n while i < length - 1:\n if nums[i] > root:\n break\n i += 1\n j = i\n while j < length - 1:\n if nums[j] < root:\n return False\n j += 1\n # print(i)\n\n left = True\n if i > 0:\n left = self.validateStackSequences(nums[:i])\n right = True\n if i < length - 1:\n right = self.validateStackSequences(nums[i:length-1])\n\n return left and right\n\n\nnums = [5,7,6,9,11,10,8]\nsol = Solution()\nres = sol.validateStackSequences(nums)\nprint(res)\n\n"} {"blob_id": "f76e34686cc8d0283d1930b645c7b37c192b93d5", "repo_name": "Dandya/My-programms", "path": "/Python/FacNum.py", "length_bytes": 497, "score": 3.65625, "int_score": 4, "content": "from math import sqrt\r\n\r\ndef FacNum(number, result = [1], lastDiv = 2):\r\n print(number)\r\n if number == 1:\r\n return result\r\n limit = int(sqrt(number)) + 1\r\n if limit < lastDiv:\r\n result.append(number)\r\n return result\r\n div = lastDiv\r\n while div != limit:\r\n if number%div == 0:\r\n result.append(div)\r\n number //= div\r\n return FacNum(number, result, div)\r\n div += 1\r\n result.append(number)\r\n return result\r\n\r\n"} {"blob_id": "b7fc32b7e082463f0f9817ee927dc44cc704e1f7", "repo_name": "manuel-mariani/TTRPG-Probabilistic-combat-estimator", "path": "/src/aleatory_variable.py", "length_bytes": 7668, "score": 3.625, "int_score": 4, "content": "import numpy as np\nfrom src.dice import Dice\nimport matplotlib.pyplot as plt\n\n\n# ------------------------------------------- #\n# Aleatory Variable #\n# ------------------------------------------- #\nclass AleatoryVariable:\n def __init__(self, domain: np.ndarray, distribution: np.ndarray):\n self.domain = domain\n self.distribution = distribution\n\n # ------------------------------------------- #\n\n @staticmethod\n def from_exact(value: int, bounds: (int, int) = None):\n \"\"\" Create an Aleatory Variable from an integer. @bounds determines the domain of the variable\"\"\"\n if bounds is None:\n return AleatoryVariable(domain=np.array([value]), distribution=np.ones(1))\n else:\n lb, ub = bounds\n domain = np.arange(lb, ub + 1)\n assert value in domain\n distribution = np.zeros(ub - lb + 1)\n distribution[domain == value] = 1\n return AleatoryVariable(domain, distribution)\n\n # ------------------------------------------- #\n\n @staticmethod\n def from_dice(dice: Dice):\n \"\"\" Create an Aleatory Variable from a Dice object\"\"\"\n return AleatoryVariable(domain=dice.values, distribution=dice.pmf)\n\n # ------------------------------------------- #\n\n @staticmethod\n def from_hit(dice: Dice, target: int):\n \"\"\" Create an Aleatory Variable using a Dice and a target [Dice(x >= target]\"\"\"\n domain = np.arange(0, 2)\n distribution = np.array(dice.prob_against(target))\n return AleatoryVariable(domain, distribution)\n\n # ------------------------------------------- #\n\n def set_domain_bounds(self, low_bound, upp_bound):\n \"\"\" Extends the domain of the aleatory variable\"\"\"\n assert low_bound <= self.domain[0] and upp_bound >= self.domain[-1]\n # If the new domain would be the same as the current, return\n if low_bound == self.domain[0] and upp_bound == self.domain[-1]:\n return\n\n # Define the new domain and initialize the distribution\n new_domain = np.arange(low_bound, upp_bound + 1)\n new_distribution = np.zeros(len(new_domain))\n\n # Copy the old distribution into the new, starting and ending at the extremities of the union of the two\n start_index = np.where(new_domain == self.domain[0])[0][0]\n stop_index = start_index + len(self.domain)\n new_distribution[start_index:stop_index] = self.distribution\n\n # Replace the domain and distribution\n self.domain = new_domain\n self.distribution = new_distribution\n\n # ------------------------------------------- #\n\n def __pow__(self, n):\n \"\"\"\n Elevate the Aleatory Variable to an integer value\n n > 0\n performs n-1 convolutions on the distribution and extends the domain wrt the result of the convolutions.\n n < 0\n same case of n > 0, but the domain is flipped\n n = 0\n returns an aleatory variable centered in 0, with P(0) = 1\n \"\"\"\n assert isinstance(n, int)\n if n == 0:\n return AleatoryVariable.from_exact(0)\n else:\n domain = np.arange(self.domain[0] * abs(n), self.domain[-1] * abs(n) + 1)\n distribution = self.distribution.copy()\n for t in range(abs(n) - 1):\n distribution = np.convolve(distribution, self.distribution)\n if n > 0:\n return AleatoryVariable(domain, distribution)\n return AleatoryVariable(np.flip(-domain), np.flip(distribution))\n\n # ------------------------------------------- #\n\n def __sub__(self, other):\n \"\"\" Subtracts an Aleatory Variable @other to the current. Inverse of __add__ \"\"\"\n assert isinstance(other, AleatoryVariable)\n\n # Iterate through the length of the current variable. For each probability in the distribution do:\n distribution = np.zeros(len(self))\n for s in range(len(self)):\n # 1. Multiply it with the entire other distribution\n weighted_partial = other.distribution * self.distribution[s]\n\n # 2. Store the new weighted distribution, but with its domain \"shifted\" according to the two domains\n for o in range(len(weighted_partial)):\n index = s - other.domain[o]\n # Keep the distribution inside the current domain by adding it to the extrema\n if index < 0:\n distribution[0] += weighted_partial[o]\n elif index >= len(self):\n distribution[-1] += weighted_partial[o]\n else:\n distribution[index] += weighted_partial[o]\n\n return AleatoryVariable(self.domain, distribution)\n\n # ------------------------------------------- #\n\n def __add__(self, other):\n \"\"\" Adds an Aleatory Variable @other to the current. Inverse of __sub__ \"\"\"\n assert isinstance(other, AleatoryVariable)\n tmp = AleatoryVariable(other.domain * -1, other.distribution)\n return self - tmp\n\n # ------------------------------------------- #\n\n def __mul__(self, other):\n \"\"\"\n Multiply an Aleatory Variable @other with the current. Despite the name, this operation is not commutative.\n \"\"\"\n assert isinstance(other, AleatoryVariable)\n\n # Multiply the two domains to form the resulting\n low_bound = self.domain[0] * other.domain[0]\n upp_bound = self.domain[-1] * other.domain[-1]\n domain = np.arange(low_bound, upp_bound + 1)\n\n # Initialize a distribution and a variable\n distribution = np.zeros(len(domain))\n variable = AleatoryVariable(domain, distribution)\n\n # Iterate through the length of the other variable, performing:\n for o in range(len(other)):\n # 1. Elevate the current variable to a value of the other variable\n tmp = (self ** int(other.domain[o]))\n\n # 2. Weight the result of 1 (distribution) based on the probability of the other value\n tmp.distribution *= other.distribution[o]\n\n # 3. Sum the weighted distribution to the new distribution, shifted accordingly to the domain\n start_index = np.where(domain == tmp.domain[0])[0][0]\n stop_index = start_index + len(tmp)\n variable.distribution[start_index:stop_index] += tmp.distribution\n\n # Normalize the variable and return it\n variable.distribution /= sum(variable.distribution)\n return variable\n\n # ------------------------------------------- #\n\n def __len__(self):\n return len(self.domain)\n\n def __str__(self):\n pairs = list(zip(self.domain, np.around(self.distribution, 6)))\n return str(pairs)\n\n # ------------------------------------------- #\n\n def plot(self, title=None):\n if title is not None:\n plt.suptitle(title, fontsize=18)\n plt.bar(self.domain, self.distribution)\n plt.show()\n\n # ------------------------------------------- #\n\n\n# ------------------------------------------- #\n# Example #\n# ------------------------------------------- #\nif __name__ == '__main__':\n av1 = AleatoryVariable.from_dice(Dice(1, 20, 0, 3))\n av1.plot(\"$V_1$\")\n\n av2 = AleatoryVariable.from_dice(Dice(1, 6))\n av2.plot(\"$V_2$\")\n\n power_av2 = av2 ** 3\n power_av2.plot(\"$V_2^3$\")\n AleatoryVariable.from_dice(Dice(3, 6)).plot(\"3d6\")\n\n minus = av1 - av2\n minus.plot(\"$V_1 - V_2$\")\n\n times = av1 * av2\n times.plot(\"$V_1 \\\\times V_2$\")\n\n times = av2 * av1\n times.plot(\"$V_2 \\\\times V_1$\")\n\n"} {"blob_id": "1ade0b44654ebddcd8e4199249ef73ce8c7fac1e", "repo_name": "rushabh0701/Python-Assignments", "path": "/population_growth (1).py", "length_bytes": 1498, "score": 3.625, "int_score": 4, "content": "import math \r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n## Rabbit data\r\nrb = 0.75 ## birth rate of rabbit\r\nrd = 0.67 ## death rate of rabbit\r\nrg = rb - rd ## growth rate\r\nrab = 1000 ## Initial rabbit count\r\n\r\n## Mice Data\r\nmb = 0.7 ## birth rate of mice\r\nmd = 0.55 ## death rate of mice\r\nmice = 500 ## Initial mice count\r\n\r\n## Fox data\r\nfb = 0.5\r\nfd = 0.48\r\n\r\nfox = 100 ## Initial fox count\r\na = 0.001\r\nb = 0.002\r\nc = 0.0002\r\nd = 0.002\r\n\r\nr = 4.4*10**(-8)\r\ns = 4.4*10**(-8)\r\nt = 4.4*10**(-8)\r\n\r\nlist_r = []\r\nlist_f = []\r\nlist_m = []\r\n\r\nprint(\"Initial Population of Rabbit\", rab)\r\nprint(\"Initial Population of fox\", fox)\r\nprint(\"Initial Population of mice\", mice)\r\n\r\nfor i in range(15):\r\n dr = rb*rab - a*rab*fox - r*rab*rab\r\n dm = mb*mice - c*mice*fox - t*mice*mice\r\n df = -fb*fox + b*rab*fox + d*mice*fox - s*fox*fox\r\n print(\"New population of rabbit at cycle %d: \"%(i),int(dr))\r\n print(\"New population of mice at cycle %d: \"%(i),int(dm))\r\n print(\"New population of fox at cycle %d: \"%(i),int(df))\r\n rab = dr\r\n mice = dm\r\n fox = df\r\n list_r.append(rab)\r\n list_m.append(mice)\r\n list_f.append(fox)\r\n \r\nplt.plot(list_r, 'r-', label='Rabbits')\r\nplt.plot(list_m, 'g-', label='Mice')\r\nplt.plot(list_f, 'b-', label='Foxes')\r\nplt.grid()\r\nplt.legend(loc='best')\r\nplt.xlabel('Cycles')\r\nplt.ylabel('Population')\r\nplt.title('Evolution of population of X and y')\r\nplt.show()\r\n#rab_new_pop = int(rab*math.exp(rg*t))\r\n#fox_new_pop = int(fox*math.exp(fg*t))\r\n\r\n"} {"blob_id": "f82b8d6815a2312e6d614aec2c3bcfb43dc52e6a", "repo_name": "swapnil96/Online-Judge-Contest", "path": "/CC_June_lunch/SQNUMBF.py", "length_bytes": 831, "score": 3.625, "int_score": 4, "content": "'''Link - https://www.codechef.com/problems/SQNUMBF'''\n\nfrom fractions import gcd\nimport math\n\ndef root(num, base):\n var = int(math.pow(num, 1.0/base))\n if (var+1)**base == num:\n return var + 1\n\n else:\n return var\n\ndef solve(n, a):\n\n for i in xrange(n):\n for j in xrange(i + 1, n):\n g = gcd(a[i], a[j])\n if g > 1:\n return g\n\n for i in xrange(n):\n x = a[i]\n for j in xrange(1, root(x, 3)):\n if ( j > 1 and x % (j*j) == 0):\n return j\n\n if (x % j == 0):\n p = x / j\n t = root(p, 2)\n if (t > 1 and t*t == p):\n return t\n\ntt = int(raw_input())\nfor i in xrange(tt):\n n = int(raw_input())\n a = map(int, raw_input().split())\n print solve(n, a)\n"} {"blob_id": "c5bfc2e2c1b927482ce8fdd7080958a85158ec4e", "repo_name": "araghu9/FinTechWebApp2020", "path": "/data/GraphGenerator.py", "length_bytes": 6870, "score": 4.0, "int_score": 4, "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 28 23:10:01 2020\n\n@author: matthewjalnos\n\"\"\"\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# function to return the stock price at the end of a time period\n# given all determining parameters\n# param dividend - initial dividend value\n# param payInterval - time between payments, in years\n# param cRatio - common ratio as a percent\n# param irRate - interest rate as a percent\n# param stockLength - the duration of the hold on the stock\ndef stockprice(dividend, payInterval, cRatio, irRate, stockLength):\n #variable to hold the price of the stock\n totalPrice = 0\n intervalInt = 1 # scaling # payments\n\n rPayInterval = 1 / float(payInterval)\n numPayments = int(float(stockLength) * rPayInterval) # the # of payments\n interest = (1 + float(irRate) / 100) # convert interest from percent to modifier\n commonR = (1 + float(cRatio) / 100) # convert common ratio from percent to modifier\n\n # loop through each payment and add the total price\n for i in range(1, numPayments+1, intervalInt):\n totalPrice = totalPrice + float(dividend) * (commonR ** (i-1) / (interest ** float(i*float(payInterval))))\n\n # return rounded price\n return (dividend)\n return round(totalPrice, 2)\n\n\nprint(stockprice(5, 0.5, 2, 4, 10))\n\n# function to print the graph of price vs interest ratio\n# when holding the other params constant\n# param lowerIR - the lowest interest rate to be calculated (percent)\n# param upperIR - the highest interest rate to be calculated (percent)\n# param dividend - initial dividend value\n# param payInterval - time between payments, in years\n# param commonRatio - common ratio as a percent\n# param irRate - interest rate as a percent\n# param stockLength - the duration of the hold on the stock\ndef graphIR(lowerIR, upperIR, dividend, payInterval, commonRatio, stockLength):\n # loop through all potential interest rates (0-100) and plot the values\n \n for i in range(lowerIR, upperIR+1, 1):\n graphValue = stockprice(dividend, payInterval, commonRatio, i, stockLength)\n #graphValue = stockprice(10, , 105, i, 10)\n plt.plot(i, graphValue,'-o') # x-axis, then y-axisplt.xlabel('Interest Rate (percent)') # labels x-axis\n plt.ylabel('Price (dollars)') # labels y-axis\n plt.title(' Relationship Between Interest Rate and Price') # title\n return (plt.show())\n\ngraphIR(10,50,5, 0.5, 2, 10)\n\n# function to print the graph of Price vs Dividend\n# when holding the other params constant\n# param lowerDiv - lowest dividend to be calculated\n# param upperDiv - highest dividend to be calculated\n# param payInterval - time between payments, in years\n# param commonRatio - common ratio as a percent\n# param irRate - interest rate as a percent\n# param stockLength - the duration of the hold on the stock\ndef graphDividend(lowerDiv,upperDiv, payInterval, commonRatio, irRate, stockLength):\n # loop through each dividend (0-upperDiv) and plot the values\n for i in range(lowerDiv, upperDiv+1, 1):\n graphValue = stockprice(i, payInterval, commonRatio, irRate, stockLength)\n plt.plot(i, graphValue, '-o') # x-axis, then y-axis\n plt.xlabel('Initial Dividend Value (dollars)') # labels x-axis\n plt.ylabel('Price (dollars)') # labels y-axis\n plt.title(' Relationship Between Initial Dividend Value and Price') # title\n plt.xticks(range(lowerDiv, upperDiv + 1))\n return (plt.show())\n\n#graphDividend(70,100,0.5,2,4,10)\n\n# function to print the graph of Price vs Pay Interval\n# when holding the other params constant\n# param lowerInt - shortest pay duration to be calculated\n# param upperInt - longest pay duration to be calculated\n# param dividend - initial dividend value\n# param commonRatio - common ratio as a percent\n# param irRate - interest rate as a percent\n# param stockLength - the duration of the hold on the stock\ndef graphInterval(lowerInterval,upperInterval, dividend, commonRatio, irRate, stockLength):\n # converts the pay interval to smaller chunks to loop through\n # DO NOT INCREASE THIS VALUE ABOVE 24 OR THE CODE BREAKS\n conversionMult = 100\n upperInter = int(upperInterval * conversionMult)+1\n lowerInter = int(lowerInterval * conversionMult)\n # loop through all potential intervals (1-upperInt) and plot the values\n for i in range(lowerInter, upperInter+1, 1):\n convertedInt = float(i/conversionMult)\n graphValue = stockprice(dividend, convertedInt, commonRatio, irRate, stockLength)\n plt.plot(convertedInt, graphValue, '-o') # x-axis, then y-axis\n plt.xlabel('Time Between Dividends (years)') # labels x-axis\n plt.ylabel('Price (dollars)') # labels y-axis\n plt.title(' Relationship Between Pay Period and Price') # title\n #plt.xticks(range(lowerInter, upperInter + 1))\n return (plt.show())\n\n#graphInterval(0.10,0.55,5,2,4,10)\n\n# function to print the graph of Price vs Common Ratio\n# when holding the other params constant\n# param lowerCR - the lowest pay ratio to be calculated\n# param upperCR - the highest pay ratio to be calculated\n# param dividend - initial dividend value\n# param payInterval - time between payments, in years\n# param irRate - interest rate as a percent\n# param stockLength - the duration of the hold on the stock\ndef graphCommonRatio(lowerCR,upperCR, dividend, payInterval, irRate, stockLength):\n\n # loop through each dividend (0-upperCR) and plot the valued\n for i in range(lowerCR, upperCR+1, 1):\n graphValue = stockprice(dividend, payInterval, i, irRate, stockLength)\n plt.plot(i, graphValue, '-o') # x-axis, then y-axis\n plt.xlabel('Common Ratio') # labels x-axis\n plt.ylabel('Price (dollars)') # labels y-axis\n plt.title(' Relationship Between Common Ratio and Price') # title\n #plt.xticks(range(lowerCR, upperCR + 1))\n return (plt.show())\n\n#graphCommonRatio(-40,4,500,0.5,4,10)\n\n# function to print the graph of Price vs Stock Length\n# when holding the other params constant\n# param lowerSL - the shortest stock duration to be calculated\n# param upperSL - the longest stock duration to be calculated\n# param dividend - initial dividend value\n# param payInterval - time between payments, in years\n# param cRatio - common ratio as a percent\n# param irRate - interest rate as a percent\ndef graphStockLength(lowerSL,upperSL, dividend, payInterval, cRatio, irRate):\n # loop through each dividend (0-upperSL) and plot the valued\n for i in range(lowerSL, upperSL+1, 1):\n graphValue = stockprice(dividend, payInterval, cRatio, irRate, i)\n plt.plot(i, graphValue, '-o') # x-axis, then y-axis\n plt.xlabel('Length of Stock (years)') # labels x-axis\n plt.ylabel('Price (dollars)') # labels y-axis\n plt.title(' Relationship Between Length of Stock and Price') # title\n return (plt.show())\n\n#graphStockLength(90,100,5,0.5,2,4)\n"} {"blob_id": "ba54e95025c4bb36057fce2ad7748f6b42464fb5", "repo_name": "yasserglez/programming-problems", "path": "/hackerrank/algorithms/the-quickest-way-up.py", "length_bytes": 1615, "score": 3.53125, "int_score": 4, "content": "# https://www.hackerrank.com/challenges/the-quickest-way-up\n\nimport sys\nimport collections\n\n\ndef _build_graph(snakes, ladders):\n snakes_dict = {(s0 - 1): (s1 - 1) for s0, s1 in snakes}\n ladders_dict = {(l0 - 1): (l1 - 1) for l0, l1 in ladders}\n graph = [[] for _ in range(100)]\n for i in range(100):\n for dice_roll in range(1, 7):\n j = i + dice_roll\n if j in snakes_dict:\n j = snakes_dict[j]\n elif j in ladders_dict:\n j = ladders_dict[j]\n if j <= 99:\n graph[i].append(j)\n return graph\n\n\n# Breadth-first search\ndef _min_number_of_moves(graph):\n queue = collections.deque([0])\n distance = [0] + [-1] * 99\n while queue:\n i = queue.popleft()\n for j in graph[i]:\n if distance[j] == -1:\n if j == 99:\n return distance[i] + 1\n distance[j] = distance[i] + 1\n queue.append(j)\n return -1\n\n\ndef quickest_way_up(snakes, ladders):\n graph = _build_graph(snakes, ladders)\n return _min_number_of_moves(graph)\n\n\nif __name__ == '__main__':\n f = sys.stdin\n T = int(f.readline().rstrip())\n for t in range(T):\n snakes, ladders = [], []\n num_snakes = int(f.readline().rstrip())\n for i in range(num_snakes):\n snakes.append(tuple(map(int, f.readline().rstrip().split())))\n num_ladders = int(f.readline().rstrip())\n for i in range(num_ladders):\n ladders.append(tuple(map(int, f.readline().rstrip().split())))\n print(quickest_way_up(snakes, ladders))\n"} {"blob_id": "704128bb344ba0a9af3ee8f85505cfde2ff86b31", "repo_name": "CescWang1991/LeetCode-Python", "path": "/point_offer/SearchMatrix.py", "length_bytes": 1118, "score": 3.546875, "int_score": 4, "content": "# \u5728\u4e00\u4e2a\u4e8c\u7ef4\u6570\u7ec4\u4e2d\uff08\u6bcf\u4e2a\u4e00\u7ef4\u6570\u7ec4\u7684\u957f\u5ea6\u76f8\u540c\uff09\uff0c\u6bcf\u4e00\u884c\u90fd\u6309\u7167\u4ece\u5de6\u5230\u53f3\u9012\u589e\u7684\u987a\u5e8f\u6392\u5e8f\uff0c\u6bcf\u4e00\u5217\u90fd\u6309\u7167\u4ece\u4e0a\u5230\u4e0b\u9012\u589e\u7684\u987a\u5e8f\u6392\u5e8f\u3002\n# \u8bf7\u5b8c\u6210\u4e00\u4e2a\u51fd\u6570\uff0c\u8f93\u5165\u8fd9\u6837\u7684\u4e00\u4e2a\u4e8c\u7ef4\u6570\u7ec4\u548c\u4e00\u4e2a\u6574\u6570\uff0c\u5224\u65ad\u6570\u7ec4\u4e2d\u662f\u5426\u542b\u6709\u8be5\u6574\u6570\u3002\n\n# \u76f8\u4f3c\u95ee\u9898\uff1a74. Search a 2D Matrix\n\n# \u4e0d\u540c\u5904\uff1aleetcode 74\u4e2d\u6bcf\u884c\u7684\u7b2c\u4e00\u4e2a\u6574\u6570\u5927\u4e8e\u524d\u4e00\u884c\u7684\u6700\u540e\u4e00\u4e2a\u6574\u6570\u3002\n\n# \u601d\u8def\uff1a\u9996\u5148\u9009\u53d6\u6570\u7ec4\u4e2d\u53f3\u4e0a\u89d2\u7684\u6570\u5b57\u3002\u5982\u679c\u8be5\u6570\u5b57\u7b49\u4e8e\u8981\u67e5\u627e\u7684\u6570\u5b57\uff0c\u67e5\u627e\u8fc7\u7a0b\u7ed3\u675f\uff1b\u5982\u679c\u8be5\u6570\u5b57\u5927\u4e8e\u8981\u67e5\u627e\u7684\u6570\u5b57\uff0c\u5254\u9664\u8fd9\u4e2a\u6570\u5b57\u6240\n# \u5728\u7684\u5217\uff1b\u5982\u679c\u8be5\u6570\u5b57\u5c0f\u4e8e\u8981\u67e5\u627e\u7684\u6570\u5b57\uff0c\u5254\u9664\u8fd9\u4e2a\u6570\u5b57\u6240\u5728\u7684\u884c\u3002\n\n\nclass Solution:\n def find(self, target, array):\n row = 0\n col = len(array[0]) - 1\n while 0 <= row < len(array) and 0 <= col < len(array[0]):\n if array[row][col] == target:\n return True\n elif array[row][col] > target:\n col -= 1\n continue\n else:\n row += 1\n continue\n return False\n"} {"blob_id": "dd2a9b127d5550d5bf6a3025187c3c0fae4cf469", "repo_name": "cheonyeji/algorithm_study", "path": "/\ud504\ub85c\uadf8\ub798\uba38\uc2a4/\uace0\ub4dd\uc810kit2\ud68c/dfsbfs/\ud0c0\uac9f\ub118\ubc84.py", "length_bytes": 512, "score": 3.515625, "int_score": 4, "content": "def solution(numbers, target):\n answer = 0\n\n total = 0\n\n def dfs(node_num, i):\n nonlocal answer, total\n\n total += node_num\n\n if i == len(numbers) - 1:\n if total == target:\n answer += 1\n total -= node_num\n\n return\n\n dfs(numbers[i + 1], i + 1)\n dfs(-numbers[i + 1], i + 1)\n\n dfs(numbers[0], 0)\n dfs(-numbers[0], 0)\n\n return answer\n\n\nprint(solution([1, 1, 1, 1, 1], 3)) # 5\nprint(solution([4, 1, 2, 1], 4)) # \t2\n"} {"blob_id": "49c9e6fe57d7e8501b32ab7afc5bffa14f0c257e", "repo_name": "vicch/leetcode", "path": "/0200-0299/0234-palindrome-linked-list/0234-palindrome-linked-list.py", "length_bytes": 2114, "score": 4.25, "int_score": 4, "content": "\"\"\"\nFor O(1) space and O(n) time, the only way is to reverse half of the list, and compare its the 2 halves are equal.\n\nReversing a list is essentially building a new list backwards, by taking nodes off the head of the old list, and attach\nto the head of the new list.\n\nTo find the middle location of the original list, use fast and slow pointers.\n\"\"\"\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution(object):\n def isPalindrome(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: bool\n \"\"\"\n\n def reverse(head):\n \"\"\"\n Reverse given list and return new head.\n \"\"\"\n\n # Init head of the new list.\n newHead = None\n\n while head:\n # Take head of old list and attach to head of new list.\n node = head\n head = head.next\n node.next = newHead\n newHead = node\n\n return newHead\n\n def isEqual(head, tail):\n # If the original list has even number of nodes, the last node of the head list will point to the last node\n # of the tail list, which means the head list has one more node that should be ignored. The fast and slow\n # pointers already guarantee that the head list has at most one more node in this case, so just checking if\n # it reaches the end of the tail list is enough.\n while tail:\n if head.val != tail.val:\n return False\n head = head.next\n tail = tail.next\n return True\n\n if not head:\n return False\n if not head.next:\n return True\n \n # The slow pointer points to the start of the later half when fast pointer reaches the end.\n fast = slow = head\n while fast and fast.next:\n fast = fast.next.next\n slow = slow.next\n\n tail = reverse(slow)\n\n return isEqual(head, tail)\n"} {"blob_id": "ffeb362d20324fb6af7b6907a690ddac30bb09d8", "repo_name": "Narcissus7/LeetCode", "path": "/2020.01.08-523.py", "length_bytes": 2963, "score": 3.625, "int_score": 4, "content": "\"\"\"\nhttps://leetcode-cn.com/problems/continuous-subarray-sum/\n523. \u8fde\u7eed\u7684\u5b50\u6570\u7ec4\u548c\n\u7ed9\u5b9a\u4e00\u4e2a\u5305\u542b\u975e\u8d1f\u6570\u7684\u6570\u7ec4\u548c\u4e00\u4e2a\u76ee\u6807\u6574\u6570\u00a0k\uff0c\u7f16\u5199\u4e00\u4e2a\u51fd\u6570\u6765\u5224\u65ad\u8be5\u6570\u7ec4\u662f\u5426\u542b\u6709\u8fde\u7eed\u7684\u5b50\u6570\u7ec4\uff0c\n\u5176\u5927\u5c0f\u81f3\u5c11\u4e3a 2\uff0c\u603b\u548c\u4e3a k \u7684\u500d\u6570\uff0c\u5373\u603b\u548c\u4e3a n*k\uff0c\u5176\u4e2d n \u4e5f\u662f\u4e00\u4e2a\u6574\u6570\u3002\n\n\u793a\u4f8b 1:\n\u8f93\u5165: [23,2,4,6,7], k = 6 \u8f93\u51fa: True\n\u89e3\u91ca: [2,4] \u662f\u4e00\u4e2a\u5927\u5c0f\u4e3a 2 \u7684\u5b50\u6570\u7ec4\uff0c\u5e76\u4e14\u548c\u4e3a 6\u3002\n\u793a\u4f8b 2:\n\u8f93\u5165: [23,2,6,4,7], k = 6 \u8f93\u51fa: True\n\u89e3\u91ca: [23,2,6,4,7]\u662f\u5927\u5c0f\u4e3a 5 \u7684\u5b50\u6570\u7ec4\uff0c\u5e76\u4e14\u548c\u4e3a 42\u3002\n\n\u8bf4\u660e:\n\u6570\u7ec4\u7684\u957f\u5ea6\u4e0d\u4f1a\u8d85\u8fc710,000\u3002\n\u4f60\u53ef\u4ee5\u8ba4\u4e3a\u6240\u6709\u6570\u5b57\u603b\u548c\u5728 32 \u4f4d\u6709\u7b26\u53f7\u6574\u6570\u8303\u56f4\u5185\u3002\n\"\"\"\nfrom typing import List\n\n\nclass Solution:\n def checkSubarraySum(self, nums: List[int], k: int) -> bool:\n \"\"\"\u66b4\u529b\"\"\"\n for i in range(len(nums) - 1):\n for j in range(i + 2, len(nums) + 1):\n if k == 0:\n if sum(nums[i:j]) == 0:\n return True\n else:\n break\n\n if sum(nums[i:j]) // k == sum(nums[i:j]) / k:\n return True\n\n return False\n\n def checkSubarraySum2(self, nums: List[int], k: int) -> bool:\n \"\"\"\u5feb\u4e00\u70b9\u7684\u66b4\u529b\uff0c\u80fd\u8fc7\"\"\"\n for i in range(len(nums) - 1):\n tmp = nums[i]\n for j in range(i + 1, len(nums)):\n tmp += nums[j]\n if k == 0:\n if tmp == 0:\n return True\n else:\n break\n\n if tmp // k == tmp / k:\n return True\n\n return False\n\n def checkSubarraySum3(self, nums: List[int], k: int) -> bool:\n \"\"\"\n \u4f7f\u7528 HashMap \u6765\u4fdd\u5b58\u5230\u7b2c i \u4e2a\u5143\u7d20\u4e3a\u6b62\u7684\u7d2f\u79ef\u548c\uff0c\u4f46\u6211\u4eec\u5bf9\u8fd9\u4e2a\u524d\u7f00\u548c\u9664\u4ee5 k \u53d6\u4f59\u6570\n \u5047\u8bbe:\n a[i]+a[i+1]+...+a[j]=n1k+q;\n \u5982\u679c\u5b58\u5728\u4e00\u4e2an\n n>j\u4e14a[i]+a[i+1]+...+a[j]+...+a[n]=n2k+q;\n \u90a3\u4e48\n a[j+1]+...+a[n]=(n2\u2212n1)k\n\n \u5982\u679c\u540c\u4e00\u4e2a\u4f59\u6570\u51fa\u73b0\u4e86\u4e24\u6b21\uff0c\u5e76\u4e14\u4e24\u6b21\u51fa\u73b0\u7684\u4e0b\u6807\u4e4b\u5dee\u5927\u4e8e1\uff0c\u90a3\u4e48\u5c31\u8868\u793a\u5728\u8fd9\u4e24\u4e2a\u5750\u6807\u4e4b\u95f4\u7684\u5143\u7d20\u4e4b\u548c\u662fk\u7684\u500d\u6570\n \u53ea\u6709\u5f53k\u4e0d\u4e3a0\u65f6\u624d\u5bf9\u5f53\u524d\u7684\u548c\u6c42\u4f59\n \u5bf9\u4e8enums = [0, 0], k = 0\u7684\u60c5\u51b5\uff0c\u9700\u8981\u6dfb\u52a0\u4e00\u4e2a\u521d\u59cb\u6620\u5c04(0, -1)\u6765\u786e\u4fdd\u7ed3\u679c\u7684\u6b63\u786e\n \"\"\"\n if len(nums) < 2:\n return False\n bag = {0: -1}\n sums = 0 # \u6c42\u548c\n for i in range(len(nums)):\n sums += nums[i]\n if k != 0:\n sums = sums % k # \u53d6\u4f59: \u4f4d\u7f6ei\n if sums not in bag:\n bag[sums] = i\n else:\n if i - bag.get(sums) > 1:\n return True\n return False\n\n\ns = Solution()\nprint(s.checkSubarraySum([0, 0], 0))\nprint(s.checkSubarraySum2([0, 0], 0))\nprint(s.checkSubarraySum3([2, 5, 33, 6, 7, 25, 15], 13))\n"} {"blob_id": "3050881a7ed006fdb15bbc98c3174580202ebaef", "repo_name": "LiYifei1218/AP-CSP-I", "path": "/PSet09RadiationExposure/radiationexposure.py", "length_bytes": 709, "score": 3.5625, "int_score": 4, "content": "\"\"\"\n|-------------------------------------------------------------------------------\n| radiationexposure.py\n|-------------------------------------------------------------------------------\n|\n| Author: Alwin Tareen\n| Created: Nov 10, 2019\n|\n| This program determines the amount of radiation exposure.\n|\n\"\"\"\n\nimport math\n\n# this function describes the radioactive decay curve of Cobalt-60\ndef f(x):\n activity = 10*math.e**(math.log(0.5)/5.27 * x)\n return activity\n\ndef decaycurvearea(start, stop, step):\n # YOUR CODE HERE\n radiation = 0\n i = start\n while i < stop:\n \n radiation += (f(i) * step)\n i += step\n return radiation\n\nresult = decaycurvearea(5, 11, 1)\nprint(result)\n\n"} {"blob_id": "3d01c2220bbae4b90d4129a87a02dff3166f721a", "repo_name": "jfriend08/LeetCode", "path": "/LargestNumber.py", "length_bytes": 852, "score": 4.3125, "int_score": 4, "content": "'''\nGiven a list of non negative integers, arrange them such that they form the largest number.\n\nFor example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.\n\nNote: The result may be very large, so you need to return a string instead of an integer.\n\nCredits:\nSpecial thanks to @ts for adding this problem and creating all test cases.\n'''\n\nclass Solution(object):\n def largestNumber(self, nums):\n struct = []\n result = ''\n for num in nums:\n size = len(str(num))\n digit = int(num/10**(size-1))\n struct.append((digit,num))\n\n struct = sorted(struct, key = lambda x: (x[0], x[1]), reverse = True)\n for (digit, num) in struct:\n result += str(num)\n\n return result\n\n\n\nif __name__ == \"__main__\":\n test = Solution()\n print test.largestNumber([3, 30, 34, 5, 9])"} {"blob_id": "53473d6378ecbb56a53a79dcd44dbe2b5b682f48", "repo_name": "PedroVictorCoding/Biology-Meets-Informatics-Course-Reusable-Code", "path": "/bioinformatics_course_reusablecode.py", "length_bytes": 39038, "score": 4.03125, "int_score": 4, "content": "'''\n# Frequency mapper for BioInformatics Course\ndef FrequencyMap(Text, k):\n freq = {}\n n = len(Text)\n for i in range(n-k+1):\n Pattern = Text[i:i+k]\n freq[Pattern]= 0\n for i in range(n-k+1):\n if Text[i:i+k] == Pattern:\n freq[Pattern] += 1\n return freq\n\n\n\n### ### ### ###\n\nText = \"\"\nk = \"\"\n\ndef FrequentWords(Text, k):\n words = []\n freq = FrequencyMap(Text, k)\n m = max(freq.values())\n for key in freq:\n if freq[key] == m: \n \tpattern = key\n \twords.append(pattern)\n return words\n\n# Copy your FrequencyMap() function here.\ndef FrequencyMap(Text, k):\n freq = {}\n n = len(Text)\n for i in range(n-k+1):\n Pattern = Text[i:i+k]\n freq[Pattern]= 0\n for i in range(n-k+1):\n if Text[i:i+k] == Pattern:\n freq[Pattern] = freq[Pattern] + 1\n return freq\n\n\n## OR ##\n\n## FInd how many time a pattern is in a text\ndef PatternCount(Text, Pattern):\n count = 0\n for i in range(len(Text)-len(Pattern)+1):\n if Text[i:i+len(Pattern)] == Pattern:\n count = count+1\n return count \n\ndef FrequencyMap(Text, k):\n freq = {}\n n = len(Text)\n for i in range(n-k+1):\n Pattern = Text[i:i+k]\n freq[Pattern]= PatternCount(Text,Pattern)\n \n return freq\n\ndef FrequentWords(Text, k):\n words = []\n freq = FrequencyMap(Text, k)\n m = max(freq.values())\n for key in freq:\n if freq[key] == m:\n words.append(key)\n words.sort()\n return words\n\nFrequentWords(\"ACGTTGCATGTCGCATGATGCATGAGAGCT\",4)\n\n### ### ### ### ###\n\n\n### ReverseComplement Function ###\n\n# Highest Level Function\ndef ReverseComplement(Pattern):\n print(\"Initial Pattern: \" + Pattern)\n Pattern = Reverse(Pattern) # reverse all letters in a string\n print(\"Reversed Pattern: \" + Pattern)\n Pattern = Complement(Pattern) # complement each letter in a string\n print(\"Complement Pattern: \" + Pattern)\n return Pattern\n\ndef Reverse(Pattern):\n PatternReversed = \"\"\n for i in range(len(Pattern)):\n PatternReversed = Pattern[i] + PatternReversed\n \n Pattern = PatternReversed\n return PatternReversed\n\ndef Complement(Pattern):\n list_pattern = list(Pattern)\n for i in range(len(list_pattern)):\n if list_pattern[i] == \"A\":\n list_pattern[i] = \"T\"\n elif list_pattern[i] == \"C\":\n list_pattern[i] = \"G\"\n elif list_pattern[i] == \"G\":\n list_pattern[i] = \"C\"\n elif list_pattern[i] == \"T\":\n list_pattern[i] = \"A\"\n \n Pattern = \"\".join(list_pattern)\n return Pattern\n\nprint(ReverseComplement(\"ACTGAGTC\"))\n\n\n### Pattern Matching Function ###\n\ndef PatternMatching(Pattern, Genome):\n\n positions = []\n def find_all(Pattern, Genome):\n start = 0\n while True:\n start = Genome.find(Pattern, start)\n if start == -1: return\n yield start\n start += 1 # use start += len(Pattern) to remove overlapping matches\n positions = list(find_all(Pattern, Genome))\n \n return positions\n\nprint(PatternMatching('ATAT', 'GATATATGCATATACTT')) \n\n#### Find frequency of a certain nucleotide in a window\n#### of half the genome's size\n\ndef PatternCount(Pattern, Text):\n count = 0\n for i in range(len(Text)-len(Pattern)+1):\n if Text[i:i+len(Pattern)] == Pattern:\n count = count+1\n return count \n\ndef SymbolArray(Genome, symbol):\n array = {}\n n = len(Genome)\n ExtendedGenome = Genome + Genome[0:n//2]\n for i in range(n):\n array[i] = PatternCount(symbol, ExtendedGenome[i:i+(n//2)])\n return array\n\n# Efficient version of the code on top\n\ndef PatternCount(Pattern, Text):\n count = 0\n for i in range(len(Text)-len(Pattern)+1):\n if Text[i:i+len(Pattern)] == Pattern:\n count = count+1\n return count \n\ndef FasterSymbolArray(Genome, symbol):\n array = {}\n n = len(Genome)\n ExtendedGenome = Genome + Genome[0:n//2]\n\n # look at the first half of Genome to compute first array value\n array[0] = PatternCount(symbol, Genome[0:n//2])\n\n for i in range(1, n):\n # start by setting the current array value equal to the previous array value\n array[i] = array[i-1]\n\n # the current array value can differ from the previous array value by at most 1\n if ExtendedGenome[i-1] == symbol:\n array[i] = array[i]-1\n if ExtendedGenome[i+(n//2)-1] == symbol:\n array[i] = array[i]+1\n return array\n\n#### Code to show a plot for a nucleotide's occurence in the genome with a window of length n//2\n\ndef PatternCount(Pattern, Text):\n count = 0\n for i in range(len(Text)-len(Pattern)+1):\n if Text[i:i+len(Pattern)] == Pattern:\n count = count+1\n return count \n\ndef FasterSymbolArray(Genome, symbol):\n array = {}\n n = len(Genome)\n ExtendedGenome = Genome + Genome[0:n//2]\n\n # look at the first half of Genome to compute first array value\n array[0] = PatternCount(symbol, Genome[0:n//2])\n\n for i in range(1, n):\n # start by setting the current array value equal to the previous array value\n array[i] = array[i-1]\n\n # the current array value can differ from the previous array value by at most 1\n if ExtendedGenome[i-1] == symbol:\n array[i] = array[i]-1\n if ExtendedGenome[i+(n//2)-1] == symbol:\n array[i] = array[i]+1\n return array\n\n## This is to read an externally saved genome\nwith open('e_coli.txt') as file:\n e_coli = file.read();\n\narray = FasterSymbolArray(e_coli, \"C\")\n\nimport matplotlib.pyplot as plt\nplt.plot(*zip(*sorted(array.items())))\nplt.show()\n\n### SkewArray Function \n\ndef SkewArray(Genome):\n skew = [0]\n score = {\"A\":0, \"T\":0, \"C\":-1, \"G\":1}\n for i in range(1,len(Genome)+1):\n skew.append(score[Genome[i-1]] + skew[i-1])\n return skew\n\n\n## Finding the ORI Region with the minimum values outputed\n\ndef SkewArray(Genome):\n array = [0]\n Skew = 0\n for i in Genome:\n if i == 'A' or i == 'T':\n Skew += 0\n array.append(Skew)\n if i == 'C':\n Skew -= 1\n array.append(Skew)\n if i == 'G':\n Skew += 1\n array.append(Skew)\n return array\n\ndef MinimumSkew(Genome):\n array = SkewArray(Genome)\n positions = []\n count = 0\n minarray = min(array)\n for i in array:\n if i == minarray:\n positions.append(count)\n count +=1\n return positions\n\n### Find distance between two strings\n\ndef HammingDistance (p, q):\n count = 0\n for i, j in zip(p, q):\n if i != j:\n count += 1\n return count\n\n\n### AproximatePatternMatching\n\ndef ApproximatePatternMatching(Text, Pattern, d):\n positions = [] # initializing list of positions\n for i in range(len(Text)-len(Pattern)+1):\n if HammingDistance(Text[i:i+len(Pattern)], Pattern) <= d:\n positions.append(i)\n return positions\n#range is modified like this because if is it just length of the bigger text, pattern will keep sliding along with empty letters, adding more to the list of positions\n\ndef HammingDistance(p, q):\n count = 0\n for i in range(len(p)):\n if p[i] != q[i]:\n count += 1\n return count\n\n### Approximate Pattern Count\n\ndef ApproximatePatternCount(Pattern, Text, d):\n count = 0 # initialize count variable\n for i in range(len(Text)-len(Pattern)+1):\n if HammingDistance(Pattern, Text[i:i+len(Pattern)]) <= d:\n count += 1\n return count\n#same thing as the pattern matching before, but it is replaced by count\n\ndef HammingDistance(p, q):\n count = 0\n for i in range(len(p)):\n if p[i] != q[i]:\n count += 1\n return count\n\n### DO NOT MODIFY THE CODE BELOW THIS LINE ###\nimport sys\nlines = sys.stdin.read().splitlines()\nprint(ApproximatePatternCount(lines[0],lines[1],int(lines[2])))\n\n#here is my pattern matching for reference. range is set like that because it will continue matching with the empty letters at the end of the long text\n\ndef ApproximatePatternMatching(Text, Pattern, d):\n positions = [] # initializing list of positions\n for i in range(len(Text)-len(Pattern)+1):\n if HammingDistance(Text[i:i+len(Pattern)], Pattern) <= d:\n positions.append(i)\n return positions\n\n### Frequent Words with Mismatches Problem\n Possible Solution:\n Use the sliding window technique and slipt each sliding window into single characters,\n then she how often the certain characters are in each window.\n\n\n##### Motifs.py #####\n### Count\ndef Count(Motifs):\n count = {}\n ## k - Length of kmer/window\n k = len(Motifs[0])\n for symbol in \"ACGT\":\n count[symbol] = []\n for j in range(k):\n count[symbol].append(0)\n \n t = len(Motifs)\n for i in range(t):\n for j in range(k):\n symbol = Motifs[i][j]\n count[symbol][j] +=1\n\n return count\n\n### Profile (requires Count function)\n\ndef Count(Motifs):\n count = {}\n ## k - Length of kmer/window\n k = len(Motifs[0])\n for symbol in \"ACGT\":\n count[symbol] = []\n for j in range(k):\n count[symbol].append(0)\n \n t = len(Motifs)\n for i in range(t):\n for j in range(k):\n symbol = Motifs[i][j]\n count[symbol][j] +=1\n\n return count\n\n\ndef Profile(Motifs):\n t = len(Motifs)\n k = len(Motifs[0])\n profile = Count(Motifs)\n \n for key,v in profile.items():\n v[:] = [x / t for x in v]\n return profile\n\n### Consensus\ndef Count(Motifs):\n count = {}\n ## k - Length of kmer/window\n k = len(Motifs[0])\n for symbol in \"ACGT\":\n count[symbol] = []\n for j in range(k):\n count[symbol].append(0)\n \n t = len(Motifs)\n for i in range(t):\n for j in range(k):\n symbol = Motifs[i][j]\n count[symbol][j] +=1\n\n return count\n\ndef Consensus(Motifs):\n k = len(Motifs[0])\n count = Count(Motifs)\n\n consensus = ''\n\n for j in range(k):\n m = 0\n frequentSymbol = ''\n for symbol in 'ACGT':\n if count[symbol][j] > m:\n m = count[symbol][j]\n frequentSymbol = symbol\n consensus += frequentSymbol\n return consensus\n\n### Score\ndef Count(Motifs):\n count = {}\n ## k - Length of kmer/window\n k = len(Motifs[0])\n for symbol in \"ACGT\":\n count[symbol] = []\n for j in range(k):\n count[symbol].append(0)\n \n t = len(Motifs)\n for i in range(t):\n for j in range(k):\n symbol = Motifs[i][j]\n count[symbol][j] +=1\n\n return count\n\ndef Consensus(Motifs):\n k = len(Motifs[0])\n count = Count(Motifs)\n\n consensus = ''\n\n for j in range(k):\n m = 0\n frequentSymbol = ''\n for symbol in 'ACGT':\n if count[symbol][j] > m:\n m = count[symbol][j]\n frequentSymbol = symbol\n consensus += frequentSymbol\n return consensus\n\ndef Score(Motifs):\n consensus = Consensus(Motifs)\n count = 0\n for motif in Motifs:\n for index in range(len(motif)):\n if motif[index] != consensus[index]:\n count += 1\n return count\n\n### Probability\n\ndef Pr(Text, Profile):\n product = 1\n for index, nucleotide in enumerate(Text):\n product *= Profile[nucleotide][index]\n return product\n\n### \ndef ProfileMostProbableKmer(text, k, profile):\n n = len(text)\n pr = {}\n most_likely_kmer = []\n for i in range(n-k+1):\n k_mer = text[i:i+k]\n probability = Pr(k_mer, profile)\n pr[k_mer] = probability\n m = max(pr.values())\n for key, value in pr.items():\n if pr[key] == m:\n most_likely_kmer.append(key)\n return most_likely_kmer[0]\n\ndef Pr(Text, Profile):\n product = 1\n for index, nucleotide in enumerate(Text):\n product *= Profile[nucleotide][index]\n return product\n\n### Greedy Motif Search\ndef Count(Motifs):\n k = len(Motifs[0])\n count = {}\n for symbol in \"ACGT\":\n count[symbol] = []\n for j in range(k):\n count[symbol].append(0)\n t = len(Motifs)\n for i in range(t):\n for j in range(k):\n symbol = Motifs[i][j]\n count[symbol][j] += 1\n return count\n\n\ndef Consensus(Motifs):\n count = Count(Motifs)\n k = len(Motifs[0])\n consensus = \"\"\n for j in range(k):\n m = 0\n frequentSymbol = \"\"\n for symbol in \"ACGT\":\n if count[symbol][j] > m:\n m = count[symbol][j]\n frequentSymbol = symbol\n consensus += frequentSymbol\n return consensus\n\n\ndef Profile(Motifs):\n t = len(Motifs)\n k = len(Motifs[0])\n profile = Count(Motifs)\n for i in 'ACTG':\n for j in range(k):\n profile[i][j] = profile[i][j]/t \n return profile\n\ndef Score(Motifs):\n k = len(Motifs[0])\n score = 0\n count = Count(Motifs)\n max_symbol = Consensus(Motifs)\n sum1 = 0\n for j in range(k):\n m = 0\n for symbol in \"ATCG\":\n if count[symbol][j] > m:\n sum1 += count[symbol][j]\n for j in range(k):\n m = 0\n for symbol in \"AGTC\":\n if count[symbol][j] > m:\n m = count[symbol][j]\n score += m \n return sum1-score\n\n\n\n\ndef Pr(Text, Profile):\n k = len(Profile[\"A\"])\n p=1\n for i in range(len(Text)):\n p=p*Profile[Text[i]][i]\n return p\n\ndef ProfileMostProbablePattern(text,k,profile):\n p=-1\n result=text[0:k]\n for i in range(len(text)-k+1):\n seq=text[i:i+k]\n pr=Pr(seq,profile)\n if pr>p:\n p=pr\n result=seq\n return result\n\ndef GreedyMotifSearch(Dna,k,t):\n BestMotifs = []\n for i in range(0, t):\n BestMotifs.append(Dna[i][0:k])\n n = len(Dna[0])\n for m in range(n-k+1):\n Motifs = []\n Motifs.append(Dna[0][m:m+k])\n for j in range(1, t):\n P = Profile(Motifs[0:j])\n Motifs.append(ProfileMostProbablePattern(Dna[j], k, P))\n if Score(Motifs) < Score(BestMotifs):\n BestMotifs = Motifs\n return BestMotifs\n\n### Big DNA set\n\ndef Count(Motifs):\n\n count = {}\n\n k = len(Motifs[0])\n\n for symbol in \"ACGT\":\n\n count[symbol] = []\n\n for j in range(k):\n\n count[symbol].append(0)\n\n t = len(Motifs)\n\n for i in range(t):\n\n for j in range(k):\n\n symbol = Motifs[i][j]\n\n count[symbol][j] += 1\n\n return count\n\n \n\ndef Consensus(Motifs):\n\n \n\n k = len(Motifs[0])\n\n count = Count(Motifs)\n\n consensus = \"\"\n\n for j in range(k):\n\n m = 0\n\n frequentSymbol = \"\"\n\n for symbol in \"ACGT\":\n\n if count[symbol][j] > m:\n\n m = count[symbol][j]\n\n frequentSymbol = symbol\n\n consensus += frequentSymbol\n\n return consensus\n\n \n\ndef Profile(Motifs):\n\n t = len(Motifs)\n\n k = len(Motifs[0])\n\n profile = Count(Motifs)\n\n for i in 'ACTG':\n\n for j in range(k):\n\n profile[i][j] = profile[i][j]/t \n\n return profile\n\n \n\ndef Score(Motifs):\n\n # Insert code here\n\n score = 0\n\n k = len(Motifs[0])\n\n count = Count(Motifs)\n\n max_symbol = Consensus(Motifs)\n\n sum1 = 0\n\n for j in range(k):\n\n m = 0\n\n for symbol in \"ATCG\":\n\n if count[symbol][j] > m:\n\n sum1 += count[symbol][j]\n\n for j in range(k):\n\n m = 0\n\n for symbol in \"AGTC\":\n\n if count[symbol][j] > m:\n\n m = count[symbol][j]\n\n score += m \n\n return sum1-score\n\n \n\ndef Pr(Text, Profile):\n\n p=1\n\n k = len(Profile[\"A\"])\n\n for i in range(len(Text)):\n\n p=p*Profile[Text[i]][i]\n\n return p\n\n \n\n#Finally solved it\n\ndef ProfileMostProbablePattern(text,k,profile):\n\n p=-1\n\n result=text[0:k]\n\n for i in range(len(text)-k+1):\n\n seq=text[i:i+k]\n\n pr=Pr(seq,profile)\n\n if pr>p:\n\n p=pr\n\n result=seq\n\n return result\n\n \n\ndef GreedyMotifSearch(Dna,k,t):\n\n BestMotifs = []\n\n for i in range(0, t):\n\n BestMotifs.append(Dna[i][0:k])\n\n n = len(Dna[0])\n\n for m in range(n-k+1):\n\n Motifs = []\n\n Motifs.append(Dna[0][m:m+k])\n\n for j in range(1, t):\n\n P = Profile(Motifs[0:j])\n\n Motifs.append(ProfileMostProbablePattern(Dna[j], k, P))\n\n if Score(Motifs) < Score(BestMotifs):\n\n BestMotifs = Motifs\n\n return BestMotifs\n\n\n### Count own often a letter appears in their \"vertical position\" + 1\ndef CountWithPseudocounts(Motifs):\n count = {}\n aa = []\n cc = []\n gg = []\n tt = []\n z = 0 \n while z <= (len(Motifs[0])-1):\n somaa = 0\n for i in Motifs:\n if i[z] == 'A':\n somaa += 1\n somaa = somaa + 1\n aa.append(somaa)\n \n somac = 0\n for i in Motifs:\n if i[z] == 'C':\n somac += 1\n somac = somac + 1\n cc.append(somac)\n\n somag = 0\n for i in Motifs:\n if i[z] == 'G':\n somag += 1\n somag = somag + 1\n gg.append(somag)\n\n somat = 0\n for i in Motifs:\n if i[z] == 'T':\n somat += 1\n somat = somat + 1\n tt.append(somat)\n\n \n z += 1\n count['A'] = aa \n count['C'] = cc\n count['G'] = gg\n count['T'] = tt\n return count\n\n#ProfileWithPseudoCounts\n\ndef ProfileWithPseudocounts(Motifs):\n t = len(Motifs) + 4\n k = len(Motifs[0])\n profile = CountWithPseudocounts(Motifs)\n \n for key,v in profile.items():\n v[:] = [x / t for x in v]\n return profile\n\n\n# Input: A set of kmers Motifs\n# Output: CountWithPseudocounts(Motifs)\n# HINT: You need to use CountWithPseudocounts as a subroutine of ProfileWithPseudocounts\ndef CountWithPseudocounts(Motifs):\n count = {}\n aa = []\n cc = []\n gg = []\n tt = []\n z = 0 \n while z <= (len(Motifs[0])-1):\n somaa = 0\n for i in Motifs:\n if i[z] == 'A':\n somaa += 1\n somaa = somaa + 1\n aa.append(somaa)\n \n somac = 0\n for i in Motifs:\n if i[z] == 'C':\n somac += 1\n somac = somac + 1\n cc.append(somac)\n\n somag = 0\n for i in Motifs:\n if i[z] == 'G':\n somag += 1\n somag = somag + 1\n gg.append(somag)\n\n somat = 0\n for i in Motifs:\n if i[z] == 'T':\n somat += 1\n somat = somat + 1\n tt.append(somat)\n\n \n z += 1\n count['A'] = aa \n count['C'] = cc\n count['G'] = gg\n count['T'] = tt\n return count\n\n\n### GreedyMotifSearchWithPseudocounts \n\ndef GreedyMotifSearchWithPseudocounts(Dna,k,t):\n BestMotifs = []\n for i in range(0, t):\n BestMotifs.append(Dna[i][0:k])\n n = len(Dna[0])\n for m in range(n-k+1):\n Motifs = []\n Motifs.append(Dna[0][m:m+k])\n for j in range(1, t):\n P = ProfileWithPseudocounts(Motifs[0:j])\n Motifs.append(ProfileMostProbablePattern(Dna[j], k, P))\n if Score(Motifs) < Score(BestMotifs):\n BestMotifs = Motifs\n return BestMotifs\n \n \n \n \ndef ProfileWithPseudocounts(Motifs):\n profile = {}\n k = len(Motifs[0])\n t = len(Motifs)\n profile = CountWithPseudocounts(Motifs)\n \n for i in range(k):\n p = 0\n \n for symbol in \"ACGT\":\n p = p+profile[symbol][i]\n for symbol in \"ACGT\":\n profile[symbol][i] = profile[symbol][i]/p\n return profile\n\ndef Score(Motifs):\n consensus = Consensus(Motifs)\n count = CountWithPseudocounts(Motifs)\n \n k = len(Motifs[0])\n t = len(Motifs) \n c = 0\n for Motif in Motifs:\n for i in range(k):\n if Motif[i] != consensus[i]:\n c = c+1\n return c\n\n\ndef Consensus(Motifs):\n consensus = \"\"\n k = len(Motifs[0])\n t = len(Motifs)\n count = CountWithPseudocounts(Motifs)\n for j in range(k):\n m = 0\n frequentSymbol = \"\"\n for symbol in \"ACGT\":\n if count[symbol][j] > m:\n m = count[symbol][j]\n frequentSymbol = symbol\n consensus += frequentSymbol\n return consensus\n\n\ndef CountWithPseudocounts(Motifs):\n count = {}\n k = len(Motifs[0])\n for symbol in \"ACGT\":\n count[symbol] = []\n for j in range(k):\n count[symbol].append(1)\n t = len(Motifs)\n for i in range(t):\n for j in range(k):\n symbol = Motifs[i][j]\n count[symbol][j] = count[symbol][j]+1\n return count\n\ndef ProfileMostProbablePattern(Text, k, profile):\n n = len(Text)\n m = -1 #This is the bug - need to adjust it to -1 from 0\n x = Text[1:k]\n for i in range(n-k+1):\n Pattern = Text[i:i+k]\n p = Pr(Pattern, profile)\n if p>m:\n m = p\n x = Pattern\n \n return x\n\n\ndef Pr(Text, Profile):\n \n p = 1\n for i in range(len(Text)):\n \n p1 = Profile[(Text[i])][i]\n p = p*p1\n \n return p\n\n\n### GreedyMotifSearch with pseudocounts\n\ndef Count(Motifs):\n\n count = {}\n\n k = len(Motifs[0])\n\n for symbol in \"ACGT\":\n\n count[symbol] = []\n\n for j in range(k):\n\n count[symbol].append(1)\n\n t = len(Motifs)\n\n for i in range(t):\n\n for j in range(k):\n\n symbol = Motifs[i][j]\n\n count[symbol][j] += 1\n\n return count\n\ndef Consensus(Motifs):\n\n k = len(Motifs[0])\n\n count = Count(Motifs)\n\n consensus = \"\"\n\n for j in range(k):\n\n m = 0\n\n frequentSymbol = \"\"\n\n for symbol in \"ACGT\":\n\n if count[symbol][j] > m:\n\n m = count[symbol][j]\n\n frequentSymbol = symbol\n\n consensus += frequentSymbol\n\n return consensus\n\ndef Profile(Motifs):\n\n t = len(Motifs)\n\n k = len(Motifs[0])\n\n profile = Count(Motifs)\n\n for i in 'ACTG':\n\n for j in range(k):\n\n profile[i][j] = profile[i][j]/t \n\n return profile\n\ndef Score(Motifs):\n\n # Insert code here\n\n score = 0\n\n k = len(Motifs[0])\n\n count = Count(Motifs)\n\n max_symbol = Consensus(Motifs)\n\n sum1 = 0\n\n for j in range(k):\n\n m = 0\n\n for symbol in \"ATCG\":\n\n if count[symbol][j] > m:\n\n sum1 += count[symbol][j]\n\n for j in range(k):\n\n m = 0\n\n for symbol in \"AGTC\":\n\n if count[symbol][j] > m:\n\n m = count[symbol][j]\n\n score += m \n\n return sum1-score\n\ndef Pr(Text, Profile):\n\n p=1\n\n k = len(Profile[\"A\"])\n\n for i in range(len(Text)):\n\n p=p*Profile[Text[i]][i]\n\n return p\n\ndef ProfileMostProbablePattern(text,k,profile):\n\n p=-1\n\n result=text[0:k]\n\n for i in range(len(text)-k+1):\n\n seq=text[i:i+k]\n\n pr=Pr(seq,profile)\n\n if pr>p:\n\n p=pr\n\n result=seq\n\n return result\n\ndef GreedyMotifSearch(Dna,k,t):\n\n BestMotifs = []\n\n for i in range(0, t):\n\n BestMotifs.append(Dna[i][0:k])\n\n n = len(Dna[0])\n\n for m in range(n-k+1):\n\n Motifs = []\n\n Motifs.append(Dna[0][m:m+k])\n\n for j in range(1, t):\n\n P = Profile(Motifs[0:j])\n\n Motifs.append(ProfileMostProbablePattern(Dna[j], k, P))\n\n if Score(Motifs) < Score(BestMotifs):\n\n BestMotifs = Motifs\n\n return BestMotifs\n\nk = 15\n\nt = 10\n\nMotifs = GreedyMotifSearch(Dna, k, t)\n\n## ADD Dna VARIABLE\n\nprint(Motifs)\n\n\nprint(Score(Motifs))\n\n## RandomMotifs\n\nimport random\n\ndef RandomMotifs(Dna, k, t):\n\n t = len(Dna)\n l = len(Dna[0])\n RandomMotif =[]\n for i in range(t):\n r = random.randint(1,l-k) # 1 is not added as it is inclusive of last element also\n RandomMotif.append(Dna[i][r:r+k])\n return RandomMotif\n\n\n### RandomMotifSearch\n\nimport random\n\ndef randomMotifs(dna,k,t):\n\n kmm = []\n sc = []\n k = 3\n D = {}\n for i in range(0,len(dna)):\n km = []\n for kk in range(len(dna[i])-k+1):\n km += [dna[i][kk:kk+k]]\n D[i] = km\n for m in range(0,t):\n ran = random.randint(0,len(D[0])-1)\n kmm += [D[m][ran]]\n\n return kmm\n\n\ndef ProfileWithPseudocounts(Motifs):\n\n\n t = len(Motifs)\n k = len(Motifs[0])\n profile = CountWithPseudocounts(Motifs) # output variable\n for symbol in profile:\n for kk in range(0,len(profile[symbol])):\n profile[symbol][kk] = profile[symbol][kk]/(len(Motifs) + 4)\n\n return profile\n\n\ndef CountWithPseudocounts(Motifs):\n\n count = {}\n for i in 'ACGT':\n count[i] = []\n for ii in range(len(Motifs[0])):\n count[i].append(1)\n for i in range(len(Motifs)):\n for j in range(len(Motifs[0])):\n symbol = Motifs[i][j]\n count[symbol][j] += 1\n\n return count\n\n\n\ndef Score(Motifs):\n\n\n count = 0\n L = Consensus(Motifs)\n for i in Motifs:\n for chr1, chr2 in zip(i,L):\n if chr1 != chr2:\n count += 1\n return count\n\n\ndef Consensus(Motifs):\n\n\n\n k = len(Motifs[0])\n count = Count(Motifs)\n consensus = \"\"\n for j in range(k):\n m = 0\n frequentSymbol = \"\"\n for symbol in \"ACGT\":\n if count[symbol][j] > m:\n m = count[symbol][j]\n frequentSymbol = symbol\n consensus += frequentSymbol\n\n return consensus\n\n\ndef Count(Motifs):\n\n count = {}\n for i in 'ACGT':\n count[i] = []\n for ii in range(len(Motifs[0])):\n count[i].append(0)\n for i in range(len(Motifs)):\n for j in range(len(Motifs[0])):\n symbol = Motifs[i][j]\n count[symbol][j] += 1\n\n return count\n\n\ndef RandomMotifs(dna,k,t):\n\n kmm = []\n sc = []\n D = {}\n for i in range(0,len(dna)):\n km = []\n for kk in range(len(dna[i])-k+1):\n km += [dna[i][kk:kk+k]]\n D[i] = km\n for m in range(0,t):\n ran = random.randint(0,len(D[0])-1)\n kmm += [D[m][ran]]\n\n return kmm\n\ndef Motifs(pf,dna):\n\n k = len(pf['A'])\n D = []\n for i in range(0,len(dna)):\n km = []\n sc = []\n for kk in range(len(dna[i])-k+1):\n km += [dna[i][kk:kk+k]]\n for i in km:\n sc += [Pr(i,pf)]\n D += [km[sc.index(max(sc))]]\n\n return D\n\n\ndef Pr(Text, Profile):\n\n p = 1\n for i in range(0,len(Text)):\n p *= Profile[Text[i]][i]\n\n return p\n\n\ndef RandomizedMotifSearch(Dna, k, t):\n\n M = RandomMotifs(Dna, k, t)\n BestMotifs = M\n\n while True:\n Profile = ProfileWithPseudocounts(M)\n M = Motifs(Profile, Dna)\n if Score(M) < Score(BestMotifs):\n BestMotifs = M\n else:\n return BestMotifs\n\n\n### Normalize Values\n\ndef Normalize(P):\n\n d = {}\n for k,v in P.items():\n d[k] = P[k]/sum(P.values())\n return d\n\nd = {'A': 0.1, 'C': 0.1, 'G': 0.1, 'T': 0.1}\n\n\n### WeightedDie\n\ndef WeightedDie(Probabilities):\n n = random.uniform(0, 1)\n for p in Probabilities:\n n -= Probabilities[p]\n if n <= 0:\n return p\n\n\n###\n\nimport random\nfrom operator import itemgetter\n# then, copy Pr, Normalize, and WeightedDie below this line\ndef WeightedDie(d):\n ran = random.uniform(0, 1)\n #print(ran,d)\n tot = 0\n for k, v in sorted(d.items(),key=itemgetter(1)):\n if tot <= ran < v + tot:\n return k\n tot += v\ndef Normalize(P):\n D = {}\n for k,v in P.items():\n D[k] = P[k]/sum(P.values())\n return D\ndef Pr(Text, Profile):\n p = 1\n for i in range(0,len(Text)):\n p *= Profile[Text[i]][i]\n return p\n# Input: A string Text, a profile matrix Profile, and an integer k\n# Output: ProfileGeneratedString(Text, profile, k)\ndef ProfileGeneratedString(Text, profile, k):\n # your code here\n n = len(Text)\n probabilities = {}\n for i in range(0,n-k+1):\n probabilities[Text[i:i+k]] = Pr(Text[i:i+k], profile)\n\n probabilities = Normalize(probabilities)\n return WeightedDie(probabilities)\n\n\n### GibbsSampler \n\nimport random\n# Input: Integers k, t, and N, followed by a collection of strings Dna\n# Output: GibbsSampler(Dna, k, t, N)\ndef GibbsSampler(Dna, k, t, N):\n BestMotifs = [] # output variable\n # your code here\n Motifs = RandomMotifs(Dna, k, t)\n BestMotifs = Motifs\n for j in range(1,N):\n i = random.randint(0,t-1)\n ReducedMotifs = []\n for j in range(0,t):\n if j != i:\n ReducedMotifs.append(Motifs[j])\n Profile = ProfileWithPseudocounts(ReducedMotifs)\n Motif_i = ProfileGeneratedString(Dna[i], Profile, k)\n Motifs[i] = Motif_i\n if Score(Motifs) < Score(BestMotifs):\n BestMotifs=Motifs\n return BestMotifs\n# place all subroutines needed for GibbsSampler below this line\n# Input: A list of strings Dna, and integers k and t\n# Output: RandomMotifs(Dna, k, t)\n# HINT: You might not actually need to use t since t = len(Dna), but you may find it convenient\ndef RandomMotifs(Dna, k, t):\n # place your code here.\n s = len(Dna[0])\n rm = []\n for i in range(0,t):\n init_index = random.randint(1,s-k)\n rm.append(Dna[i][init_index:init_index+k]) \n return rm\n# Input: A set of kmers Motifs\n# Output: ProfileWithPseudocounts(Motifs)\ndef ProfileWithPseudocounts(Motifs):\n t = len(Motifs)\n k = len(Motifs[0])\n profile = {} # output variable\n # your code here\n c = CountWithPseudocounts(Motifs)\n for n in 'ACGT':\n p = []\n for i in range(0,k):\n p.append(c[n][i]/(t+4))\n profile[n] = p\n return profile\n# Input: A set of kmers Motifs\n# Output: CountWithPseudocounts(Motifs)\ndef CountWithPseudocounts(Motifs):\n t = len(Motifs)\n k = len(Motifs[0])\n # insert your code here\n count = {} # initializing the count dictionary\n for symbol in \"ACGT\":\n count[symbol] = []\n for j in range(k):\n count[symbol].append(1)\n for i in range(t):\n for j in range(k):\n symbol = Motifs[i][j]\n count[symbol][j] += 1\n return count \n#tests in which of the intervals defined by list ar the number r lies\ndef testinterval(ar,r):\n ar.sort()\n if r<= ar[0]:\n return ar[0]\n for i in range(1,len(ar)-1):\n if ar[i-1] m:\n m = count[symbol][j]\n frequentSymbol = symbol\n consensus += frequentSymbol\n\n return consensus\n\n\ndef Count(Motifs):\n\n count = {}\n for i in 'ACGT':\n count[i] = []\n for ii in range(len(Motifs[0])):\n count[i].append(0)\n for i in range(len(Motifs)):\n for j in range(len(Motifs[0])):\n symbol = Motifs[i][j]\n count[symbol][j] += 1\n\n return count\n\n\ndef RandomMotifs(dna,k,t):\n\n kmm = []\n sc = []\n D = {}\n for i in range(0,len(dna)):\n km = []\n for kk in range(len(dna[i])-k+1):\n km += [dna[i][kk:kk+k]]\n D[i] = km\n for m in range(0,t):\n ran = random.randint(0,len(D[0])-1)\n kmm += [D[m][ran]]\n\n return kmm\n\ndef Motifs(pf,dna):\n\n k = len(pf['A'])\n D = []\n for i in range(0,len(dna)):\n km = []\n sc = []\n for kk in range(len(dna[i])-k+1):\n km += [dna[i][kk:kk+k]]\n for i in km:\n sc += [Pr(i,pf)]\n D += [km[sc.index(max(sc))]]\n\n return D\n\n\ndef Pr(Text, Profile):\n\n p = 1\n for i in range(0,len(Text)):\n p *= Profile[Text[i]][i]\n\n return p\n\n\ndef RandomizedMotifSearch(Dna, k, t):\n\n M = RandomMotifs(Dna, k, t)\n BestMotifs = M\n\n while True:\n Profile = ProfileWithPseudocounts(M)\n M = Motifs(Profile, Dna)\n if Score(M) < Score(BestMotifs):\n BestMotifs = M\n else:\n return BestMotifsionary Probabilities, where keys are k-mers and values are the probabilities of these k-mers (which do not necessarily sum up to 1)\n# Output: A normalized dictionary where the probability of each k-mer was divided by the sum of all k-mers' probabilities\ndef Normalize(Probabilities):\n # your code here\n result = {}\n sum = 0\n for m in Probabilities:\n sum += Probabilities[m]\n for n in Probabilities:\n result[n]= Probabilities[n]/sum\n return result \n# Input: A set of k-mers Motifs\n# Output: The score of these k-mers.\ndef Score(Motifs):\n # Insert code here\n k = len(Motifs[0])\n t = len(Motifs)\n cs = ConsensusWithPseudocounts(Motifs)\n score = 0\n for j in range(0,k):\n for i in range(0,t):\n if Motifs[i][j] != cs[j]:\n score += 1\n return score\n# Input: A set of kmers Motifs\n# Output: A consensus string of Motifs.\ndef ConsensusWithPseudocounts(Motifs):\n # insert your code here\n k = len(Motifs[0])\n count = CountWithPseudocounts(Motifs)\n consensus = \"\"\n for j in range(k):\n m = 0\n frequentSymbol = \"\"\n for symbol in \"ACGT\":\n if count[symbol][j] > m:\n m = count[symbol][j]\n frequentSymbol = symbol\n consensus += frequentSymbol\n return consimport random\n\ndef randomMotifs(dna,k,t):\n\n kmm = []\n sc = []\n k = 3\n D = {}\n for i in range(0,len(dna)):\n km = []\n for kk in range(len(dna[i])-k+1):\n km += [dna[i][kk:kk+k]]\n D[i] = km\n for m in range(0,t):\n ran = random.randint(0,len(D[0])-1)\n kmm += [D[m][ran]]\n\n return kmm\n\n\ndef ProfileWithPseudocounts(Motifs):\n\n\n t = len(Motifs)\n k = len(Motifs[0])\n profile = CountWithPseudocounts(Motifs) # output variable\n for symbol in profile:\n for kk in range(0,len(profile[symbol])):\n profile[symbol][kk] = profile[symbol][kk]/(len(Motifs) + 4)\n\n return profile\n\n\ndef CountWithPseudocounts(Motifs):\n\n count = {}\n for i in 'ACGT':\n count[i] = []\n for ii in range(len(Motifs[0])):\n count[i].append(1)\n for i in range(len(Motifs)):\n for j in range(len(Motifs[0])):\n symbol = Motifs[i][j]\n count[symbol][j] += 1\n\n return count\n\n\n\ndef Score(Motifs):\n\n\n count = 0\n L = Consensus(Motifs)\n for i in Motifs:\n for chr1, chr2 in zip(i,L):\n if chr1 != chr2:\n count += 1\n return count\n\n\ndef Consensus(Motifs):\n\n\n\n k = len(Motifs[0])\n count = Count(Motifs)\n consensus = \"\"\n for j in range(k):\n m = 0\n frequentSymbol = \"\"\n for symbol in \"ACGT\":\n if count[symbol][j] > m:\n m = count[symbol][j]\n frequentSymbol = symbol\n consensus += frequentSymbol\n\n return consensus\n\n\ndef Count(Motifs):\n\n count = {}\n for i in 'ACGT':\n count[i] = []\n for ii in range(len(Motifs[0])):\n count[i].append(0)\n for i in range(len(Motifs)):\n for j in range(len(Motifs[0])):\n symbol = Motifs[i][j]\n count[symbol][j] += 1\n\n return count\n\n\ndef RandomMotifs(dna,k,t):\n\n kmm = []\n sc = []\n D = {}\n for i in range(0,len(dna)):\n km = []\n for kk in range(len(dna[i])-k+1):\n km += [dna[i][kk:kk+k]]\n D[i] = km\n for m in range(0,t):\n ran = random.randint(0,len(D[0])-1)\n kmm += [D[m][ran]]\n\n return kmm\n\ndef Motifs(pf,dna):\n\n k = len(pf['A'])\n D = []\n for i in range(0,len(dna)):\n km = []\n sc = []\n for kk in range(len(dna[i])-k+1):\n km += [dna[i][kk:kk+k]]\n for i in km:\n sc += [Pr(i,pf)]\n D += [km[sc.index(max(sc))]]\n\n return D\n\n\ndef Pr(Text, Profile):\n\n p = 1\n for i in range(0,len(Text)):\n p *= Profile[Text[i]][i]\n\n return p\n\n\ndef RandomizedMotifSearch(Dna, k, t):\n\n M = RandomMotifs(Dna, k, t)\n BestMotifs = M\n\n while True:\n Profile = ProfileWithPseudocounts(M)\n M = Motifs(Profile, Dna)\n if Score(M) < Score(BestMotifs):\n BestMotifs = M\n else:\n return BestMotifsensus \n\nk = 8\nt = 5\nN = 100\nDna = [\"CGCCCCTCTCGGGGGTGTTCAGTAAACGGCCA\",\"GGGCGAGGTATGTGTAAGTGCCAAGGTGCCAG\",\"TAGTACCGAGACCGAAAGAAGTATACAGGCGT\",\"TAGATCAAGTTTCAGGTGCACGTCGGTGAACC\",\"AATCCACCAGCTCCACGTGCAATGTTGGCCTA\"]\n\n'''\n\n# Run Code Here #\n\n# End Code #"} {"blob_id": "85b864ea68f4f8c81b96204244609fc540377d07", "repo_name": "gokmonk/Bowerbird", "path": "/s/python/old_interface/web_interface/lib/token_bucket.py", "length_bytes": 2032, "score": 3.5625, "int_score": 4, "content": "import threading\nimport time\n\nclass TokenBucket(object):\n \"\"\"An implementation of the token bucket algorithm.\n source: http://code.activestate.com/recipes/511490/\n\n >>> bucket = TokenBucket(80, 0.5)\n >>> print bucket.consume(10)\n True\n >>> print bucket.consume(90)\n False\n \"\"\"\n def __init__(self, capacity, fill_rate, lock=None):\n \"\"\"capacity is the maximum tokens in the bucket.\n fill_rate is the rate in tokens/second that the bucket will be refilled.\n A negative fill_rate means that the bucket is always full.\n lock is the synchronisation lock to use (a threading.RLock if None)\"\"\"\n self.capacity = float(capacity)\n self._tokens = float(capacity)\n self.fill_rate = float(fill_rate)\n self._timestamp = time.time()\n if lock:\n self._lock = lock\n else:\n self._lock = threading.RLock()\n\n @property\n def tokens(self):\n with self._lock:\n self._update_tokens()\n return self._tokens\n\n def consume(self, tokens):\n \"\"\"Consume tokens from the bucket. Returns 0 if there were\n sufficient tokens, otherwise the expected time until enough\n tokens become available.\"\"\"\n if tokens > self.capacity:\n raise ValueError('Requested tokens (%f) exceeds capacity (%f)' %\n (tokens, self.capacity))\n with self._lock:\n self._update_tokens()\n if tokens <= self._tokens:\n self._tokens -= tokens\n return 0\n return (tokens - self._tokens) / self.fill_rate\n\n def _update_tokens(self):\n if self._tokens < self.capacity:\n if self.fill_rate < 0:\n self._tokens = self.capacity\n else:\n now = time.time()\n # limit tokens to capacity\n self._tokens = min(self.capacity, self._tokens +\n self.fill_rate * (now - self._timestamp))\n self._timestamp = now\n\n\n"} {"blob_id": "e9fe1a197df69069a24c35b105ba4a5b13b5d6c7", "repo_name": "dobreandl/statistical-tests", "path": "/Statistical-tests/Tests/ChiSquare.py", "length_bytes": 2218, "score": 3.703125, "int_score": 4, "content": "'''\nCreated on Jan 23, 2018\n\n@author: dobreandragos\n'''\n\n\nfrom scipy.stats import chisquare, chi2\n\n'''\nComputes the chi square value and returns if the null hypothesis should be accepted or not\n\nThe acceptance of the hypothesis means that the current values and the expected ones match\nfor the given accept/reject probability.\n\nParameters\n ----------\n currentValues : array\n Observed frequencies in each category.\n expectedValues : array\n Expected frequencies in each category. \n acceptRejectProbability : float\n Value between 0 and 1 which denotes the grade of confidence of accepting/rejecting the\n hypotethis\n\n Returns\n -------\n chisq : float\n The chi-squared test statistic.\n criticalPoint : float\n The critical point for the data provided and the acceptRejectProbability\n accept: boolean\n Denotes if the hypothesis is accepted or not\n'''\ndef chi_compute(currentValues, expectedValues, acceptRejectProbability):\n degreesOfFreedom = len(currentValues) - 1\n \n criticalPoint = chi2.isf(q=(1 - acceptRejectProbability), df=degreesOfFreedom)\n \n chisq, _ = chisquare(currentValues, expectedValues)\n \n return chisq, criticalPoint, chisq < criticalPoint\n\n\n'''\nTests for the chi_compute\n'''\n\ndef test_chi_compute():\n _, _, accepted = chi_compute([28,22], [25,25], 0.95)\n \n assert accepted == True\n \n _, _, accepted = chi_compute([10,40], [25,25], 0.95)\n \n assert accepted == False \n\n'''\nDemonstrates the chi_compute function for testing a coin flip results\n'''\ndef chi_compute_usage_example():\n numberOfFlips = 50 # 50 coins flips\n acceptRejectProbability = 0.95\n currentHeadFlips = 28 # number of flips which resulted into a head result\n \n currentValues = [numberOfFlips - currentHeadFlips, numberOfFlips - currentHeadFlips] # 28 Heads and 22 tails\n expectedValues = [numberOfFlips / 2, numberOfFlips / 2]\n \n chisq, criticalPoint, accepted = chi_compute(currentValues, expectedValues, acceptRejectProbability)\n \n print(\"ChiSq value: \"+ str(chisq) + \" critical point: \" + str(criticalPoint) + \" accepted: \"+ str(accepted))\n \n \nchi_compute_usage_example()\n \n \n "} {"blob_id": "ae36424aa147c35586f8395b4c49b34448d9820c", "repo_name": "LukasForst/RPH", "path": "/prisoners_dilemma/player_backup/player.py", "length_bytes": 5605, "score": 3.53125, "int_score": 4, "content": "class MyPlayer:\n\n \"\"\"analyzuje matici,hraje podle ni,pokusi se nejvyhodneji kooperovat s protivn\u00edkem\"\"\"\n\n # navrh matice payoff_matrix[[(4,4), (1,6)],[(6,1), (2,2)]]\n # 4,4 - 1,6\n # 6,1 - 2,2\n # obecne payoff_matrix[coop, defect]\n # cilem je nasbirat co nejmene bodu\n\n def __init__(self, payoff_matrix, *number_of_iterations): # number_of_iterations nemusi program dostat\n\n self.opponent_move_record = [] # pole se zaznamem tahu\n self.my_last_turn = None\n self.tactic = None # konecna taktika\n self.found_tactic = None # taktika sledovani oponenta\n self.changed = False # prepinac, pokud zmenim taktiku podle soupere = True\n self.iterations_available = False # dostupnost poctu iteraci\n self.steps = 0 # je rychlejsi pouzivat steps counting nez pokazde se dotazovat na len(self.opponent_move_record)\n\n self.matrix_coop1 = payoff_matrix[0][0][0] # dosazeni do promenych z poli\n self.matrix_coop2 = payoff_matrix[1][0][0]\n self.matrix_def1 = payoff_matrix[0][1][0]\n self.matrix_def2 = payoff_matrix[1][1][0]\n\n if(number_of_iterations): # overeni, zdali je number_of_iteration k dispozici\n self.iterations = number_of_iterations[0]\n self.iterations_available = True\n else:\n self.iterations_available = False\n\n MyPlayer.get_basic_tactic(self)\n\n def record_opponents_move(self, opponent_move): # vstup je posledni protivnikuv tah FALSE = cooperate, TRUE = defect\n if(opponent_move):\n self.opponent_move_record.append(True) # defect\n else:\n self.opponent_move_record.append(False) # cooperate\n\n def get_basic_tactic(self): # metoda pro zjisteni idealni taktiky\n if((self.matrix_coop1 + self.matrix_coop2) < (self.matrix_def1 + self.matrix_def2)): # analyza matice, pokud je soucet vice bodu za coop tak def jinak opacne\n self.basic_tactics = True # klasicka taktika vypoctena z vyhodnosti matice\n else:\n self.basic_tactics = False\n self.tactic = self.basic_tactics\n\n def opponent_same_tactic(self): # zjisteni, jestli protivnik nehraje porad stejne\n opponent_basic_move = self.opponent_move_record[0]\n opponent_same_tactic = False\n\n for i in range(1,self.steps):\n if(self.opponent_move_record[i] == opponent_basic_move):\n opponent_same_tactic = True\n else:\n opponent_same_tactic = False\n break\n\n if(opponent_same_tactic and self.opponent_move_record[-1]): # pokud ma porad stejnou taktiku a hraje Defect\n if(self.matrix_coop2 > self.matrix_def2):\n self.basic_tactics = True\n self.changed = True\n elif(self.matrix_coop2 < self.matrix_def2):\n self.basic_tactics = False\n self.basic_tactics = True\n else:\n MyPlayer.get_basic_tactic(self)\n\n elif(opponent_same_tactic and not self.opponent_move_record[-1]): # pokud ma porad stejnou taktiku a hraje Cooperate\n if(self.matrix_coop1 > self.matrix_coop2):\n self.basic_tactics = False\n self.changed = True\n elif(self.matrix_def1 < self.matrix_def2):\n self.basic_tactics = True\n self.changed = True\n else:\n MyPlayer.get_basic_tactic(self)\n\n\n def get_opponent_tactic(self): # zjisteni, zdali nehraje protivnik porad stejne\n\n # kontrola provedenych kroku\n # provadi se pouze pokud byla hrana vice nez 4 kola\n # take pouze pokud se schoduje posledni a predposledni tah soupere\n # diky tomu se da zjistit, zdali delsi dobu nehraje stejne tahy\n\n if(not self.changed):\n if (self.opponent_move_record[-1] == self.opponent_move_record[-2] == self.opponent_move_record[-3] == self.my_last_turn):\n if (self.matrix_coop2 < self.matrix_def2):\n self.found_tactic = False\n else:\n self.found_tactic = True\n self.tactic = self.found_tactic\n self.changed = True\n\n else: #pokud se protivnik neprispusobi, nastavi se klasicka taktika zpet\n if (self.opponent_move_record[-1] == self.opponent_move_record[-2] and self.my_last_turn != self.opponent_move_record[-1]):\n self.tactic = self.basic_tactics\n self.changed = False\n\n def opponent_cheating_check(self): # pokud e prizpusobim hraci a on mi zacne podvadet nastavim zpet klasickou taktiku\n for i in range(self.steps-1, self.steps-5, -1):\n if(self.my_last_turn != self.opponent_move_record[i]):\n MyPlayer.get_basic_tactic(self)\n self.changed = False\n break\n\n def move(self): # vyhodnoceni a predani tahu pocitaci\n if (self.steps == 5 or self.steps == 6): # po trech krocich se zkontroluje, jestli nehraju proti podobnemu hraci, jako jsem ja\n MyPlayer.get_opponent_tactic(self)\n elif (self.steps == 10 and not self.changed): # po deseti krocich se zjisti, jestli protivnik nehraje porad stejne\n MyPlayer.opponent_same_tactic(self)\n elif(self.steps > 12 and self.steps%5 == 0 and self.changed): # kontrola, zdali me protivnik nepodvadi pri nejvyhodnejsi taktice pro nas oba\n MyPlayer.opponent_cheating_check(self)\n\n self.steps += 1# pocet probehlych iteraci\n self.my_last_turn = self.tactic\n return self.tactic\n\n"} {"blob_id": "dcda426fca3ded5f64241558a64fd5e0828d4e88", "repo_name": "edkrueger/python-algorithms", "path": "/resc/math.py", "length_bytes": 1873, "score": 3.65625, "int_score": 4, "content": "\"\"\"Math Utilities.\"\"\"\n\n# pylint: disable=invalid-name\n# pylint: disable=too-many-locals\n\n\ndef recursive_integer_multiplication(x, y):\n \"\"\"Takes two positive integers and finds their product.\"\"\"\n\n x_str = str(x)\n y_str = str(y)\n\n len_x = len(x_str)\n len_y = len(y_str)\n\n if len_x == 1 and len_y == 1:\n return x * y\n\n # disabled because lack of walrus suport\n # pylint: disable=used-before-assignment\n n = len_max if (len_max := max(len_x, len_y)) % 2 == 0 else len_max + 1\n\n x_str_padded = (n - len_x) * \"0\" + x_str\n y_str_padded = (n - len_y) * \"0\" + y_str\n\n a = int(x_str_padded[0 : n // 2])\n b = int(x_str_padded[n // 2 :])\n c = int(y_str_padded[0 : n // 2])\n d = int(y_str_padded[n // 2 :])\n\n ad = recursive_integer_multiplication(a, d)\n bc = recursive_integer_multiplication(b, c)\n ac = recursive_integer_multiplication(a, c)\n bd = recursive_integer_multiplication(b, d)\n\n return (10 ** n) * ac + (10 ** (n // 2)) * (ad + bc) + bd\n\n\ndef karatsuba_multiplication(x, y):\n \"\"\"Takes two positive integers and finds their product.\"\"\"\n\n x_str = str(x)\n y_str = str(y)\n\n len_x = len(x_str)\n len_y = len(y_str)\n\n if len_x == 1 and len_y == 1:\n return x * y\n\n # disabled because lack of walrus suport\n # pylint: disable=used-before-assignment\n n = len_max if (len_max := max(len_x, len_y)) % 2 == 0 else len_max + 1\n\n x_str_padded = (n - len_x) * \"0\" + x_str\n y_str_padded = (n - len_y) * \"0\" + y_str\n\n a = int(x_str_padded[0 : n // 2])\n b = int(x_str_padded[n // 2 :])\n c = int(y_str_padded[0 : n // 2])\n d = int(y_str_padded[n // 2 :])\n\n pq = recursive_integer_multiplication(a + b, c + d)\n ac = recursive_integer_multiplication(a, c)\n bd = recursive_integer_multiplication(b, d)\n\n return (10 ** n) * ac + (10 ** (n // 2)) * (pq - ac - bd) + bd\n"} {"blob_id": "7d469f3da759e8e59daa6362096803b748415aa9", "repo_name": "mmariani/meuler", "path": "/037/037.py", "length_bytes": 663, "score": 3.640625, "int_score": 4, "content": "#!/usr/bin/env python3\n\nimport itertools\nimport primes\n\n\ndef truncations(n):\n # also yields the whole number\n s = str(n)\n s1 = str(n)\n while s:\n yield int(s)\n s = s[1:]\n while s1:\n yield int(s1)\n s1 = s1[:-1]\n\n\ndef run():\n found = set()\n primeset = set()\n for p in primes.eratosthenes():\n primeset.add(p)\n if p <= 7:\n continue\n if set(truncations(p)).issubset(primeset):\n found.add(p)\n # the problems states there are only 11 such numbers\n if len(found) == 11:\n break\n print(sum(found))\n\n\n\nif __name__ == '__main__':\n run()\n\n"} {"blob_id": "7481319900ced20d5e88ebe5a105deafc7a55e96", "repo_name": "pashovt/LeetcodeJuneChallenge", "path": "/Week1 1st-7th June/Day6 - Queue Reconstruction by Height.py", "length_bytes": 1167, "score": 3.921875, "int_score": 4, "content": "\"\"\"\nSuppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h. Write an algorithm to reconstruct the queue.\n\nNote:\nThe number of people is less than 1,100.\n\n \nExample\n\nInput:\n[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]\n\nOutput:\n[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]\n\nHint 1:\nWhat can you say about the position of the shortest person?\nIf the position of the shortest person is i, how many people would be in front of the shortest person?\n\nHint 2:\nOnce you fix the position of the shortest person, what can you say about the position of the second shortest person?\n\n\"\"\"\n\nclass Solution:\n def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n result = []\n \n people.sort(key = lambda x : (-x[0], x[1]))\n print(people)\n \n for x in people:\n print(x)\n result.insert(x[1],x)\n print(result)\n return result\n\nSolution.reconstructQueue([[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]])\n"} {"blob_id": "1c7e342291ce5c11e0e76a95690efac05ae0f795", "repo_name": "eselyavka/python", "path": "/leetcode/solution_55.py", "length_bytes": 630, "score": 3.828125, "int_score": 4, "content": "import unittest\n\n\nclass Solution(object):\n def canJump(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n n = len(nums)\n if n == 1:\n return True\n\n dp = [False for i in range(n)]\n goal = n - 1\n for i in range(n - 1, -1, -1):\n if i + nums[i] >= goal:\n dp[i] = True\n goal = i\n\n return dp[0]\n\n\nclass TestSolution(unittest.TestCase):\n def test_canJump(self):\n solution = Solution()\n self.assertTrue(solution.canJump([2, 3, 1, 1, 4]))\n\n\nif __name__ == '__main__':\n unittest.main()\n"} {"blob_id": "770ef3b94caf98d071db17281f86385130a216e7", "repo_name": "akashvacher/AdventOfCode2019", "path": "/day6/day6.1.py", "length_bytes": 989, "score": 3.78125, "int_score": 4, "content": "#!/usr/bin/env python\nfrom collections import defaultdict\n\n# Dictionary mapping a planet to all the moons/parents orbiting around\nchild = defaultdict(list)\ncache = {}\n\n\ndef total_orbits():\n '''\n Return total number of orbits in given system\n '''\n total = 0\n for i in child:\n total += total_satellites(i)\n return total\n\n\ndef total_satellites(planet):\n '''\n Given a planet, return the number of planets/moons\n orbiting around it\n '''\n if planet in cache:\n return cache[planet]\n\n # This planet has no planet orbiting it\n if planet not in child:\n cache[planet] = 0\n return cache[planet]\n\n total = 0\n for i in child[planet]:\n total += 1 + total_satellites(i)\n cache[planet] = total\n return cache[planet]\n\n\ndef load_input():\n global not_root\n with open(\"in.txt\") as f:\n for line in f:\n x, y = line.strip().split(')')\n child[x].append(y)\n\n\nload_input()\nprint(total_orbits())\n"} {"blob_id": "8153becc6d399376e43126ef50db4b3a8f8706ba", "repo_name": "AngelWings1997/Algorithm-and-Complexity", "path": "/Divide and Conquer/Merge Sort/merge sort.py", "length_bytes": 1598, "score": 3.890625, "int_score": 4, "content": "\"\"\"\n# -*- coding: utf-8 -*-\n@author: Hongzhi Fu\n\"\"\"\n\n# implementation of merge sort\n# to sort a random array with 10,000 elements\n# two metrics (\"number of comparison\" and \"consumed time\") for efficiency evaluation\n# time complexity: \u0398(nlog n) in all cases\n# space complexity \u0398(n)\n# stability: stable\n\nimport time\nimport random\n\ndef merge(a, b):\n i, j, k = 0, 0, 0 # initialize variables\n p, q = len(a), len(b)\n global comparison # global variable\n c = [0 for i in range(p+q)]\n while i < p and j < q:\n if a[i] <= b[j]:\n c[k] = a[i]; i += 1\n else:\n c[k] = b[j]; j += 1\n k += 1\n comparison += 1\n while i < p:\n c[k] = a[i]\n i += 1; k += 1\n while j < q:\n c[k] = b[j]\n j += 1; k += 1\n return c\n\ndef merge_sort(array):\n if len(array) <= 1:\n return array\n m = len(array) // 2 # middle position\n A = merge_sort(array[: m])\n B = merge_sort(array[m:])\n C = merge(A, B)\n return C\n\ntime_in_total = 0\nepoch = 5 # num of iteration\ntotal_comparison = 0\n\nfor i in range(epoch):\n time_start = time.time()\n array = [random.randint(0,10000) for i in range(10000)]\n comparison = 0\n merge_sort(array)\n time_finish = time.time()\n total_comparison += comparison\n time_in_total += time_finish - time_start\n print(\"Epoch {}: \\n number of comparison: {}\\n time consumed: {:.4f} s\".format(i+1, comparison, time_finish-time_start))\nprint(\"average number of comparison: %d\" % (total_comparison/epoch))\nprint('average time consumed: {:.4f} s'.format(time_in_total/epoch))\n\n"} {"blob_id": "0ef8d19b7889c49d9004519e9d860c9dca05ca83", "repo_name": "jaychsu/algorithm", "path": "/leetcode/685_redundant_connection_ii.py", "length_bytes": 1751, "score": 3.796875, "int_score": 4, "content": "\"\"\"\ngiven input is an directed graph\n\n3 corner cases:\n\n1. There is a loop in the graph, and no vertex has more than 1 parent.\n2. A vertex has more than 1 parent, but there isn\u2019t a loop in the graph.\n3. A vertex has more than 1 parent, and is part of a loop.\n\nREF: https://leetcode.com/problems/redundant-connection-ii/discuss/108070/Python-O(N)-concise-solution-with-detailed-explanation-passed-updated-testcases\n\"\"\"\n\n\nimport collections\n\n\nclass Solution:\n def findRedundantDirectedConnection(self, edges):\n \"\"\"\n :type edges: List[List[int]]\n :rtype: List[int]\n \"\"\"\n ans = edge = None # `edge` is the last edge in a loop\n adj = collections.defaultdict(set)\n uf = collections.defaultdict(int)\n has_parent = set()\n\n for u, v in edges:\n adj[u].add(v)\n\n if v in has_parent:\n ans = (u, v)\n\n if not self.union(uf, u, v):\n edge = (u, v)\n\n has_parent.add(v)\n\n if not ans:\n return edge\n\n res = self.dfs(ans[1], adj, set())\n return res if res else ans\n\n def union(self, uf, u, v):\n a = self.find(uf, u)\n b = self.find(uf, v)\n\n if a == b:\n return False\n\n uf[b] = a\n return True\n\n def find(self, uf, u):\n if uf[u] == 0:\n uf[u] = u\n return u\n if uf[u] == u:\n return u\n\n uf[u] = self.find(uf, uf[u])\n return uf[u]\n\n def dfs(self, u, adj, visited):\n # to detect cycle\n visited.add(u)\n\n for v in adj[u]:\n if v in visited:\n return (u, v)\n\n res = self.dfs(v, adj, visited)\n if res:\n return res\n"} {"blob_id": "888f4430afd6d8061b356ffc0b79415f6d7f90d2", "repo_name": "jpsalviano/uri-online-judge", "path": "/2687.py", "length_bytes": 3590, "score": 3.78125, "int_score": 4, "content": "# 2687\r\n\r\n# Depth-first search\r\n\r\n# 1 procura pelos 0 fora do perimetro de 1 (linha 0 e -1, coluna 0 e -1)\r\n# 2 guarda a quantidade de 0 fora do perimetro de 1\r\n# 3 output: ((L x L) - quantidade de 0 fora do perimetro de 1)/2\r\n\r\n# cria uma lista de marcacao marked = []\r\n# busca na primeira row completa, depois desce checando o primeiro e ultimo itens ate a ultima row completa\r\n# for i, row in enumerate(grid) -> for j, col in enumerate(row)\r\n# -> if i != 0 or l-1 -> if j != 0 or l-1 -> continue\r\n# sobre o elemento: if == 0 && if not in marked\r\n# marca: marked.append (row, col)\r\n# cria o stack com o ultimo item da lista de marcacao = [marked[-1]]\r\n###recursive:\r\n# while True:\r\n# if len(stack) == 0, break\r\n# e = stack[-1] > procura ao redor de e -> for n, next in enumerate(grid[r-1][c], grid[r][c+1], grid[r+1][c], grid[r][c-1])\r\n# if next nao existe, esta marcado ou == 1 AND n == 3 -> del stack[-1]\r\n# elif next nao existe, esta marcado ou == 1, continue\r\n# else, marked.append(next), stack.append(next), break\r\n\r\n\r\nq = int(input()) #quantidade de bacterias\r\n\r\nfor _ in range(q):\r\n l = int(input()) #length - largura e altura do grid\r\n grid = [] #cria o grid vazio\r\n for _ in range(l): #preenche com l inputs\r\n row = input().split()\r\n grid.append(row)\r\n marked = [] #lista de elementos marcados\r\n for i_row, row in enumerate(grid): #percorre todas rows\r\n for i_col, col in enumerate(row): #percorre todas cols\r\n if (i_row != 0 or l-1) and (i_col != 0 or l-1): #ignora rows e cols que nao sejam a primeira (0) ou a ultima (-1)\r\n continue\r\n e_row, e_col, e_val = (i_row, i_col, int(grid[i_row][i_col])) #elemento (x, y, v = 0 ou 1)\r\n if (e_val == 0) and (e_row, e_col) not in marked: #se elemento for zero e nao estiver marcado\r\n marked.append((e_row, e_col)) #marca o item\r\n stack = [marked[-1]] #cria stack com o ultimo item da lista\r\n while True: #entra na busca dfs recursiva\r\n if len(stack) == 0: #para quando o stack tiver zerado\r\n break\r\n #up, right, bottom and left neighbours in list neighbors\r\n neighbors_coordinates = [ (e_row-1, e_col), (e_row, e_col+1), (e_row+1, e_col), (e_row, e_col-1) ]\r\n #cria lista de vizinhos excluindo os impossiveis (index fora do grid)\r\n neighbors = [n for n in neighbors_coordinates if 0 <= n[0] <= l-1 and 0 <= n[1] <= l-1]\r\n for i_n, n in enumerate(neighbors): #checa cada um dos vizinhos possiveis\r\n n_row, n_col, n_val = (n[0], n[1], int(grid[n_row][n_col])) #guarda row x col e value (0 ou 1)\r\n if (n_val == 1) or (n_row, n_col) in marked: #se for 1 ou tiver marcado\r\n if i_n == (len(neighbors) - 1): #checa se \u00e9 o ultimo neighbor...\r\n del stack[-1] #caso seja: deleta o ultimo item do stack\r\n continue #caso nao seja: simplesmente checa o proximo vizinho (ou encerra o loop caso seja o ultimo)\r\n else: #caso nao esteja marcado nem seja 1\r\n mark.append((n_row, n_col)) #marca\r\n stack.append((n_row, n_col)) #joga no stack como ultimo item\r\n break #encerra o for loop e volta pro while loop pra checar o ultimo item do stack\r\n print( (l**2 - len(marked)) / 2 ) #printa a quantidade de elementos - marcados / 2"} {"blob_id": "0fcae2059a0b3ed612bc47126f928153dd146c25", "repo_name": "jbobo/leetcode", "path": "/merge_k_sorted_lists.py", "length_bytes": 1130, "score": 4.1875, "int_score": 4, "content": "#!/usr/bin/env python3\n\"\"\" Implement an algorithm to merge K sorted linked lists.\n\nThis solution pushes each node value into a min-heap/p-queue and then pushes each\nvalue from the heap into a new sorted linked list\n\"\"\"\nfrom heapq import heappush, heappop\n\n\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n\ndef merge_k_lists(lists):\n min_heap = []\n\n for node in lists:\n while node:\n heappush(min_heap, node.val)\n node = node.next\n if min_heap:\n sorted_list_head = ListNode(heappop(min_heap))\n pointer = sorted_list_head\n while min_heap:\n pointer.next = ListNode(heappop(min_heap))\n pointer = pointer.next\n return sorted_list_head\n return None\n\n\nif __name__ == \"__main__\":\n # [[1,4,5],[1,3,4],[2,6]]\n lists = [\n ListNode(1, ListNode(4, ListNode(5))),\n ListNode(1, ListNode(3, ListNode(4))),\n ListNode(2, ListNode(6))\n ]\n merged_list = merge_k_lists(lists)\n while merged_list:\n print(merged_list.val)\n merged_list = merged_list.next\n"} {"blob_id": "f7397f85ef3e8beb7324846de250e5e44dfabe61", "repo_name": "ianjustin39/Data-Structures-and-Algorithms", "path": "/DataStructure/problem3_Huffman_Coding .py", "length_bytes": 5844, "score": 3.5625, "int_score": 4, "content": "import sys\n\n\nclass Node:\n def __init__(self, freq, char=None):\n self.left = None\n self.right = None\n self.father = None\n self.freq = freq\n self.char = char\n\n def is_left(self):\n return self.father.left == self\n\n\ndef count_freq(text):\n chars = []\n chars_freqs = []\n for i in range(0, len(text)):\n if text[i] in chars:\n pass\n else:\n chars.append(text[i])\n char_freq = (text[i], text.count(text[i]))\n chars_freqs.append(char_freq)\n return chars_freqs\n\n\ndef create_nodes(data_list):\n return [Node(data[1], data[0]) for data in data_list]\n\n\ndef get_tree(node_list):\n queue = node_list[:]\n while len(queue) > 1:\n queue.sort(key=lambda item: item.freq)\n node_left = queue.pop(0)\n node_right = queue.pop(0)\n node_father = Node(node_left.freq + node_right.freq)\n node_father.left = node_left\n node_father.right = node_right\n node_left.father = node_father\n node_right.father = node_father\n queue.append(node_father)\n queue[0].father = None\n return queue[0]\n\n\ndef get_codes(node_list, root, text, data_list):\n huffman_str = ''\n if len(node_list) > 1:\n codes = [''] * len(node_list)\n for i in range(len(node_list)):\n node_tmp = node_list[i]\n while node_tmp != root:\n if not node_tmp.is_left():\n codes[i] = '0' + codes[i]\n else:\n codes[i] = '1' + codes[i]\n node_tmp = node_tmp.father\n huffman_str = ''\n for char in text:\n i = 0\n for item in data_list:\n if char == item[0]:\n huffman_str += codes[i]\n i += 1\n\n return huffman_str\n else:\n for i in range(len(text)):\n huffman_str += '1'\n return huffman_str\n\n\ndef huffman_encoding(text):\n if text:\n print(\"huffman_encoding start: \", text)\n data_list = count_freq(text)\n node_list = create_nodes(data_list)\n if len(node_list) == 1:\n huffman_str = get_codes(node_list, node_list[0], text, data_list)\n print(\"====>\", huffman_str)\n return huffman_str, node_list[0]\n\n root = get_tree(node_list)\n\n huffman_str = get_codes(node_list, root, text, data_list)\n return huffman_str, root\n else:\n return '', None\n\n\ndef huffman_decoding(encoded_data, tree):\n output = ''\n if encoded_data and tree.char is None:\n output = ''\n node = tree\n for char in encoded_data:\n\n if char == '0':\n node = node.right\n if node.char:\n output += node.char\n node = tree\n\n elif char == '1':\n node = node.left\n if node.char:\n output += node.char\n node = tree\n\n else:\n for i in range(len(encoded_data)):\n output += tree.char\n return output\n\n\nif __name__ == \"__main__\":\n codes = {}\n\n print(\"--- Test case 1 ---\")\n a_great_sentence_1 = \"abccc\"\n\n print(\"The size of the data is: {}\\n\".format(sys.getsizeof(a_great_sentence_1)))\n print(\"The content of the data is: {}\\n\".format(a_great_sentence_1))\n\n encoded_data, tree = huffman_encoding(a_great_sentence_1)\n\n print(\"The size of the encoded data is: {}\\n\".format(sys.getsizeof(int(encoded_data, base=2))))\n print(\"The content of the encoded data is: {}\\n\".format(encoded_data))\n\n decoded_data = huffman_decoding(encoded_data, tree)\n\n print(\"The size of the decoded data is: {}\\n\".format(sys.getsizeof(decoded_data)))\n print(\"The content of the encoded data is: {}\\n\".format(decoded_data))\n\n print(\"--- Test case 2 ---\")\n a_great_sentence_2 = \"The bird is the word\"\n\n print(\"The size of the data is: {}\\n\".format(sys.getsizeof(a_great_sentence_2)))\n print(\"The content of the data is: {}\\n\".format(a_great_sentence_2))\n\n encoded_data, tree = huffman_encoding(a_great_sentence_2)\n\n print(\"The size of the encoded data is: {}\\n\".format(sys.getsizeof(int(encoded_data, base=2))))\n print(\"The content of the encoded data is: {}\\n\".format(encoded_data))\n\n decoded_data = huffman_decoding(encoded_data, tree)\n\n print(\"The size of the decoded data is: {}\\n\".format(sys.getsizeof(decoded_data)))\n print(\"The content of the encoded data is: {}\\n\".format(decoded_data))\n\n print(\"--- Test case 3 ---\")\n a_great_sentence_3 = None\n\n print(\"The size of the data is: {}\\n\".format(sys.getsizeof(a_great_sentence_3)))\n print(\"The content of the data is: {}\\n\".format(a_great_sentence_3))\n\n encoded_data, tree = huffman_encoding(a_great_sentence_3)\n\n print(\"The size of the encoded data is: [\", encoded_data, \"]\")\n print(\"The content of the encoded data is: [\", encoded_data, \"]\")\n\n decoded_data = huffman_decoding(encoded_data, tree)\n\n print(\"The size of the decoded data is: [{}]\\n\".format(sys.getsizeof(decoded_data)))\n print(\"The content of the encoded data is: [{}]\\n\".format(decoded_data))\n\n print(\"--- Test case 4 ---\")\n a_great_sentence_4 = \"aaaaa\"\n\n print(\"The size of the data is: {}\\n\".format(sys.getsizeof(a_great_sentence_4)))\n print(\"The content of the data is: {}\\n\".format(a_great_sentence_4))\n\n encoded_data, tree = huffman_encoding(a_great_sentence_4)\n\n print(\"The size of the encoded data is: {}\\n\".format(sys.getsizeof(int(encoded_data, base=2))))\n print(\"The content of the encoded data is: {}\\n\".format(encoded_data))\n\n decoded_data = huffman_decoding(encoded_data, tree)\n\n print(\"The size of the decoded data is: {}\\n\".format(sys.getsizeof(decoded_data)))\n print(\"The content of the encoded data is: {}\\n\".format(decoded_data))\n\n"} {"blob_id": "917046721deed9f01c3e68144420dd434268ca4e", "repo_name": "doates625/Square-Stacker-AI", "path": "/agents/mcts/mcts.py", "length_bytes": 6296, "score": 3.8125, "int_score": 4, "content": "\"\"\"\nClass to implement Monte Carlo Tree Search (MCTS)\n\nMCTS consists of 4 main steps\n- Selection\n - selects which of the children nodes to search down\n- Expansion\n - if child is a leaf (has no children) will expand the possible states\n- Simulation\n - from a state, simulate random games until a terminal state is reached\n- Backpropagation\n - update values of states on path back to the root node\n\nEach round contributes to choosing the next move\nOriginally used for two-player games in which there is a time limit for each move\nWill be abstracted out for our purposes\n\nIf this works, can be further implemented in ADI which will make an agent out of it\n\"\"\"\nfrom random import choice\nfrom copy import deepcopy\nimport math\nfrom agents.agent import Agent\nfrom square_stacker_game import SquareStackerGame\nfrom agents.mcts.Node import Node\n\n\nclass MCTS(Agent):\n\n def __init__(self, max_sims = 50):\n # Takes an instance of a Board and optionally some keyword\n # arguments. Initializes the list of game states and the\n # statistics tables.\n\n Agent.__init__(self)\n\n self.total_simulations = 0\n self.root_node = None\n self.if_debug = False\n self.loglevel = 0\n\n # parameters to change for how deep it goes\n self.max_sims = max_sims\n\n def select_move(self, game):\n # type: (SquareStackerGame) -> None\n \"\"\"\n Causes the AI to calculate the best move from the current game state and return it.\n :param game: root state\n :return: best possible move\n \"\"\"\n\n root = deepcopy(game)\n self.root_node = Node(root)\n self.total_simulations = 0\n # while within some limit (time or power)\n for i in range(self.max_sims):\n self.total_simulations += 1\n\n if not self.total_simulations % 50:\n self.debug(\"Simulation number: \" + str(self.total_simulations), loglevel=1)\n\n leaf = self.selection(self.root_node) # selection\n self.debug(\"Leaf chosen \" + str(leaf))\n\n simulation_result = self.simulation(leaf)\n self.debug(\"Simulation result: \" + str(simulation_result))\n\n self.backpropagate(leaf, simulation_result)\n\n self.debug(\"MOVE CHOSEN\")\n jesse = self.best_child(self.root_node)\n return jesse.move\n\n # SELECTION\n def selection(self, node):\n # states encoded as state vectors\n self.debug(\"SELECTING\")\n depth = 1\n\n while self.fully_expanded(node):\n depth += 1\n node = self.best_uct(node)\n\n if not self.total_simulations % 50:\n self.debug(\"current depth \" + str(depth), loglevel=1)\n\n # if terminal -> return node and simulate again\n if self.non_terminal(node):\n if node.traversed == 0: # if never traversed -> return node and simulate\n return node\n else: # if has traversed but not expanded -> expand and return child\n return self.expand(node)\n else:\n return node\n\n # EXPLORATION\n def fully_expanded(self, node):\n \"\"\"\n does node have children\n :param node: Node\n :return: bool\n \"\"\"\n # if len(node.children) == len(node.visited_children) and node.children:\n if node.children:\n return True\n else:\n return False\n\n def expand(self, parent):\n \"\"\"\n create children for the node and choose one at random\n :param parent: Node\n :return: Node\n \"\"\"\n self.debug(\"EXPAND CHILDREN\")\n valid_moves = parent.valid_moves\n\n # if not node.children:\n for move in valid_moves:\n new_game = parent.game_state.deepcopy()\n new_game.make_move(move)\n\n child = Node(new_game)\n child.move = move\n child.parent = parent\n parent.children.append(child)\n\n chosen_one = choice(parent.children)\n\n return chosen_one\n\n # SIMULATION\n def simulation(self, node):\n self.debug(\"SIMULATION\")\n # creates copy of game to run simulation on\n sim_game = node.game_state.deepcopy()\n sim_node = deepcopy(node)\n sim_node.game_state = sim_game\n\n while self.non_terminal(sim_node):\n sim_node = self.sim_random(sim_node)\n\n return sim_node.state_score\n\n # randomly select child\n def sim_random(self, node):\n valid_moves = node.valid_moves\n rand_move = choice(valid_moves)\n\n node.game_state.make_move(rand_move)\n node.update_state(node.game_state)\n return node\n\n # BACKPROPAGATION\n def backpropagate(self, node, result):\n \"\"\"\n recursively call function to go up the chain of branch and update scores\n :param node: Node()\n :param result: Int\n :return: None\n \"\"\"\n node.score += result\n node.traversed += 1\n\n if node == self.root_node:\n return\n\n self.backpropagate(node.parent, result)\n\n def best_uct(self, node):\n \"\"\"\n :param node: Node\n :return: Node() with best score\n \"\"\"\n best = node.children[0]\n top_score = self.uct(best)\n scores = []\n for child in node.children:\n try_score = self.uct(child)\n scores.append(try_score)\n if try_score > top_score:\n best = child\n top_score = try_score\n\n self.debug(scores)\n return best\n\n def uct(self, node):\n if node.traversed == 0:\n return math.inf\n return (node.score / node.traversed) + 2 * math.sqrt(math.log(node.parent.traversed) / node.traversed)\n\n def best_child(self, root):\n # select the best child from the tree\n jesse = self.best_uct(root)\n\n return jesse\n\n # check if leaf has any moves left\n def non_terminal(self, leaf):\n \"\"\"\n are there any legal moves from this state\n :param leaf: Node()\n :return: bool\n \"\"\"\n if leaf.valid_moves:\n return True\n else:\n return False\n\n def debug(self, msg, loglevel=0):\n if self.if_debug:\n if loglevel >= self.loglevel:\n print(msg)\n"} {"blob_id": "58742db5719b839c0bc58f018b4c2c3311ff17ab", "repo_name": "markPVale/py-turtles", "path": "/Chap_14_algorithms.py", "length_bytes": 31559, "score": 4.15625, "int_score": 4, "content": "# 14). In the spirit of Test-driven development\n\n# We\u2019d like to know the index where a specific item occurs within in a list of items.\n# Specifically, we\u2019ll return the index of the item if it is found,\n# or we\u2019ll return -1 if the item doesn\u2019t occur in the list.\n# Let us start with some tests:\n\n\n# friends = [\"Joe\", \"Zoe\", \"Brad\", \"Angelina\", \"Zuki\", \"Thandi\", \"Paris\"]\n# assert search_linear(friends, \"Zoe\") == 1\n# assert search_linear(friends, \"Joe\") == 0\n# assert search_linear(friends, \"Paris\") == 6\n# assert search_linear(friends, \"Bill\") == -1\n\n\n# Motivated by the fact that our tests don\u2019t even run,\n# let alone pass, we now write the function:\n\nfrom math import log, ceil\nimport time\nimport urllib.request\n\n\ndef search_linear(xs, target):\n \"\"\"\n Find and return the index of target in sequence xs\n \"\"\"\n for i, v in enumerate(xs):\n if v == target:\n return i\n return -1\n\n\nfriends = [\"Joe\", \"Zoe\", \"Brad\", \"Angelina\", \"Zuki\", \"Thandi\", \"Paris\"]\nassert search_linear(friends, \"Zoe\") == 1\nassert search_linear(friends, \"Joe\") == 0\nassert search_linear(friends, \"Paris\") == 6\nassert search_linear(friends, \"Bill\") == -1\n\n\n# 14.3)\n\n# vocab = [\"apple\", \"boy\", \"dog\", \"down\",\n# \"fell\", \"girl\", \"grass\", \"the\", \"tree\"]\n# book_words = \"the apple fell from the tree to the grass\".split()\n# test(find_unknown_words(vocab, book_words) == [\"from\", \"to\"])\n# test(find_unknown_words([], book_words) == book_words)\n# test(find_unknown_words(vocab, [\"the\", \"boy\", \"fell\"]) == [])\n\n# The basic strategy is to run through each of the words in the book,\n# look it up in the vocabulary, and if it is not in the vocabulary,\n# save it into a new resulting list which we return from the function:\n\n\n# My 'unassisted' attempt:\n# def find_unknown_words(vocab, wds):\n# result = []\n# for wrd in wds:\n# if wrd not in vocab:\n# result.append(wrd)\n# return result\n\n\n# Using the previous algorithm in new algorith:\n\n# def find_unknown_words(vocab, wds):\n# result = []\n# for w in wds:\n# if (search_linear(vocab, w) < 0):\n# result.append(w)\n# return result\n\n\nvocab = [\"apple\", \"boy\", \"dog\", \"down\", \"fell\", \"girl\", \"grass\", \"the\", \"tree\"]\n# book_words = \"the apple fell from the tree to the grass\".split()\n\n# find_unknown_words(vocab, book_words)\n\n# assert find_unknown_words(vocab, book_words) == [\"from\", \"to\"]\n# assert find_unknown_words([], book_words) == book_words\n# assert find_unknown_words(vocab, [\"the\", \"boy\", \"fell\"]) == []\n\n\n# Now let us look at the scalability. We have more realistic vocabulary\n# in the text file that could be downloaded at the beginning of this chapter,\n# so let us read in the file (as a single string) and split it into a list\n# of words\n\nalice_url = \"http://openbookproject.net/thinkcs/python/english3e/_downloads/alice_in_wonderland.txt\"\n\nvocab_url = \"http://openbookproject.net/thinkcs/python/english3e/_downloads/vocab.txt\"\n\n\n# use function from last exercise to download the file from the server:\n\n# import urllib.request\n\n# urllib.request.urlretrieve(url, destination_filename)\n\n# Fetch Alice in Wonderland from the web and add it to new file:\n# urllib.request.urlretrieve(alice_url, \"alice.txt\")\n\n# Fetch 'vocab' from the web and add it to new file:\n# urllib.request.urlretrieve(vocab_url, \"vocab.txt\")\n\n\n# def retrieve_page(url):\n# \"\"\"\n# Retreive the contents of a web page.\n# The contents is converted to a string before returning it.\n# \"\"\"\n# my_socket = urllib.request.urlopen(url)\n# dta = str(my_socket.read())\n# my_socket.close()\n# return dta\n\ndef load_words_from_file(filename):\n \"\"\" Read words from filename, return list of words.\"\"\"\n f = open(filename, \"r\")\n file_content = f.read()\n f.close()\n wds = file_content.split()\n return wds\n\n\nbigger_vocab = load_words_from_file(\"vocab.txt\")\n# print(\"There are {0} words in the vocab, starting with\\n {1} \".format(\n# len(bigger_vocab), bigger_vocab[:6]))\n\n\n# Now let us load up a book\n# We need to clean up the contents of the book.\n# This will involve removing punctuation, and converting everything to the same case\n\n# text_to_words(\"my name is Earl!\") == [\"my\", \"name\", \"is\", \"earl\"]\n# text_to_words(\"'Well, I never!', said Alice.\") == [\n# \"well\", \"i\", \"never\", \"said\", \"alice\"]\n\n\n# Translate method for strings:\n\ndef text_to_words(the_text):\n my_substitutions = the_text.maketrans(\"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\\\"#$%&()*+,-./:;<=>?@[]^_`{|}~'\\\\\",\n \"abcdefghijklmnopqrstuvwxyz \")\n cleaned_text = the_text.translate(my_substitutions)\n wds = cleaned_text.split()\n return wds\n\n\nassert text_to_words(\"my name is Earl!\") == [\"my\", \"name\", \"is\", \"earl\"]\nassert text_to_words(\"'Well, I never!', said Alice.\") == [\n \"well\", \"i\", \"never\", \"said\", \"alice\"]\n\n\n# Now we're ready to read in our book:\n\ndef get_words_from_book(filename):\n read_file = open(filename, \"r\")\n content = read_file.read()\n read_file.close()\n wds = text_to_words(content)\n return wds\n\n\nbook_words = get_words_from_book(\"alice.txt\")\n# print(\"There are {0} words in the book, the first 100 are\\n {1}\".format(\n# len(book_words), book_words[:100]))\n\n\n# Now we have all the pieces ready, let us see what words in this book are not\n# in the vocabulary:\n\n# missing_words = find_unknown_words(bigger_vocab, book_words)\n\n# print(missing_words)\n\n\n# We wait a considerable time now, something like a minute,\n# before Python finally works its way through this\n\n\n# Let us try to improve the efficiency of this:\n\n# import time\n\n# Note, that time.clock() has since been deprecated, using:\n# t0 = time.process_time()\n# missing_words = find_unknown_words(book_words, book_words)\n# t1 = time.process_time()\n# print(\"There are {0} unknown words.\".format(len(missing_words)))\n# print(\"That took {0:.4f} seconds.\".format(t1-t0))\n# >>> There are 0 unkown words.\n# >>> That took 2.7484 seconds.\n\n# t0 = time.perf_counter()\n# missing_words = find_unknown_words(book_words, book_words)\n# t1 = time.perf_counter()\n# print(\"There are {0} unknown words.\".format(len(missing_words)))\n# print(\"That took {0:.4f} seconds.\".format(t1-t0))\n# >>> There are 0 unkown words.\n# >>> That took 2.7542 seconds.\n\n\n# 14.4) Binary Search\n\n# Lets start with some tests. Remember, the list needs to be sorted:\n\n# xs = [2,3,5,7,11,13,17,23,29,31,37,43,47,53]\n# assert search_binary(xs, 20) == -1\n# assert search_binary(xs, 99) == -1\n# assert search_binary(xs, 1) == -1\n# assert for(i, v) in enumerate(xs):\n# test(search_binary(xs, v) == i)\n\n# It is useful to think about region-of-interest(ROI) with the list being searched.\n# In the tests above, we start our seach within an ROI in the center of the data,\n# this results in three possible outcomes:\n# we found the target\n# we can discard the front half of the data\n# we can discard the second half of the data\n\n# Example Code:\n\ndef search_binary(xs, target):\n \"\"\" Find and return the index of key in sequence xs \"\"\"\n b = 0\n ub = len(xs)\n while True:\n # If search comes up empty:\n if b == ub:\n return -1\n # Probe the middle of the ROI\n mid_index = (b + ub) // 2\n\n # Fetch the item at the position\n item_at_mid = xs[mid_index]\n\n # print(\"ROI[{0}:{1}](size={2}), probed='{3}', target='{4}'\".format(\n # b, ub, ub-b, item_at_mid, target))\n\n # How does the probed item compare to the target?\n if item_at_mid == target:\n return mid_index\n if item_at_mid < target:\n b = mid_index + 1\n else:\n ub = mid_index\n\n\n# def find_unknown_words(vocab, wds):\n# result = []\n# for w in wds:\n# if (search_binary(vocab, w) < 0):\n# result.append(w)\n# return result\n\n\n# xs = [2, 3, 5, 7, 11, 13, 17, 23, 29, 31, 37, 43, 47, 53]\n# assert search_binary(xs, 20) == -1\n# assert search_binary(xs, 99) == -1\n# assert search_binary(xs, 1) == -1\n\n# for(i, v) in enumerate(xs):\n# assert search_binary(xs, v) == i\n\n\n# Substitute a call to this search algorithm instead of calling the\n# search_linear in find_unknown_words\n\n# first linear:\n# t0 = time.perf_counter()\n# missing_words = find_unknown_words(bigger_vocab, book_words)\n# t1 = time.perf_counter()\n# print(\"There are {0} unknown words.\".format(len(missing_words)))\n# print(\"That took {0:.4f} seconds.\".format(t1-t0))\n# returns\n# >>> There are 3396 unknown words.\n# >>> That took 13.4931 seconds.\n\n# with binary search:\n# returns:\n# >>> There are 3396 unknown words.\n# >>> That took 0.0641 seconds.\n\n\n# Formula for how many probes are needed for a list of (N) size:\n# k = [sqrtlog(N+1)]\n\n# or how big of a list we can deal with given (k) amount of probes:\n# N = 2**K - 1\n\n\n# Example: A list has 1000 elements, what is max number of probes needed to do a\n# binary search?\n\n# form math import log, ceil\nprint(ceil(log(1000 + 1, 2)))\n# >>> 10\n# Summation: to find a target in a list of 1000 elements,\n# the max number of probes needed is 10\n\n\n# 14.5 Removing adjacent duplicates from the list\n# One approach: sort the list and remove adjacent duplicates\n\n# remove_adjacent_dups([1,2,3,3,3,5,6,9,9]) == [1,2,3,5,6,9]\n# test(remove_adjacent_dups([]) == [])\n# test(remove_adjacent_dups([\"a\", \"big\", \"big\", \"bite\", \"dog\"]) ==\n# [\"a\", \"big\", \"bite\", \"dog\"])\n\n\ndef remove_adjacent_dups(xs):\n \"\"\"Return a new list in which all adjacent\n ducplicates from xs have been removed.\n \"\"\"\n result = []\n most_recent_elem = None\n for e in xs:\n if e != most_recent_elem:\n result.append(e)\n most_recent_elem = e\n\n return result\n\n\n# Run this on alice.txt\n\n# all_words = get_words_from_book('alice.txt')\n# all_words.sort()\n# book_words = remove_adjacent_dups(all_words)\n# print(\"There are {0} words in the book. Only {1} are unique.\".format(\n# len(all_words), len(book_words)))\n# print(\"The first 100 words are \\n{0}\".format(book_words[:100]))\n\n# >>> There are 27336 words in the book. Only 2569 are unique.\n# >>> The first 100 words are...\n\n\n# 14.6) Merging Sorted Lists\n\n# A simple yet inefficient algorithm:\n# newlist = xs + ys\n# newlist.sort()\n\n# Tests:\nxs = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]\nys = [4, 8, 12, 16, 20, 24]\nzs = xs + ys\nzs.sort()\n\n\ndef merge(xs, ys):\n \"\"\" merge sorted lists xs and ys. Return a sorted result \"\"\"\n result = []\n xi = 0\n yi = 0\n\n# Keep two indexes and whichever item currently indexed is smaller,\n# add that item to the result variable\n while True:\n if xi >= len(xs):\n result.extend(ys[yi:])\n return result\n\n if yi >= len(ys):\n result.extend(xs[xi:])\n return result\n\n # Both lists still have items, copy smaller item to result\n if xs[xi] <= ys[yi]:\n result.append(xs[xi])\n xi += 1\n else:\n result.append(ys[yi])\n yi += 1\n\n\nassert merge(xs, []) == xs\nassert merge([], []) == []\nassert merge(xs, ys) == zs\nassert merge([1, 2, 3], [3, 4, 5]) == [1, 2, 3, 3, 4, 5]\nassert merge(['a', 'big', 'cat'], ['big', 'bite', 'dog']) == [\n 'a', 'big', 'big', 'bite', 'cat', 'dog']\n\n\n# 14.7)\n\n# The pattern for the algorithm to merge sorted lists considers:\n# What should we do when either list has no more items?\n# What should we do if the smallest items from each list are equal to each other?\n# What should we do if the smallest item in the first list is smaller than the smallest one\n# in the second list?\n# What should we do in the remaining case?\n\n\n# Adapt the merge algorithm fo each of these cases:\n\n# 1) Return only those items that are present in both lists\n\n# def merge_common(lst_1, lst_2):\n# result = []\n# for element in lst_1:\n# if element in lst_2:\n# result.append(element)\n# return result\n\n\n# Using list comprehensions:\n# def merge_common(lst_1, lst_2):\n# return [element for element in lst_1 if element in lst_2]\n\n\n# A more pythonic approach:\ndef merge_common(lst_1, lst_2):\n return sorted(list(set(lst_1).intersection(lst_2)))\n\n\nlst1 = [1, 2, 3, 4, 4, 5, 55, 66, 33, 21]\nlst2 = [3, 44, 5, 33, 4]\n\n\nprint(merge_common(lst1, lst2))\n\n\n# 2) Return only those items that are present in the first list, but not in the second\nfirst1 = [0, 1, 1, 2, 3, 4, 5, 7]\nsec2 = [1, 3, 5, 6, 7, 10]\n\n\ndef lst1_unique(xs, ys):\n \"\"\" return a list of items from first and second list that are unique to\n list one\n \"\"\"\n result = []\n xi = 0\n yi = 0\n\n# Keep two indexes and whichever item currently indexed is smaller,\n# add that item to the result variable\n while True:\n if xi >= len(xs):\n return result\n\n if yi >= len(ys):\n result.extend(xs[xi:])\n return result\n\n # Both lists still have items, copy smaller item to result\n # ******Unless for this case, the items are equal*****\n if xs[xi] < ys[yi]:\n result.append(xs[xi])\n xi += 1\n elif xs[xi] == ys[yi]:\n xi += 1\n else:\n yi += 1\n\n\nprint(lst1_unique(first1, sec2))\n\n# 3) Return only those items that are present in the second list, but not in the first\nfirst2 = [0, 1, 1, 2, 3, 4, 5, 7]\nsec3 = [1, 3, 5, 6, 7, 10]\n\n\ndef lst2_unique(xs, ys):\n \"\"\" return a list of items from first and second list that are unique to\n list one\n \"\"\"\n result = []\n xi = 0\n yi = 0\n\n# Keep two indexes and whichever item currently indexed is smaller,\n# add that item to the result variable\n while True:\n if xi >= len(xs):\n result.extend(ys[yi:])\n return result\n\n if yi >= len(ys):\n return result\n\n # Both lists still have items, copy smaller item to result\n # ******Unless for this case, the items are equal*****\n if xs[xi] < ys[yi]:\n xi += 1\n elif xs[xi] == ys[yi]:\n yi += 1\n else:\n result.append(ys[yi])\n yi += 1\n\n\nprint(lst2_unique(first2, sec3))\n\n# 4) Return items that are present in either the first or second list:\n\n\ndef merge_lists(lst_1, lst_2):\n return sorted(list(lst_1)+(lst_2))\n\n\n# print(merge_lists(lst1, lst2))\n\n\n# 5) Return items from the first list that are not eliminated by a matching\n# element in the second list. In this case, an item in the second list \"knocks out\"\n# just one matching item in the first list. This operation is sometimes called bagdiff.\nhome = [5, 7, 11, 11, 11, 12, 13]\naway = [7, 8, 11]\n\n\ndef bagdiff(xs, ys):\n \"\"\" merge sorted lists xs and ys. Return a sorted result \"\"\"\n result = []\n xi = 0\n yi = 0\n\n# Keep two indexes and whichever item currently indexed is smaller,\n# add that item to the result variable\n while True:\n if xi >= len(xs):\n result.extend(ys[yi:])\n return result\n\n if yi >= len(ys):\n result.extend(xs[xi:])\n return result\n\n # Both lists still have items, copy smaller item to result\n # ******Unless for this case, the items are equal*****\n if xs[xi] < ys[yi]:\n result.append(xs[xi])\n xi += 1\n elif xs[xi] > ys[yi]:\n yi += 1\n else:\n xi += 1\n yi += 1\n\n\nprint(bagdiff(home, away))\n\n\n# Use a variant of the merge to return the words that occur in the Alice.txt,\n# but not in the vocabulary.\n\ndef find_unknowns_merge_pattern(vocab, wds):\n \"\"\"Both the vocab and wds must be sorted. Return a new\n list of words from wds that do not occur in vocab.\n \"\"\"\n\n result = []\n xi = 0\n yi = 0\n\n while True:\n if xi >= len(vocab):\n result.extend(wds[yi:])\n return result\n\n if yi >= len(wds):\n return result\n # Good, word exists in vocab\n if vocab[xi] == wds[yi]:\n yi += 1\n # Move past this vocab word\n elif vocab[xi] < wds[yi]:\n xi += 1\n else:\n result.append(wds[yi])\n yi += 1\n\n\nall_words = get_words_from_book('Alice.txt')\nt0 = time.perf_counter()\nall_words.sort()\nbook_words = remove_adjacent_dups(all_words)\nmissing_words = find_unknowns_merge_pattern(bigger_vocab, book_words)\nt1 = time.perf_counter()\nprint('There are {0} unknown words'.format(len(missing_words)))\nprint('That took {0:.4f} seconds'.format(t1-t0))\n\n\n# >>> There are 827 unknown words\n# >>> That took 0.0149 seconds\n\n\n# 14.8) Eight Queens puzzle, pt.1\n\n# Check if Queens share a diagonal:\n# share_diagonal(5,2,2,0)\n\n# def share_diagonal(x0, y0, x1, y1):\n# \"\"\"Is (x0, y0) on a shared diagonal with (x1, y1)?\"\"\"\n# dy = abs(y1 - y0)\n# dx = abs(x1 - x0)\n# # they clash if dx == dy\n# return dx == dy\n\n\n# def col_clashes(bs, c):\n# \"\"\" Return True if the queen at column c clashes with any queen to its left\"\"\"\n# for i in range(c):\n# if share_diagonal(i, bs[i], c, bs[c]):\n# return True\n# # No clashes - col c has a safe placement\n# return False\n\n\n# def has_clashes(the_board):\n# \"\"\" Determine whether we have any queens clashing on the diagonals\n# We're assuming here that the_board is a permutation of column\n# numbers, so we're not explicitly checking row or\n# column clashes\n# \"\"\"\n# for col in range(1, len(the_board)):\n# if col_clashes(the_board, col):\n# return True\n# return False\n\n# # Because of the many ways of choosing 8 squares of a 64 square game board,\n# # we will use permutatuions.\n\n# # We'll try a random shuffle of the permutation [0,1,2,3,4,5,6,7]\n\n\n# def main():\n# import random\n# # import random\n# rng = random.Random()\n\n# # generate the initial permutation\n# bd = list(range(8))\n# num_found = 0\n# tries = 0\n# while num_found < 10:\n# rng.shuffle(bd)\n# tries += 1\n# if not has_clashes(bd):\n# print(\"Found solution {0} in {1} tries.\".format(bd, tries))\n# tries = 0\n# num_found += 1\n\n\n# main()\n\n\n# Here is an interesting fact. On an 8x8 board, there are known to be\n# 92 different solutions to this puzzle. We are randomly picking one\n# of 40320 possible permutations of our representation. So our chances\n# of picking a solution on each try are 92/40320. Put another way, on\n# average we\u2019ll need 40320/92 tries \u2014 about 438.26 \u2014 before we stumble\n# across a solution. The number of tries we printed looks like our experimental\n# data agrees quite nicely with our theory!\n\n\n# 14.11) Exercises:\n\n# 1) Alice in Wonderland Merge\n# See above\n\n\n# 2) Modify the queens program to solve some boards of size 4, 12, and 16.\n# What is the maximum size puzzle you can usually solve in under a minute?\n\n# def share_diagonal(x0, y0, x1, y1):\n# \"\"\"Is (x0, y0) on a shared diagonal with (x1, y1)?\"\"\"\n# dy = abs(y1 - y0)\n# dx = abs(x1 - x0)\n# # they clash if dx == dy\n# return dx == dy\n\n\n# def col_clashes(bs, c):\n# \"\"\" Return True if the queen at column c clashes with any queen to its left\"\"\"\n# for i in range(c):\n# if share_diagonal(i, bs[i], c, bs[c]):\n# return True\n# # No clashes - col c has a safe placement\n# return False\n\n\n# def has_clashes(the_board):\n# \"\"\" Determine whether we have any queens clashing on the diagonals\n# We're assuming here that the_board is a permutation of column\n# numbers, so we're not explicitly checking row or\n# column clashes\n# \"\"\"\n# for col in range(1, len(the_board)):\n# if col_clashes(the_board, col):\n# return True\n# return False\n\n# # Because of the many ways of choosing 8 squares of a 64 square game board,\n# # we will use permutatuions.\n\n# # We'll try a random shuffle of the permutation [0,1,2,3,4,5,6,7]\n\n\n# def main():\n# import random\n# # import random\n# rng = random.Random()\n\n# # generate the initial permutation\n# bd = list(range(16))\n# num_found = 0\n# tries = 0\n# t0 = time.perf_counter()\n# while num_found < 10:\n# rng.shuffle(bd)\n# tries += 1\n# if not has_clashes(bd):\n# print(\"Found solution {0} in {1} tries.\".format(bd, tries))\n# tries = 0\n# num_found += 1\n# t1 = time.perf_counter()\n# print(t1 - t0)\n\n\n# main()\n\n\n# Board size of Four:\n# Found solution [1, 3, 0, 2] in 1 tries.\n# Found solution [2, 0, 3, 1] in 5 tries.\n# Found solution [1, 3, 0, 2] in 10 tries.\n# Found solution [1, 3, 0, 2] in 2 tries.\n# Found solution [1, 3, 0, 2] in 26 tries.\n# Found solution [2, 0, 3, 1] in 5 tries.\n# Found solution [2, 0, 3, 1] in 9 tries.\n# Found solution [2, 0, 3, 1] in 13 tries.\n# Found solution [2, 0, 3, 1] in 8 tries.\n# Found solution [1, 3, 0, 2] in 10 tries.\n# 0.0003903910000000038\n\n# Board size of 12:\n# Found solution [3, 10, 4, 7, 11, 0, 6, 1, 9, 5, 8, 2] in 127616 tries.\n# Found solution [8, 5, 9, 1, 6, 11, 3, 0, 7, 10, 4, 2] in 25748 tries.\n# Found solution [4, 1, 8, 11, 7, 3, 0, 9, 5, 10, 2, 6] in 21588 tries.\n# Found solution [8, 5, 3, 0, 6, 11, 1, 10, 7, 2, 4, 9] in 169467 tries.\n# Found solution [3, 9, 6, 8, 10, 2, 0, 5, 1, 4, 11, 7] in 49349 tries.\n# Found solution [4, 6, 1, 10, 5, 7, 9, 3, 0, 2, 8, 11] in 13077 tries.\n# Found solution [7, 1, 6, 9, 0, 8, 11, 4, 2, 10, 5, 3] in 51184 tries.\n# Found solution [6, 8, 3, 11, 9, 2, 5, 1, 10, 7, 0, 4] in 88882 tries.\n# Found solution [3, 7, 9, 2, 0, 5, 10, 8, 1, 11, 4, 6] in 2092 tries.\n# Found solution [3, 10, 7, 2, 6, 11, 1, 5, 0, 9, 4, 8] in 6695 tries.\n# 3.950741986\n\n# Board size of 16:\n# Found solution [7, 9, 12, 0, 13, 3, 10, 8, 1, 4, 2, 11, 6, 15, 5, 14] in 1377112 tries.\n# Found solution [14, 12, 3, 8, 6, 2, 9, 1, 4, 0, 10, 15, 5, 11, 13, 7] in 187288 tries.\n# Found solution [11, 5, 8, 4, 0, 12, 15, 7, 10, 6, 2, 14, 1, 3, 9, 13] in 761302 tries.\n# Found solution [11, 7, 0, 6, 13, 9, 1, 15, 10, 14, 2, 4, 8, 3, 5, 12] in 2537199 tries.\n# Found solution [7, 10, 3, 6, 12, 5, 0, 11, 4, 15, 9, 2, 14, 8, 1, 13] in 369347 tries.\n# Found solution [1, 8, 13, 3, 10, 15, 4, 11, 0, 2, 7, 5, 14, 12, 9, 6] in 1227528 tries.\n# Found solution [7, 14, 10, 15, 6, 1, 11, 2, 0, 13, 4, 9, 12, 3, 5, 8] in 219311 tries.\n# Found solution [8, 3, 0, 6, 15, 12, 7, 11, 2, 14, 1, 4, 9, 13, 10, 5] in 1888880 tries.\n# Found solution [12, 5, 9, 11, 13, 8, 3, 0, 2, 15, 10, 7, 4, 14, 1, 6] in 2778809 tries.\n# Found solution [7, 0, 6, 14, 12, 15, 9, 5, 1, 4, 11, 13, 2, 10, 8, 3] in 1009425 tries.\n# 103.54650013000001\n\n\n# 3) Adapt the queen program so that we keep a list of solutions that have already\n# printed, so we don't print the same solution more than once:\n# Add empty list, set to variable solutions\n# At the end of main function, solutions.append(list(bd))\n# Add this line in main: if not has_clashes(bd) and bd not in solutions:\n\n\n# def share_diagonal(x0, y0, x1, y1):\n# \"\"\"Is (x0, y0) on a shared diagonal with (x1, y1)?\"\"\"\n# dy = abs(y1 - y0)\n# dx = abs(x1 - x0)\n# # they clash if dx == dy\n# return dx == dy\n\n\n# def col_clashes(bs, c):\n# \"\"\" Return True if the queen at column c clashes with any queen to its left\"\"\"\n# for i in range(c):\n# if share_diagonal(i, bs[i], c, bs[c]):\n# return True\n# # No clashes - col c has a safe placement\n# return False\n\n\n# def has_clashes(the_board):\n# \"\"\" Determine whether we have any queens clashing on the diagonals\n# We're assuming here that the_board is a permutation of column\n# numbers, so we're not explicitly checking row or\n# column clashes\n# \"\"\"\n# for col in range(1, len(the_board)):\n# if col_clashes(the_board, col):\n# return True\n# return False\n\n# # Because of the many ways of choosing 8 squares of a 64 square game board,\n# # we will use permutatuions.\n\n# # We'll try a random shuffle of the permutation [0,1,2,3,4,5,6,7]\n\n\n# def main():\n# import random\n# # import random\n# rng = random.Random()\n# solutions = []\n# # generate the initial permutation\n# bd = list(range(4))\n# num_found = 0\n# tries = 0\n# t0 = time.perf_counter()\n# while num_found < 10:\n# rng.shuffle(bd)\n# tries += 1\n# if not has_clashes(bd) and bd not in solutions:\n# print(\"Found solution {0} in {1} tries.\".format(bd, tries))\n# solutions.append(list(bd))\n# tries = 0\n# num_found += 1\n# t1 = time.perf_counter()\n# print(t1 - t0)\n\n\n# main()\n\n\n# 4) Chess boards are symmetric: if we have a solution to the queens problem,\n# its mirror solution \u2014 either flipping the board on the X or in the Y axis,\n# is also a solution. And giving the board a 90 degree, 180 degree, or 270 degree\n# rotation is also a solution. In some sense, solutions that are just mirror images\n# or rotations of other solutions \u2014 in the same family \u2014 are less interesting than\n# the unique \u201ccore cases\u201d. Of the 92 solutions for the 8 queens problem, there are\n# only 12 unique families if you take rotations and mirror images into account.\n# Wikipedia has some fascinating stuff about this.\n\n# a)Write a function to mirror a solution in the Y axis,\n\n\n# b) Write a function to mirror a solution in the X axis,\n\n# c) Write a function to rotate a solution by 90 degrees anti-clockwise,\n# and use this to provide 180 and 270 degree rotations too.\n\n# d) Write a function which is given a solution, and it generates the\n# family of symmetries for that solution. For example, the symmetries of\n\n# e) Now adapt the queens program so it won\u2019t list solutions that are in the same family.\n# It only prints solutions from unique families.\n\n# def share_diagonal(x0, y0, x1, y1):\n# \"\"\"Is (x0, y0) on a shared diagonal with (x1, y1)?\"\"\"\n# dy = abs(y1 - y0)\n# dx = abs(x1 - x0)\n# # they clash if dx == dy\n# return dx == dy\n\n\n# def col_clashes(bs, c):\n# \"\"\" Return True if the queen at column c clashes with any queen to its left\"\"\"\n# for i in range(c):\n# if share_diagonal(i, bs[i], c, bs[c]):\n# return True\n# # No clashes - col c has a safe placement\n# return False\n\n\n# def has_clashes(the_board):\n# \"\"\" Determine whether we have any queens clashing on the diagonals\n# We're assuming here that the_board is a permutation of column\n# numbers, so we're not explicitly checking row or\n# column clashes\n# \"\"\"\n# for col in range(1, len(the_board)):\n# if col_clashes(the_board, col):\n# return True\n# return False\n\n# # Because of the many ways of choosing 8 squares of a 64 square game board,\n# # we will use permutatuions.\n\n# # We'll try a random shuffle of the permutation [0,1,2,3,4,5,6,7]\n\n\n# def main():\n# import random\n# # import random\n# rng = random.Random()\n# solutions = []\n# # generate the initial permutation\n# bd = list(range(4))\n# num_found = 0\n# tries = 0\n# t0 = time.perf_counter()\n# while num_found < 10:\n# rng.shuffle(bd)\n# tries += 1\n# if not has_clashes(bd):\n# # if not has_clashes(bd) and bd not in solutions:\n# print(\"Found solution {0} in {1} tries.\".format(bd, tries))\n# solutions.append(list(bd))\n# tries = 0\n# num_found += 1\n# t1 = time.perf_counter()\n# print(t1 - t0)\n\n\n# main()\n\n\n# Every week a computer scientist buys four lotto tickets.\n# She always chooses the same prime numbers, with the hope that\n# if she ever hits the jackpot, she will be able to go onto TV and\n# Facebook and tell everyone her secret. This will suddenly create\n# widespread public interest in prime numbers, and will be the trigger\n# event that ushers in a new age of enlightenment. She represents her weekly\n# tickets in Python as a list of lists:\n\n# my_tickets = [ [ 7, 17, 37, 19, 23, 43],\n# [ 7, 2, 13, 41, 31, 43],\n# [ 2, 5, 7, 11, 13, 17],\n# [13, 17, 37, 19, 23, 43] ]\n\n# Complete these exercises.\n\n# a) Each lotto draw takes six random balls, numbered from 1 to 49.\n# Write a function to return a lotto draw.\n# (I used the random.sample() function which returns k length of unique elements\n# chosen from the population sequence.)\n\ndef lotto_draw():\n import random\n winner = sorted(random.sample(range(1, 50), 6))\n print(winner)\n return winner\n\n# lotto_draw()\n\n# b) Write a function that compares a single ticket and a draw,\n# and returns the number of correct picks on that ticket:\n\n\ndef buy_lotto_ticket():\n import random\n number_of_tix = int(input('how many tickets would you like to buy?'))\n print_out = []\n draw = sorted(random.sample(range(1, 50), 6))\n for tix in range(number_of_tix):\n draw = sorted(random.sample(range(1, 50), 6))\n print_out.append(draw)\n print(print_out)\n return draw\n\n\n# buy_lotto_ticket()\n\n\ndef did_you_win():\n import random\n winner = sorted(random.sample(range(1, 50), 6))\n print(winner)\n number_of_tix = int(input('how many tickets would you like to buy?'))\n print_out = []\n for items in range(number_of_tix):\n draw = sorted(random.sample(range(1, 50), 6))\n print_out.append(draw)\n for tix in print_out:\n if tix == winner:\n print('you Won!')\n print(tix, '->', winner)\n print('Sorry, no matches', print_out, winner)\n\n\n# did_you_win()\n\n\n# c.) Write a function that takes a list of tickets and a draw,\n# and returns a list telling how many picks were correct on each ticket\n\ndef lucky_nums():\n import random\n\n winner = sorted(random.sample(range(1, 50), 6))\n # print(winner)\n number_of_tix = int(input('how many tickets would you like to buy?'))\n print_out = []\n for items in range(number_of_tix):\n draw = sorted(random.sample(range(1, 50), 6))\n print_out.append(draw)\n\n chosen = [list(set(num).intersection(winner)) for num in print_out]\n\n count = 0\n\n for lst in chosen:\n for num in lst:\n if num > 0:\n count += 1\n\n print(print_out, winner)\n print(chosen)\n print(f'{count} or your numbers/number matched winning numbers')\n\n\n# lucky_nums()\n\n# d.) Write a function that takes a list of integers, and returns the number of primes in the list:\n\n\ndef isPrime(numlist):\n primes = []\n\n for num in numlist:\n numIsPrime = True\n if num > 1:\n for i in range(2, num):\n if num % i == 0:\n numIsPrime = False\n\n if numIsPrime == True:\n primes.append(num)\n return primes\n\n\nprint(isPrime([2, 3, 4, 5, 7, 11]))\nassert isPrime([42, 4, 7, 11, 1, 13]) == [7, 11, 13]\n\n\n# e). Write a function to discover whether the computer scientist has missed any\n# prime numbers in her selection of the four tickets. Return a list of all primes that she has missed:\n\n\n# f). Write a function that repeatedly makes a new draw, and compares the draw to the four tickets.\n\n# 1) Count how many draws are needed until one of the computer scientist\u2019s tickets\n# has at least 3 correct picks. Try the experiment twenty times, and average out the\n# number of draws needed.\n\n# 2) How many draws are needed, on average, before she gets at least 4 picks correct?\n\n# 3) How many draws are needed, on average, before she gets at least 5 correct?\n# (Hint: this might take a while. It would be nice if you could print some dots,\n# like a progress bar, to show when each of the 20 experiments has completed.)\n"} {"blob_id": "4b0da2c6d531879f4556c2f0095dba58ae6b1473", "repo_name": "ashish3x3/competitive-programming-python", "path": "/Hackerrank/Maths/finding_time_for_area_overlaping_of_squares.py", "length_bytes": 1527, "score": 3.671875, "int_score": 4, "content": "# https://www.hackerrank.com/challenges/sherlock-and-moving-tiles\n\n'''\nSherlock is given square tiles, initially both of whose sides have length placed in an plane; so that the bottom left corner of each square coincides with the the origin and their sides are parallel to the axes.\n\nAt , both squares start moving along line (along the positive and ) with velocities and .\n\nFor each query of form , Sherlock has to report the time at which the overlapping area of tiles is equal to qi.\n\nNote: Assume all distances in meter, time in seconds and velocities in meter per second unless otherwise specified.\n\nInput Format \nFirst line contains integers . Next line contains , the number of queries. Each of the next lines consists of one integer in one line.\n\nConstraints \n \n \n \n\nOutput Format \nFor each query, print the required answer in one line. Your answer will be considered correct if it is at most away from the true answer. See the explanation for more details.\n\nSample Input\n\n10 1 2\n2\n50\n100\nSample Output\n\n4.1421\n0.0000\nExplanation\n\nFor the first case, note that the answer is around 4.1421356237..., so any of the following will be accepted:\n\n4.1421356237\n4.14214\n4.14215000\n4.1421\n4.1422\n\n'''\n\n# Enter your code here. Read input from STDIN. Print output to STDOUT\nimport sys \nimport math\npar = [int(i) for i in raw_input().strip().split(' ')] \nQ = int(input())\nfor j in range(0,Q): \n Aq = int(raw_input()) \n t = float((math.sqrt(2)*(par[0]-math.sqrt(Aq)))/(abs(par[1]-par[2])))\n print format(t, '.20f')"} {"blob_id": "7795889d4a4376cc44bd752e26301316db1a131d", "repo_name": "mastercsay2511/100daysofcodewithGFG", "path": "/Day 10 - 19/12 - Day/main.py", "length_bytes": 1736, "score": 3.546875, "int_score": 4, "content": "#User function Template for python3\nclass Solution:\n\n\t\n\tdef search(self,pat, txt):\n # code here\n l_txt=len(txt)\n p_txt=len(pat)\n dicti={}\n for i in pat:\n dicti[i]=dicti.get(i,0)+1\n i=0\n j=0\n count=len(dicti)\n ans=0\n length=0\n # for i in range(0,l_txt+1):\n while(i 0:\n txt=input().strip()\n pat=input().strip()\n ob = Solution()\n ans = ob.search(pat, txt)\n print(ans)\n tc=tc-1\n# } Driver Code Ends\n"} {"blob_id": "ae20390b3ae612b1574150241a68154dd9837436", "repo_name": "jaecheolkim99/CodingPlayground", "path": "/LeetCode/Sequential Digits.py", "length_bytes": 1040, "score": 3.953125, "int_score": 4, "content": "\"\"\"\nAn integer has sequential digits if and only if each digit in the number is one more than the previous digit.\n\nReturn a sorted list of all the integers in the range [low, high] inclusive that have sequential digits.\n\nExample\nInput: low = 1000, high = 13000\nOutput: [1234,2345,3456,4567,5678,6789,12345] \n\"\"\"\n\nclass Solution(object):\n def sequentialDigits(self, low, high):\n \"\"\"\n :type low: int\n :type high: int\n :rtype: List[int]\n \"\"\"\n \n result = []\n candidate = 12\n digit = 2\n inc = 11\n \n while (candidate < high):\n check = candidate;\n \n for i in range(9-digit+1):\n if check > high:\n return result\n if check >= low and check <= high:\n result.append(check) \n check += inc\n \n digit += 1\n candidate = candidate*10 + digit\n inc = inc * 10 + 1\n \n return result"} {"blob_id": "9dedc34f1664dd7a84dee463a074cd9b19e59495", "repo_name": "AG-Systems/programming-problems", "path": "/Leetcode/Smallest-String-Starting-From-Leaf.py", "length_bytes": 793, "score": 3.71875, "int_score": 4, "content": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def smallestFromLeaf(self, root: TreeNode) -> str:\n if root == None:\n return \"\"\n \n self.smallest_string = \"~\"\n \n def dfs(root, new_str):\n if root:\n new_str.append(chr(root.val + ord('a')))\n \n if root.left == None and root.right == None:\n self.smallest_string = min(self.smallest_string, \"\".join(new_str[::-1]))\n dfs(root.left, new_str)\n dfs(root.right, new_str)\n new_str.pop()\n \n dfs(root, [])\n return self.smallest_string\n"} {"blob_id": "2717620ed19e94a1a38ab4588cc7dc8072ea9fb7", "repo_name": "lilweege/dmoj-solutions", "path": "/ccc20s2.py", "length_bytes": 2435, "score": 3.765625, "int_score": 4, "content": "'''\nLuigi Quattrociocchi\nWaterloo CCC 2020 J5/S2: Escape room\nBFS Solution 11/15 points\n'''\n\n# using math sqrt for (fast factor)\nimport math\n# fast input\nimport sys\nm = int(sys.stdin.readline())\nn = int(sys.stdin.readline())\n\n# method for finding factors and then coordinates\n# although more efficient methods exist (look into Sieve of Eratosthenes)\ndef findCoords(v):\n\t# initialize list of coordinate (factor pairs)\n\tf = []\n\t# check all numbers less than sqrt of value\n\t# any number beyond that will already be known\n\tfor i in range(1, int(math.sqrt(v))+1):\n\t\t# is it a factor?\n\t\tif v%i == 0:\n\t\t\t# the reciprocal of i will be the corresponding factor\n\t\t\tj = int(v/i)\n\n\t\t\t# both factors are added at once\n\t\t\t# since multiplation is commutative\n\n\t\t\t# are factor pairs within bounds of grid\n\t\t\tif j <= m and i <= n:\n\t\t\t\tf.append((j, i))\n\t\t\tif i <= m and j <= n:\n\t\t\t\tf.append((i, j))\n\n\t# return array of coordinates\n\treturn f\n\n\n# initialize grid with input values\n# grid is row by col (y, x)\ngrid = [[int(elm) for elm in sys.stdin.readline().split()] for _ in range(m)]\n\n# boolean array, has current cell been visited\nvisited = [[False for _ in range(n)] for _ in range(m)]\n\n# initially, we don't know if it's possible to escape\n# since we are trying to prove that it is possible, we say False\n# if no valid path is found this boolean will not be changed\npossible = False\n\n# since grid is in terms of rows and cols,\n# tuples will be in terms (y, x).\n# start at position (1, 1) as specified\nstart = (1, 1)\n\n# as stated by the question,\n# the end or final position will be (m, n)\nend = (m, n)\n\n# queue will only contain the root note to begin\n# other ways of doing queues in python exist\n# for example: from collections import deque\nq = [start]\n\n# while length of queue > 0\n# AKA \"while q (exists)\"\nwhile q:\n\t# pop will remove the first value from queue (since BFS is FiFo)\n\t# current cell becomes the popped value\n\tcur = q.pop(0)\n\ty, x = cur[0]-1, cur[1]-1\n\n\t# has the current cell been visited yet?\n\tif visited[y][x]:\n\t\t# if so, skip the check for this cell\n\t\tcontinue\n\n\t# mark current cell as visited\n\tvisited[y][x] = True\n\n\t# if current cell is the final spot\n\tif cur == end:\n\t\t# path is possible\n\t\tpossible = True\n\t\t# break out of loop\n\t\tbreak\n\n\t# call method on current value, find all possible moves\n\t# add all possible moves (coords to jump to) to queue\n\tq.extend(findCoords(grid[y][x]))\n\n# output final answer\nprint(\"yes\" if possible else \"no\")\n"} {"blob_id": "af4bb3abc07d1b4d88d863164ca1d052e4e8e867", "repo_name": "sky-dream/LeetCodeProblemsStudy", "path": "/[1218][Medium][Longest_Arithmetic_Subsequence_of_Given_Difference]/Longest_Arithmetic_Subsequence_of_Given_Difference.py", "length_bytes": 863, "score": 3.578125, "int_score": 4, "content": "# leetcode time cost : 796 ms\n# leetcode memory cost : 27.2 MB \nfrom collections import defaultdict\nclass Solution:\n #def longestSubsequence(self, arr: List[int], difference: int) -> int:\n def longestSubsequence(self, arr, difference):\n # length_dict key is the value in the array, dict value is the subqueue length that include the current value in the array\n length_dict = defaultdict(int)\n result = 0\n for value in arr:\n length_dict[value] = length_dict[value - difference] + 1 \n result = max (result , length_dict[value] )\n return result\n \ndef main():\n arr, difference = [1,5,7,8,5,3,4,2,1], -2 # Example 3, expect is 4\n obj = Solution()\n result = obj.longestSubsequence(arr, difference)\n print(\"return result is :\",result)\n \nif __name__ =='__main__':\n main() "} {"blob_id": "5a658c503e98c4e3eb7637bfe4c23bf045e1ec77", "repo_name": "lilo907/Euler", "path": "/pythaTriplet.py", "length_bytes": 724, "score": 4.03125, "int_score": 4, "content": "# A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,\r\n#\r\n# a2 + b2 = c2\r\n# For example, 32 + 42 = 9 + 16 = 25 = 52.\r\n#\r\n# There exists exactly one Pythagorean triplet for which a + b + c = 1000.\r\n# Find the product abc.\r\n\r\n\r\ndef isLessThan(a, b, c):\r\n if a < b < c:\r\n return True\r\n\r\n\r\ndef pyTheorem(a, b, c):\r\n if isLessThan(a, b, c):\r\n if a ** 2 + b ** 2 == c ** 2:\r\n return True\r\n\r\n\r\nfor z in range(0, 1000):\r\n for y in range(0, z):\r\n for x in range(0, y):\r\n if isLessThan(x, y, z) and x + y + z == 1000:\r\n if pyTheorem(x, y, z):\r\n print(x)\r\n print(y)\r\n print(z)\r\n\r\n\r\n\r\n"} {"blob_id": "74812b55dc391668b845b330f366681c45d439ed", "repo_name": "huangjenny/wallbreakers", "path": "/week4/combination_sum.py", "length_bytes": 1206, "score": 3.671875, "int_score": 4, "content": "# Jenny Huang\n# Wallbreakers Cohort #3\n# Week 4\n# Combination Sum\n# https://leetcode.com/problems/combination-sum/\n\nclass Solution(object):\n def combinationSum(self, candidates, target):\n \"\"\"\n :type candidates: List[int]\n :type target: int\n :rtype: List[List[int]]\n \"\"\"\n if not candidates:\n return []\n \n output = []\n candidates.sort()\n \n backtracking(self, 0, output, [], 0, candidates, target)\n return output\n \ndef backtracking(self, start, output, subset, total, candidates, target):\n if start >= len(candidates):\n return\n \n # loop through array\n for i in range(start, len(candidates)):\n # check if sum = target\n if candidates[i] + total == target:\n # combine subset and candidates[i] and append to output\n output.append(subset + [candidates[i]])\n return\n # sum > target\n elif candidates[i] + total > target:\n return\n # recurse\n else:\n # start = i to look at candidates[start:]\n backtracking(self, i, output, subset + [candidates[i]], total + candidates[i], candidates, target)"} {"blob_id": "11b24d547c9019cbfa8504ea113f04a75b8df5fa", "repo_name": "Roasbeef/Project-Euler-Solutions-", "path": "/1-10/p_9.py", "length_bytes": 363, "score": 3.84375, "int_score": 4, "content": "'''\nThere exists exactly one Pythagorean triplet\nfor which a + b + c = 1000.\nFind the product abc.\n'''\n\nanswer = [(a * b * c) for c in xrange(505, 0, -1)\n for a in xrange(c, 0, -1)\n for b in xrange(a, 0, -1)\n if a + b + c == 1000\n and a ** 2 + b ** 2 == c ** 2][0]\n\nprint answer\n"} {"blob_id": "fcd5907b1cf93df51db8f5acb5dd4a9a2c8d79b9", "repo_name": "itar3/shortest_path", "path": "/as.py", "length_bytes": 7774, "score": 4.1875, "int_score": 4, "content": "##############################################Help classes#########################################################\n\n#class used in task3 during backtracking in order to reverse list in O(n) times\n#where n is number of items in stack\nclass Stack:\n def __init__(self):\n\n self.count = 0\n self.top = -1\n self.array = []\n\n def is_full(self):\n return self.count >= len(self.array)\n\n def is_empty(self):\n return self.count == 0\n\n def push(self, item):\n self.top += 1\n self.array.append(item)\n self.count += 1\n\n def pop(self):\n if self.is_empty():\n raise Exception(\"stack is empty\")\n tobereturn = self.array[self.top]\n self.top -= 1\n self.count -= 1\n return tobereturn\n\n def __len__(self):\n return self.count\n\n#class node needed for class queue for task 2\nclass Node:\n def __init__(self,item,next):\n self.item = item\n self.next = next\n\n#class that represents linked queue for task 2\nclass Queue:\n def __init__(self):\n self.rear = None\n self.front = None\n self.count = 0\n\n def is_empty(self):\n return self.count == 0\n\n def append(self, item):\n new_node = Node(item, None)\n\n if self.is_empty():\n self.front = new_node\n else:\n self.rear.next = new_node\n self.rear = new_node\n\n self.count+=1\n\n # function to perform pop action (get rid of item in front)\n # takes O(1) time\n def serve(self):\n if self.is_empty():\n raise IndexError(\"queue is empty\")\n item = self.front.item\n self.front = self.front.next\n if self.is_empty():\n self.rear = None\n self.count -=1\n return item\n\n#Min heap used to optimize Dijkstra\nclass Heap:\n def __init__(self,size= 100):\n self.count = 0\n self.array = [None] * size\n\n def is_empty(self):\n return self.count == 0\n\n def add(self, item):\n if self.count + 1 < len(self.array):\n self.array[self.count + 1] = item\n else:\n raise Exception(\"Heap is full\")\n self.count += 1\n self.rise(self.count)\n\n\n def swap(self, i, j):\n self.array[i], self.array[j] = self.array[j], self.array[i]\n\n def rise(self, node):\n while node > 1 and self.array[node][1] < self.array[node // 2][1]:\n self.swap(node // 2, node)\n node = node // 2\n\n\n def sink(self, node):\n while node * 2 <= self.count:\n child = self._get_smallest_child(node)\n if self.array[child][1] > self.array[node][1]:\n break\n self.swap(node, child)\n node = child\n\n\n def _get_smallest_child(self, node):\n if node * 2 == self.count or self.array[node * 2][1] < self.array[2 * node + 1][1]:\n return 2 * node\n else:\n return 2 * node + 1\n\n def update(self, vertex, new_distance):\n for i in range(1, len(self.array)):\n if self.array[i] == vertex:\n self.array[i][1] = new_distance\n\n def pop(self):\n retval = self.array[1]\n self.swap(1, self.count)\n self.count -= 1\n self.sink(1)\n\n return retval\n\n#######################################################Assignment classes#################################################################\n\nclass Vertex:\n def __init__(self, id):\n self.id = id\n self.edges = []\n\n def add_edge(self, edge):\n self.edges.append(edge)\n\nclass Edge:\n def __init__(self, u, v, w = 0):\n self.u = u\n self.v = v\n self.w = w\n\nclass Graph:\n def __init__(self, gfile):\n self.vertices = []\n self.read_file(gfile)\n self.max_distances = []\n\n def get_vertex(self, vertex):\n return self.vertices[vertex]\n\n def add_edge(self,u,v, w):\n vertex_u = self.get_vertex(u)\n vertex_v = self.get_vertex(v)\n\n edge = Edge(vertex_u, vertex_v, w)\n vertex_u.add_edge(edge)\n\n #since the graph is undirected, meaning every edge goes both ways\n #therefore we add edge back to every given edge\n edge = Edge(vertex_v,vertex_u, w)\n vertex_v.add_edge(edge)\n\n def read_file(self, gfile):\n file = open(gfile, 'r')\n list = []\n for line in file:\n line = line.split()\n list.append(line)\n\n self.size = int(list[0][0])\n for i in range(self.size):\n v = Vertex(i)\n self.vertices.append(v)\n\n for i in range(1, len(list)):\n vertex_u = int(list[i][0])\n vertex_v = int(list[i][1])\n w = int(list[i][2])\n\n self.add_edge(vertex_u, vertex_v, w)\n\n\n def shallowest_spanning_tree(self):\n min_id = 0\n for i in range(self.size):\n self.bfs(i)\n if len(self.max_distances) > 1 and self.max_distances[i][1] < self.max_distances[min_id][1]:\n min_id = i\n\n\n return self.max_distances[min_id][0], self.max_distances[min_id][1]\n\n def bfs(self, s):\n s = self.get_vertex(s)\n distance = [-1] * self.size\n distance[s.id] = 0\n max_distance = 0\n queue = Queue()\n queue.append(s)\n\n while not queue.is_empty():\n u = queue.serve()\n for e in u.edges:\n if distance[e.v.id] == -1:\n distance[e.v.id] = distance[e.u.id] + 1\n if distance[e.u.id] + 1 > max_distance:\n max_distance = distance[e.u.id] + 1\n\n queue.append(e.v)\n\n self.max_distances.append((s.id, max_distance))\n\n\n def dijkstra(self, s):\n s = self.get_vertex(s)\n distance = [9999999] * self.size\n previous = [None] * self.size\n distance[s.id] = 0\n queue = Heap(self.size)\n queue.add([s, 0])\n while not queue.is_empty():\n u = queue.pop()\n key = u[1]\n u = u[0]\n if distance[u.id] <= key:\n for e in u.edges:\n if distance[e.v.id] > distance[e.u.id] + e.w:\n distance[e.v.id] = distance[u.id] + e.w\n previous[e.v.id] = e.u.id\n queue.add([e.v, distance[e.v.id]])\n\n\n return distance, previous\n\n\n def backtrack(self, previous, home, start, final_path, total_distance):\n p = Stack()\n while start != home:\n p.push(start)\n start = previous[start]\n\n while not p.is_empty():\n final_path.append(p.pop())\n total_distance +=1\n\n\n return final_path, total_distance\n\n\n def shortest_errands(self, home, destination, ice_locs, ice_cream_locs):\n distance, previous = self.dijkstra(home)\n total_distance = 0\n final_path = []\n\n final_path.append(home)\n\n d = distance[ice_locs[0]]\n ci = ice_locs[0]\n for i in ice_locs:\n if distance[i] < d:\n d = distance[i]\n ci = i\n final_path, total_distance = self.backtrack(previous, home, ci, final_path, total_distance)\n\n distance, previous = self.dijkstra(ci)\n\n d = distance[ice_cream_locs[0]]\n cic = ice_cream_locs[0]\n for i in ice_cream_locs:\n if distance[i] < d:\n d = distance[i]\n cic = i\n final_path, total_distance = self.backtrack(previous, ci, cic, final_path, total_distance)\n\n distance, previous = self.dijkstra(cic)\n final_path,total_distance = self.backtrack(previous, cic, destination, final_path, total_distance)\n\n return total_distance, final_path\n\n\nz = Graph('test1')\n\nprint(z.dijkstra(1))"} {"blob_id": "b3f42c6b9d0dfeb2b2b8b4a5bc208a5eeb7e015c", "repo_name": "doubleduck98/uni", "path": "/python/lista3/zad3.py", "length_bytes": 309, "score": 3.734375, "int_score": 4, "content": "acc = {}\n\n \ndef sudan(n, x, y):\n if (n, x, y) in acc:\n return acc[(n, x, y)]\n elif n == 0:\n return x + y\n elif y == 0:\n return x\n else:\n acc[(n, x, y)] = sudan(n - 1, sudan(n, x, y - 1), sudan(n, x, y - 1) + y)\n return acc[(n, x, y)]\n\n\nprint(sudan(1, 4, 14))\n"} {"blob_id": "98f3afee231f32c39e2e20aa12c06b6634a00e73", "repo_name": "nascarsayan/lintcode", "path": "/107.py", "length_bytes": 2343, "score": 3.546875, "int_score": 4, "content": "class Solution:\n \"\"\"\n @param: s: A string\n @param: dic: A dictionary of words dict\n @return: A boolean\n \"\"\"\n\n def wordBreak(self, s, dic):\n # write your code here\n ls = len(s)\n c = 0\n dp = [False] * ls + [True]\n matched = []\n for st in range(ls - 1, -1, -1):\n if s[st:] in dic:\n dp[st] = True\n matched.insert(0, st)\n continue\n for fl in matched:\n c += 1\n if s[st:fl] in dic:\n dp[st] = True\n matched.insert(0, st)\n break\n print(c)\n return dp[0]\n\n\n# class Solution:\n\n# def wordBreak(self, s, wordDict):\n# \"\"\"\n# :type s: str\n# :type wordDict: List[str]\n# :rtype: bool\n# \"\"\"\n# n = len(s)\n# wordDict = set(wordDict)\n\n# dp = [False] * (n + 1)\n# dp[0] = True\n\n# for i in range(1, n + 1):\n# if s[0:i] in wordDict:\n# dp[i] = True\n# continue\n# for j in range(1, i):\n# if dp[j]:\n# if s[j:i] in wordDict:\n# dp[i] = True\n# break\n# return dp[-1]\n\n# Bad recursive soution\n# class Solution:\n# \"\"\"\n# @param: s: A string\n# @param: dic: A dictionary of words dict\n# @return: A boolean\n# \"\"\"\n\n# def recurse(self, s, ssize, dic, dicsize, sidx):\n# if (sidx == ssize):\n# return True\n# matched = list(dic)\n# for idx in range(sidx, ssize):\n# midx = 0\n# while (midx < len(matched)):\n# wd = matched[midx]\n# if (len(wd) == idx - sidx + 1):\n# if (wd[idx - sidx] == s[idx] and\n# self.recurse(s, ssize, dic, dicsize, idx + 1)):\n# return True\n# else:\n# matched.remove(wd)\n# midx -= 1\n# elif (idx - sidx >= len(wd) or wd[idx - sidx] != s[idx]):\n# matched.remove(wd)\n# midx -= 1\n# midx += 1\n# if len(matched) == 0:\n# return False\n# return False\n\n# def wordBreak(self, s, dic):\n# # write your code here\n# if len(s) == 0 and '' in dic:\n# return True\n# for wd in dic:\n# if len(wd) == 0:\n# dic.remove(wd)\n# dicsize = len(dic)\n# ssize = len(s)\n# return self.recurse(s, ssize, dic, dicsize, 0)\n\n# print(Solution().wordBreak('abccab', set(['a', 'c', 'b'])))\n\n# print(Solution().wordBreak('a', set(['b'])))\n"} {"blob_id": "71a71e9e3e559a696fbb45a66e04b52b8a88fb05", "repo_name": "khoeger/rhymesToMusic", "path": "/restructure/rhymesToMusic/parseTextAsMusic/parseText.py", "length_bytes": 7250, "score": 3.71875, "int_score": 4, "content": "\"\"\"\n Need to convert music to text in some way\n Goal\n - read characters in string by \"type\"\n - if a character is type [], then follow rules to write melody\n - output melody\n\n For purposes of having a working conversion\n - read characters in string by \"type\"\n - types: words =[a-zA-Z]+ and [[a-zA-Z]+'[a-zA-Z]+], non words else\n\"\"\"\nfrom nltk.corpus import cmudict\nimport re\nimport music21 as mus\nfrom text_processing.wordsToPhonemes import *\n\nd = cmudict.dict()\n\n#-------------------------------\ndef isPunctuation(chunk):\n pattern = re.compile(\"[^a-zA-Z]+\")\n punctuationList = re.findall(pattern,chunk)\n return(punctuationList)\n\ndef letterOrNot(chunkPiece,pattern):\n if re.findall(pattern,chunkPiece)==[]:\n return(\"letter\")\n else:\n return(\"other\")\n\ndef punctuationSlots(chunk,punctuationList):\n pattern = re.compile(\"[^a-zA-Z]+\")\n\n front = chunk[0]\n end = chunk[-1]\n\n # is the first char a letter?\n firstChar = letterOrNot(front,pattern)\n if firstChar == \"letter\":\n pass\n return(\"ADD A VALUE\")\n\ndef frontPunctuation(chunk):\n pattern = re.compile(\"[\\n ]*[^a-zA-Z0-9]+\")\n frontPunc = re.findall(pattern,chunk)\n if frontPunc == []:\n return(\"\")\n else:\n return(frontPunc[0])\n\ndef endPunctuation(chunk):\n pattern = re.compile(\"[^a-zA-Z0-9]+[\\n ]*\")\n endPunc = re.findall(pattern,chunk)\n if endPunc == []:\n return(\"\")\n else:\n return(endPunc[0])\n\ndef textChunk(chunk):\n pattern1 = re.compile(\"[\\n ][^a-zA-Z0-9]+\")\n pattern2 = re.compile(\"[^a-zA-Z0-9]+[\\n ]\")\n chunk0 = re.sub(pattern1, \"\", chunk)\n chunk1 = re.sub(pattern2, \"\", chunk0)\n return(chunk1)\n\ndef phonemeToPitchVal(dictionary,phoneme,scale):\n #print(\"Phoneme\",\"type(phoneme)\")\n #print(phoneme,type(phoneme))\n if phoneme in dictionary.keys():\n noteDegree = dictionary[phoneme]\n freq = scale.pitchFromDegree(noteDegree)\n return(freq)\n else:\n return(\"[parseText.py: phonemeToPitchVal] \",\n \"Error converting degree to frequency. \",\n \"Phoneme not in the dictionary\")\n\n\ndef buildMeasure(chunk,d,dictionary,scale):\n \"\"\"\n Given an input chunk:\n - Separate chunk into frontPunctuation, text, endPunctuation\n - break text chunk into syllable chunks\n - create a chunk piece list composed of all composite chunks\n - determine measure rhythm from chunk list length\n - build measure\n \"\"\"\n fPuncChunk = frontPunctuation(chunk)\n tChunk = textChunk(chunk)\n tChunk = tChunk.lower()\n ePuncChunk = endPunctuation(chunk)\n\n measure = mus.stream.Stream()\n convertList = []\n\n if fPuncChunk != '':\n convertList.append('REST')\n if textChunk != '':\n #textChunkOn = 1\n textChunkPhonemes = word2Phoneme(chunk,d)\n textChunkPhonemesClean = rmNumsFrmStrList(textChunkPhonemes)\n #textChunkPhonemeLen = len(textChunkPhonemesClean)\n convertList = convertList + textChunkPhonemesClean\n if ePuncChunk != '':\n convertList.append('REST')\n #print(\"convertList\")\n #print(convertList)\n mParts = len(convertList)\n #print(\"mParts\")\n #print(mParts)\n noteLength = 4/mParts\n #print(\"noteLength\")\n #print(noteLength)\n\n dur = mus.duration.Duration(noteLength)\n\n for element in convertList:\n\n if element == 'REST':\n charRest = mus.note.Rest()\n charRest.duration = dur\n measure.append(charRest)\n else:\n pVal = phonemeToPitchVal(dictionary,element,scale)\n pValNote = mus.note.Note(pVal)\n pValNote.duration = dur\n measure.append(pValNote)\n\n return(measure)\n\ndef buildMeasure2(chunk,d,dictionary,scale):\n \"\"\"\n Given an input chunk:\n - determine measure rhythm from chunk list length\n - build measure\n \"\"\"\n # fPuncChunk = frontPunctuation(chunk)\n # tChunk = textChunk(chunk)\n # tChunk = tChunk.lower()\n # ePuncChunk = endPunctuation(chunk)\n\n measure = mus.stream.Stream()\n\n convertList = chunk#[]\n\n # if fPuncChunk != '':\n # convertList.append('REST')\n # if textChunk != '':\n # #textChunkOn = 1\n # textChunkPhonemes = word2Phoneme(chunk,d)\n # textChunkPhonemesClean = rmNumsFrmStrList(textChunkPhonemes)\n # #textChunkPhonemeLen = len(textChunkPhonemesClean)\n # convertList = convertList + textChunkPhonemesClean\n # if ePuncChunk != '':\n # convertList.append('REST')\n # #print(\"convertList\")\n # #print(convertList)\n mParts = len(convertList)\n #print(\"mParts\")\n #print(mParts)\n quarters = 4 # quarter notes per measure\n noteLength = quarters/mParts\n #print(\"noteLength\")\n #print(noteLength)\n\n dur = mus.duration.Duration(noteLength)\n #print(dur)\n punctuation = re.compile(r\"(\\W+)\")\n\n for element in convertList:\n\n if element == 'MeasureRest':\n charRest = mus.note.Rest()\n charRest.duration = mus.duration.Duration(quarters/2)\n measure.append(charRest)\n elif punctuation.fullmatch(element):\n charRest = mus.note.Rest()\n charRest.duration = dur#mus.duration.Duration(quarters/(mParts*2)) #dur\n measure.append(charRest)\n else:\n\n #print(element)\n #print(removeNums(element))\n pVal = phonemeToPitchVal(dictionary,removeNums(element),scale)\n pValNote = mus.note.Note(pVal)\n pValNote.duration = dur\n measure.append(pValNote)\n\n return(measure)\n\ndef buildPiece(chunkList,d,dictionary,scale):\n piece = mus.stream.Stream()\n instr = mus.instrument.Ocarina()\n piece.insert(0.0, instr)\n #for chunk in chunkList:\n for i in range(0,len(chunkList)):\n if chunkList[i] == []:\n pass\n #measure = buildMeasure(chunk,d,dictionary,scale)\n else:\n measure = buildMeasure2(chunkList[i],d,dictionary,scale)\n piece.append(measure)\n return(piece)\n\"\"\"\n--- Learning RE library tricks ---\n\n>>> inputText = \"This is my sample string. Long live the Queen!!!! Haha <3 \\nSee, it's a new line!\"\n>>>\n>>> pat4 = re.compile(r\"([\\n]+)\")\n>>> pat4.split(inputText)\n['This is my sample string. Long live the Queen!!!! Haha <3 ', '\\n', \"See, it's a new line!\"]\n>>>\n>>> pats4 = pat4.split(inputText)\n>>> pats4\n['This is my sample string. Long live the Queen!!!! Haha <3 ', '\\n', \"See, it's a new line!\"]\n>>>\n>>> pat3 = re.compile(\"[ ]+\")\n>>> pats3 = []\n>>> for i in pats4:\n... x = pat3.split(i)\n... for j in x:\n... pats3.append(j)\n...\n>>> pats3\n['This', 'is', 'my', 'sample', 'string.', 'Long', 'live', 'the', 'Queen!!!!', 'Haha', '<3', '', '\\n', 'See,', \"it's\", 'a', 'new', 'line!']\n>>>\n--- DON'T DO RIGHT AWAY ---\n - also, remove the ''\n>>>\n>>> pat2 = re.compile(r\"(\\W+)\"\n... )\n>>> pats2 = []\n>>> for i in pats3:\n... x = pat2.split(i)\n... for j in x:\n... pats2.append(j)\n...\n>>> pats2\n['This', 'is', 'my', 'sample', 'string', '.', '', 'Long', 'live', 'the', 'Queen', '!!!!', '', 'Haha', '', '<', '3', '', '', '\\n', '', 'See', ',', '', 'it', \"'\", 's', 'a', 'new', 'line', '!', '']\n\n\"\"\"\n"} {"blob_id": "2d33ce6263d4cccaa2d44511aac667095b6c7f82", "repo_name": "coyotespike/projecteulersolutions", "path": "/Problem6.py", "length_bytes": 1663, "score": 3.9375, "int_score": 4, "content": "\"\"\"\nThe difference between the sum of the squares of the first ten natural numbers and the square of the sum\nis 3025 - 385 = 2640\n\nFind the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.\n\nthe sum up to any number n is : n(n+1)/2\nthe sum of squares up to any number is: (n/6)(2n+1)(n+1)\n\nYou can find this sum of squares formula by a simple and beautiful method called finite differences.\nFor any series of numbers, make a list of the differences between them. Then make a list of the differences between\nthe differences. When these differences equal each other, that depth of the list is equal to the highest degree of\nthe polynomial equation which produced the series.\nFor, instance, the differences between [-3, 2, 13, 30, 53] are [5, 11, 17, 23], and the differences between those are\n[6, 6, 6]:\n\n -3 2 13 30 53\n 5 11 17 23\n 6 6 6\nTherefore the equation must be of the form an^2 + bn + c. Next, if we know that when n=1 the formula works out\nto the first number in the series, -3, we can just substitute different values of to get a system of equations.\nIf n =1, a + b + c = -3\nIf n=2 4a + 2b + c = 2\nIf n=3, 9a + 3b + c = 13\n\nThese are easy to solve, and tell us what a, b, and c are. Here, the finite differences method easily finds the sum\nof squares formula.\n\n\n\"\"\"\n\ndef square_difference (number):\n\n return abs(sum([num**2 for num in range(number+1)]) - (sum(range(number+1))**2))\n\nprint square_difference(100)\n\ndef math_diff (number):\n return (((number*(number+1))/2)**2 - ((number*((2*number + 1)*(number+1)))/6))\n\nprint math_diff(100)"} {"blob_id": "6168a2934f2223d9288d1fd257382aa390900944", "repo_name": "tashakim/puzzles_python", "path": "/quick_select.py", "length_bytes": 1030, "score": 3.640625, "int_score": 4, "content": "class Solution:\n def findKthLargest(self, nums, k):\n \"\"\"Purpose: Returns the kth largest item of an unsorted array,\n using Quickselect.\n \"\"\"\n def partition(l, r, i):\n pivot = nums[i]\n nums[i], nums[r] = nums[r], nums[i] \n index = l\n for i in range(l, r):\n if nums[i] < pivot:\n nums[index], nums[i] = nums[i], nums[index]\n index += 1\n\n nums[r], nums[index] = nums[index], nums[r] \n return index\n \n def select(l, r, k_smallest):\n if l == r: \n return nums[l] \n i = random.randint(l, r) \n i = partition(l, r, i)\n \n if k_smallest == i:\n return nums[k_smallest]\n elif k_smallest < i:\n return select(l, i - 1, k_smallest)\n else:\n return select(i + 1, r, k_smallest)\n return select(0, len(nums) - 1, len(nums) - k)\n "} {"blob_id": "e0a7b4d3db355e650a11ef4b123c709f31f2da2c", "repo_name": "supernovan/schoolworkLTH", "path": "/eda132-master/reversi.py", "length_bytes": 8978, "score": 3.625, "int_score": 4, "content": "import random\nimport sys\nimport math\nimport time\n\nEMPTY = 0\nWHITE = 1\nBLACK = -1\n\n#Draws the board\ndef drawBoard(board):\n\thline = \" +---+---+---+---+---+---+---+---+\"\n\tprint(\" a b c d e f g h\")\n\tprint(hline)\n\tfor i in range(1,9):\n\t\tprint(str(i) + \" |\", end=\"\")\n\t\tfor j in range(1,9):\n\t\t\ttemp = board[i][j]\n\t\t\tif temp == 0:\n\t\t\t\tprint(\" |\", end=\"\")\n\t\t\telif temp == 1:\n\t\t\t\tprint(\" O |\", end=\"\")\n\t\t\telif temp == 2:\n\t\t\t\tprint(\" S |\", end=\"\")\n\t\t\telse:\n\t\t\t\tprint(\" X |\", end=\"\")\n\n\t\tprint(\"\")\n\n\tprint(hline)\n\n#Returns a list of all available moves\ndef showMoves(board, player):\n\tmoves = []\n\tfor i in range(1,9):\n\t\tfor j in range(1,9):\n\t\t\tif board[i][j] == 0:\n\t\t\t\tif checkMove(board, player, i, j) == True:\n\t\t\t\t\tmoves.append((i - 1)*8 + j)\n\treturn moves\n\n#Checks wether a move is okay for that player\ndef checkMove(board, player, x, y):\n\tfor i in range(x-1, x+2):\n\t\tfor j in range(y-1, y+2):\n\t\t\tif i == x and j == y or not(validTile(i,j)):\n\t\t\t\tcontinue\n\n\t\t\tif board[i][j] == player:\n\t\t\t\tcontinue\n\n\t\t\tif board[i][j] == -player:\n\t\t\t\tvec = checkMoveDirection(board, player, x, y, i-x, j-y)\n\t\t\t\tif vec[0] == True:\n\t\t\t\t\treturn True\n\treturn False\n\n#Checks a move and put player on that tile and flips everything that should be flipped\n#returns number of tiles that got swaped\ndef checkMoveAndFlip(board, player, x, y):\n\tif board[x][y] != EMPTY:\n\t\treturn 0\n\tcheck = 0\n\tfor i in range(x-1, x+2):\n\t\tfor j in range(y-1, y+2):\n\t\t\tif i == x and j == y or not(validTile(i,j)):\n\t\t\t\tcontinue\n\n\t\t\tif board[i][j] == player:\n\t\t\t\tcontinue\n\n\t\t\tif board[i][j] == -player:\n\t\t\t\tvec = checkMoveDirection(board, player, x, y, i-x, j-y)\n\t\t\t\tif vec[0] == True:\n\t\t\t\t\tcheck = True\n\t\t\t\t\tfor k in range(0,int(vec[1])):\n\t\t\t\t\t\tdx = int((i-x)*k)\n\t\t\t\t\t\tdy = int((j-y)*k)\n\t\t\t\t\t\tboard[x + dx][y + dy] = player\n\t\t\t\t\t\tcheck += 1\n\treturn check\n\n#returns a vector containing of wether a certain direction\n#should be be flipped and how many tiles we should flip\ndef checkMoveDirection(board, player, x, y, dx, dy):\n\tvec = [False, 1]\n\tx += dx\n\ty += dy\n\twhile validTile(x, y):\n\t\tif board[x][y] == EMPTY:\n\t\t\treturn vec\n\t\telif board[x][y] == player:\n\t\t\tvec[0] = True\n\t\t\treturn vec\n\t\telse:\n\t\t\tvec[1] += 1\n\t\t\tx += dx\n\t\t\ty += dy\n\treturn vec\n\n\n#Checks wether x and y is on the board\ndef validTile(x, y):\n\treturn x >= 1 and x <= 8 and y >= 1 and y <= 8\n\n\n#Duplicates the board\ndef dupBoard(board):\n\tdup = [x[:] for x in board]\n\treturn dup\n\n\n#MinMax algorithm with alphabeta, right now there is a depths instead of a timelimit\ndef minMax(alpha, beta, board, ms, maxDepth, depth, player):\n\n\tmoves = showMoves(board, player)\n\tif ms <= time.time()*1000.0 or depth > maxDepth:\n\t\tprint(\"knas\")\n\telif len(moves) == 0:\n\t\treturn 0\n\tmaxValue = float(\"inf\")\n\tbestMove = 0\n\tfor i in moves:\n\t\tdup = dupBoard(board)\n\t\tcheckMoveAndFlip(dup, player, (i-1)%8+1, math.ceil(i/8))\n\t\tvalue = playMin(alpha, beta, dup, ms,maxDepth, depth+1, -player)\n\t\tif value < maxValue:\n\t\t\tbestMove = i\n\t\t\tmaxValue = value\n\treturn bestMove\n\ndef playMax(alpha, beta, board, ms, maxDepth, depth, player):\n\n\tmoves = showMoves(board, player)\n\tif ms <= time.time()*1000.0 or depth > maxDepth:\n\t\treturn alpha\n\telif len(moves) == 0: #might not be correct\n\t\treturn alpha\n\n\tfor i in moves:\n\t\tdup = dupBoard(board)\n\t\tcheckMoveAndFlip(dup, player, (i-1)%8+1, math.ceil(i/8))\n\t\tvalue = playMin(alpha, beta, dup, ms, maxDepth, depth +1, -player)\n\t\tif value >= beta:\n\t\t\treturn beta\n\t\tif value > alpha:\n\t\t\talpha = value\n\n\treturn alpha\n\ndef playMin(alpha, beta, board, ms, maxDepth, depth, player):\n\t\n\tmoves = showMoves(board, player)\n\tif ms <= time.time()*1000.0 or depth > maxDepth:\n\t\treturn beta\n\telif len(moves) == 0: #might not be correct\n\t\treturn beta\n\t\n\n\tfor i in moves:\n\t\tdup = dupBoard(board)\n\t\tcheckMoveAndFlip(dup, player, (i-1)%8+1, math.ceil(i/8))\n\t\tvalue = playMax(alpha, beta, dup, ms, maxDepth, depth+1, -player)\n\t\tif value <= beta:\n\t\t\treturn alpha\n\t\tif value < beta:\n\t\t\tbeta = value\n\treturn beta\n\n#montecarlo simulation\ndef monteCarlo(boardState, player, ms):\n\tmoves = showMoves(boardState, player)\n\ttimes = []\n\twins = []\n\tif len(moves) == 0:\n\t\treturn 0\n\n\tfor i in range(0, len(moves)):\n\t\ttimes.append(0)\n\t\twins.append(0)\n\n\twhile (ms > time.time()*1000.0 ):\n\t\tfor i in range(0, len(moves)):\n\t\t\ttimes[i] += 1\n\t\t\tdup = dupBoard(boardState)\n\t\t\tif simulation(dup, player) == 1:\n\t\t\t\twins[i] += 1\n\n\t\t#print(time)\n\tmaxValue = float(\"-inf\")\n\tindex = 0;\n\tfor i in range(0, len(wins)):\n\t\tif maxValue < wins[i]:\n\t\t\tmaxValue = wins[i]\n\t\t\tindex = i\n\n\n\treturn moves[index]\n\n#Random simulation for montecarlo\ndef simulation(board, player):\n\twhile True:\n\t\tmoves1 = showMoves(board, player)\n\t\tif len(moves1) == 0:\n\t\t\tmoves2 = showMoves(board, -player)\n\t\t\tif len(moves2) == 0:\n\t\t\t\treturn won(board, player)\n\t\t\telse:\n\t\t\t\tmove = random.randint(0, len(moves2)-1)\n\t\t\t\tcheckMoveAndFlip(board, -player, math.ceil(moves2[move]/8), (moves2[move]-1)%8 + 1)\n\t\telse:\n\t\t\tmove = random.randint(0, len(moves1)-1)\n\t\t\tcheckMoveAndFlip(board, player, math.ceil(moves1[move]/8), (moves1[move]-1)%8 + 1)\n\t\t\tmoves2 = showMoves(board, -player)\n\t\t\tif len(moves2) != 0:\n\t\t\t\tmove = random.randint(0, len(moves2)-1)\n\t\t\t\tcheckMoveAndFlip(board, -player, math.ceil(moves2[move]/8), (moves2[move]-1)%8 + 1)\n\n\treturn 0\n\n\n#checks which player won\ndef won(board, player):\n\tplayer1 = 0\n\tplayer2 = 0\n\tfor i in range(1,9):\n\t\tfor j in range(1, 9):\n\t\t\tif board[i][j] == player:\n\t\t\t\tplayer1 += 1\n\t\t\telif board[i][j] == -player:\n\t\t\t\tplayer2 += 1\n\n\tif player1 > player2:\n\t\treturn player\n\telif player2 > player1:\n\t\treturn -player\n\telse: \n\t\treturn 0\n\ndef translateInput(string):\n\tif len(string) == 2:\n\t\ttry:\n\t\t\treturn [ord(string[0]) - 96, int(string[1])]\n\t\texcept ValueError:\n\t\t\tprint(\"Format error, shuting down\")\n\t\t\tsys.exit(1)\n\n\n\ndef aiFight(player, board, temp, maxDepth):\n\twhile len(showMoves(board, player)) > 0 or len(showMoves(board, -player)) > 0:\n\t\tdrawBoard(board)\n\t\ttime.sleep(1)\n\t\tprint(\"AlphaBeta is thinking\")\n\t\tms = time.time()*1000.0 + 1000*temp\n\t\tcompMove = minMax(float(\"-inf\"), float(\"inf\") ,board, ms, maxDepth, 0, player)\n\t\tif compMove == 0:\n\t\t\tprint(\"AlphaBeta can not do anything\")\n\n\t\telse:\n\t\t\tcheckMoveAndFlip(board, player, math.ceil(compMove/8), (compMove-1)%8+1)\n\t\t\tdrawBoard(board)\n\t\tprint(\"MonteCarlo is thinking\")\n\t\tms = time.time()*1000.0 + 1000*temp\n\t\tcompMove = monteCarlo(board, -player, ms)\n\t\tif compMove == 0:\n\t\t\tprint(\"MonteCarlo can not do anything\")\n\t\telse:\n\t\t\tcheckMoveAndFlip(board, -player, math.ceil(compMove/8), (compMove-1)%8+1)\n\ndef regularFight(player, board, temp, maxDepth):\n\twhile len(showMoves(board, player)) > 0 or len(showMoves(board, -player)) > 0:\n\t\tdrawBoard(board)\n\t\ttime.sleep(1)\n\t\tprint(\"Make a move that's available (e.g a3, only this format works)\")\n\t\tuserMove = input()\n\t\tmove = translateInput(userMove)\n\t\twhile not(checkMove(board, player, move[1], move[0])):\n\t\t\tmove = translateInput(input(\"Invailid move, type a valid move. (eg a3)\"))\n\n\t\tcheckMoveAndFlip(board, player, move[1], move[0])\n\t\tdrawBoard(board)\n\t\tprint(\"AlphaBeta is thinking\")\n\t\tms = time.time()*1000.0 + 1000*temp\n\t\tcompMove = minMax(float(\"-inf\"), float(\"inf\") ,board, ms, maxDepth, 0, -player)\n\t\tif compMove == 0:\n\t\t\tprint(\"AlphaBeta can not do anything\")\n\t\telse:\n\t\t\tcheckMoveAndFlip(board, -player, math.ceil(compMove/8), (compMove-1)%8+1)\n\n\n\n\n#The game matrix\nboard = [[]]\nfor i in range(0,9):\n\tboard.append([])\n\tfor j in range(0,9):\n\t\tboard[i].append(0)\n\n\n#Starting pieces\npiece = input(\"white or black? (w or b)\")\nif piece == \"w\" or piece == \"W\":\n\tplayer = WHITE\nelse:\n\tplayer = BLACK\n\n\n\nboard[4][4] = player\nboard[4][5] = -player\nboard[5][5] = player\nboard[5][4] = -player\n\n\n#checks wether anyone can make a move right now\ntemp = int(input(\"How much time will be computer be allowed to think? (in seconds)\"))\nmaxDepth = int(input(\"maxdepth to search for?\"))\n\ngameMode = input(\"type 'ai' for montecarlo vs minmax or anything else to just fight minmax algorithm\")\n\nif gameMode == \"ai\":\n\taiFight(player, board, temp, maxDepth)\nelse:\n\tregularFight(player, board, temp, maxDepth)\n\ndrawBoard(board)\nresult = won(board, player)\nif result == 1:\n\tprint(\"AlphaBeta won\")\nelif result == -1:\n\tprint(\"MonteCarlo won\")\nelse: \n\tprint(\"they both lost\")\n\nsum1 = 0\nsum2 = 0\nfor i in range(1,9):\n\tfor j in range(1,9):\n\t\tif board[i][j] == player:\n\t\t\tsum1 += 1\n\t\telif board[i][j] == -player:\n\t\t\tsum2 += 1\nprint(str(sum1) + \"-\" + str(sum2))\n\n\n\n\n# board = [[0,0,0,0,0,0,0,0,0],[0,1,1,1,1,1,1,1,1],[0,1,1,1,-1,-1,-1,1,1],[0,1,1,-1,-1,-1,1,-1,1],[0,1,-1,-1,1,-1,-1,1,1],[0,1,-1,1,1,1,-1,1,1],[0,1,1,1,-1,-1,-1,-1,-1],[0,1,1,1,1,1,1,1,-1],[0,1,1,1,1,1,1,1,0]]\n# rBoard = [[]]\n# for i in range(0,9):\n# \trBoard.append([])\n# \tfor j in range(0,9):\n# \t\trBoard[i].append(0)\n# # iterate through rows\n# for i in range(0, 9):\n# # iterate through columns\n# for j in range(0, 9):\n# rBoard[j][i] = board[i][j]\n# player = WHITE\n# drawBoard(rBoard)\n# moves = showMoves(board, player)\n# print(moves)\n# compMove = minMax(float(\"-inf\"), float(\"inf\") ,board, 8, 0, player)\n# print(str(compMove))"} {"blob_id": "37d8e3543a98bd5015851b74122e3bde58a04678", "repo_name": "mattjp/leetcode", "path": "/practice/medium/0039-Combination_Sum.py", "length_bytes": 568, "score": 3.546875, "int_score": 4, "content": "class Solution:\n def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:\n\n def search(nums: List[int], path: List[int]=[], cur: int=0):\n for i,num in enumerate(nums):\n if cur+num < target:\n search(nums[i:], path+[num], cur+num) # reduce search space so we don't look backwards\n else:\n if cur+num==target:\n self.output.append(path+[num])\n return # if input is sorted, we can just quit here\n \n \n self.output = []\n search(sorted(candidates))\n return self.output\n"} {"blob_id": "066e3c043cbb1c67f1dbe2748cc28c94d95568c3", "repo_name": "rumangerst/evolution", "path": "/\u00dcbung_1/BinaryStringEvolution.py", "length_bytes": 4239, "score": 3.703125, "int_score": 4, "content": "# coding: utf8\r\n\r\n\"\"\"\r\n\r\nEvolutionary algorithm, optimizing a bit string.\r\n\r\n\"\"\"\r\n\r\nimport random;\r\n\r\niteration = 0;\r\n\r\n\"\"\"\r\nCreates an individual with given size\r\n\"\"\"\r\ndef create_new_individual(size):\r\n output = \"\";\r\n \r\n for _ in range(size):\r\n output = output + str(random.randint(0,1));\r\n return output;\r\n\r\n\"\"\"\r\nGenerate Score for the individual\r\n\"\"\"\r\ndef F(individual):\r\n score = 0;\r\n \r\n for character in individual:\r\n score += 1 if character == \"1\" else 0;\r\n \r\n return score;\r\n\r\n\"\"\"\r\nReturns a mutated variant of the invididual with mutation probability p\r\n\"\"\"\r\ndef getMutant(individual, p):\r\n individual_chars = list(individual); #Strings are immuteable and always recreating strings is expensive\r\n \r\n for i in range(len (individual_chars)):\r\n rand = 1.0 - random.random(); #random.random() returns number in [0,1), but we want a number in (0,1], so invert it\r\n assert rand >= 0 and rand <= 1; #for checking\r\n \r\n \r\n if (rand <= p): \r\n \r\n char = individual_chars[i];\r\n individual_chars[i] = \"0\" if char == \"1\" else \"1\"; #swap the bit\r\n \r\n return \"\".join(individual_chars);\r\n\r\ndef selectbest(population):\r\n assert len(population) > 0;\r\n \r\n best = population[0]; #select the first\r\n bestscore = F(best);\r\n \r\n #Search for best individual\r\n for individual in population:\r\n \r\n score = F(individual);\r\n \r\n if score > bestscore:\r\n best = individual;\r\n bestscore = score;\r\n \r\n return best;\r\n \r\n\"\"\"\r\nGenerates population and runs evolution on it\r\n\r\nparent - Inital parent\r\ndescendants - \u03bb\r\nmutation_rate - p\r\n\r\n\"\"\"\r\ndef evolution(parent, descendants, mutation_rate):\r\n \r\n global iteration;\r\n global bestindividual;\r\n global population;\r\n \r\n population = [parent]; #only the parent exists\r\n iteration = 0; #set iteration to zero\r\n \r\n bestindividual = parent; #save it here for termination \r\n \r\n while F(bestindividual) != 40 and iteration < 10000: \r\n \r\n iteration += 1; #count iteration\r\n \r\n \r\n print \"iteration \" + str(iteration);\r\n \r\n #Look for best indidual\r\n bestindividual = selectbest(population);\r\n \r\n print \"best: \" + bestindividual;\r\n \r\n \r\n #Create a new population with only individual and it's descendants in it\r\n population = [bestindividual];\r\n \r\n \r\n for _ in range(descendants):\r\n population.append(getMutant(bestindividual, mutation_rate));\r\n \r\n #Go on until terminated.\r\n \r\n #terminated!\r\n #return the best individual\r\n \r\n return bestindividual;\r\n\r\ndef main_mutationtest():\r\n \r\n global mutationtest_iterationresult; \r\n global mutationtest_fresult;\r\n mutationtest_iterationresult = [];\r\n mutationtest_fresult = [];\r\n \r\n mutationtest_testranges = [x * 0.01 for x in range(0,11) ];\r\n mutationtest_testranges.extend( [x * 0.05 for x in range(3,21) ] );\r\n \r\n for mutation_rate in mutationtest_testranges:\r\n \r\n print \"**** TESTING WITH RATE \" + str(mutation_rate);\r\n \r\n parent = create_new_individual(40); #parameter: n\r\n descendants = 400; # = \u03bb \r\n \r\n best = evolution(parent, descendants, mutation_rate); #returns best individual\r\n \r\n mutationtest_iterationresult.append(iteration); \r\n mutationtest_fresult.append(F(best));\r\n \r\n print \"RESULT (iter):\" + str( mutationtest_iterationresult); \r\n print \"RESULT (best):\" + str( mutationtest_fresult); \r\n \r\n\"\"\"\r\nMain method\r\n\"\"\"\r\ndef main():\r\n \r\n parent = create_new_individual(40); #parameter: n\r\n descendants = 100; # = \u03bb\r\n mutation_rate = 0.05; # = p ; Mutation rate should be selected that only 1-2 chars will mutate\r\n \r\n best = evolution(parent, descendants, mutation_rate); #returns best individual\r\n \r\n print \"Best individual in \" + str(iteration) + \" iterations: \" + best;\r\n \r\n#main();\r\nmain_mutationtest();\r\n"} {"blob_id": "69de015fd1be07ac2d640e5e63b179c320babcfc", "repo_name": "Ashutoshkr007/EZ-SHA-1", "path": "/SHA-1.py", "length_bytes": 4052, "score": 3.71875, "int_score": 4, "content": "def binary(item):\r\n x = bin(int(str(item), 0))[2:]\r\n pad = ''\r\n if len(x)<32:\r\n pad = '0'*(32-len(x))\r\n x = pad + x\r\n return x\r\nprint(binary(32))\r\n\r\ndef trunc(item, length):\r\n item = binary(item)\r\n if len(item) > length:\r\n rem = len(item) - length\r\n item = item[rem:]\r\n return int(item, 2)\r\n\r\ndef _left_rotate(n, b):\r\n n = str(n)\r\n if n[:2] == '0b':\r\n n = n[2:]\r\n else:\r\n n = binary(n)\r\n n = n[b:] + n[:b]\r\n return int(n, 2)\r\n\r\n\"\"\"Divide the input into tokens of charachter\"\"\"\r\nInput = input()\r\nsplit_in = [char for char in Input]\r\nprint(split_in)\r\n\r\n\"\"\"Get the ASCII of each token in an Array\"\"\"\r\nascii_in = [ord(split_in[i]) for i in range(len(split_in))]\r\nprint(ascii_in)\r\n\r\n\"\"\"Now create an array of binary ASCII values from previous array\"\"\"\r\nascii_bin = [bin(ascii_in[i])[2:] for i in range(len(ascii_in))]\r\nprint(ascii_bin)\r\n\r\n\"\"\"Add 0 in front of each binary no. till they are of 8 length each\"\"\"\r\nfor i in range(len(ascii_bin)):\r\n padding = '0'*(8-len(ascii_bin[i]))\r\n ascii_bin[i] = padding + ascii_bin[i]\r\nprint(ascii_bin)\r\n\r\n\"\"\"join the binary Array and add 1 in front\"\"\"\r\nstr_ascii = ''.join(ascii_bin) + '1'\r\nprint(str_ascii)\r\n\r\n\"\"\"Add 0 till the legth of binary ASCII string is 512 mod 448 doing like this is neccassry for big messages \r\n for small you can simpy do this will length is mod 448\"\"\"\r\nwhile(len(str_ascii) % 512 != 448):\r\n str_ascii += '0'\r\nprint(str_ascii, len(str_ascii))\r\n\"\"\"Use the binary ASCII array of 8bits each and add the length of each array element convert that to 64 bit binary\r\n number and concatenate in the end of 448 bit ASCII string sp you can get 512 bit binay message denoting length of the\r\n message in the Least Significant 64 bit and message in remaining bits\"\"\"\r\nlength = 0\r\nfor i in ascii_bin:\r\n length += len(i)\r\nlength_bin = bin(length)[2:]\r\npadding = '0' * (64-len(length_bin))\r\nlength_bin = padding + length_bin\r\nprint(length_bin)\r\nstr_ascii += length_bin\r\nprint(str_ascii, len(str_ascii))\r\n\r\n\"\"\"Divide the message int0 chunks of 512 bits\"\"\"\r\nimport textwrap\r\nitem = ''\r\nchunks = textwrap.wrap(str_ascii, 512)\r\nprint(chunks)\r\n\r\n\"\"\"Divide each chunk into sixteen 32-bit word\"\"\"\r\nchunkword = []\r\nchunkword = [textwrap.wrap(i, 32) for i in chunks]\r\nprint(chunkword)\r\n\r\n\"\"\"Perform operatios to get Eighty 32-bit words\"\"\"\r\nfor i in range(len(chunkword)):\r\n for j in range(16, 80):\r\n wordA = int(chunkword[i][j-3], 2)\r\n wordB = int(chunkword[i][j-8], 2)\r\n wordC = int(chunkword[i][j-14], 2)\r\n wordD = int(chunkword[i][j-16], 2)\r\n xorA = wordA ^ wordB\r\n xorB = xorA ^ wordC\r\n xorC = xorB ^ wordD\r\n xorC = bin(xorC)[2:]\r\n xorC = '0'*(32-len(xorC)) + xorC\r\n xorC = xorC[1:] + xorC[0]\r\n chunkword[i].append(xorC)\r\nprint(chunkword)\r\n\r\n\"\"\"NOw loop throught each chunk to get standard results\"\"\"\r\nh0 = 0b01100111010001010010001100000001\r\nh1 = 0b11101111110011011010101110001001\r\nh2 = 0b10011000101110101101110011111110\r\nh3 = 0b00010000001100100101010001110110\r\nh4 = 0b11000011110100101110000111110000\r\na = h0\r\nb = h1\r\nc = h2\r\nd = h3\r\ne = h4\r\nnew_word = chunkword[0]\r\nfor i in range(80):\r\n if 0 <= i <= 19:\r\n f = d ^ (b & (c ^ d))\r\n k = 0b01011010100000100111100110011001\r\n elif 20 <= i <= 39:\r\n f = b ^ c ^ d\r\n k = 0b01101110110110011110101110100001\r\n elif 40 <= i <= 59:\r\n f = (b & c) | (b & d) | (c & d)\r\n k = 0b10001111000110111011110011011100\r\n elif 60 <= i <= 79:\r\n f = b ^ c ^ d\r\n k = 0b11001010011000101100000111010110\r\n word = new_word[i]\r\n word = int(word, 2)\r\n a, b, c, d, e = trunc((_left_rotate(a, 5) + f + e + k + word), 32), a, _left_rotate(b, 30), c, d\r\n\r\n\r\nh0 = trunc((h0 + a), 32)\r\nh1 = trunc((h1 + b), 32)\r\nh2 = trunc((h2 + c), 32)\r\nh3 = trunc((h3 + d), 32)\r\nh4 = trunc((h4 + e), 32)\r\n\r\nprint(hex(h0)+hex(h1)[2:]+hex(h2)[2:]+hex(h3)[2:]+hex(h4)[2:])\r\n\r\nimport hashlib\r\nresult = hashlib.sha1(Input.encode())\r\nprint(result.hexdigest())"} {"blob_id": "a1b6129eeffbd32e60bf32e42c626582c714db95", "repo_name": "darrencheng0817/AlgorithmLearning", "path": "/Python/leetcode/SingleNumberIii.py", "length_bytes": 655, "score": 3.84375, "int_score": 4, "content": "'''\r\nCreated on 1.12.2016\r\n\r\n@author: Darren\r\n''''''\r\n\r\r\nGiven an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.\r\r\n\r\r\n\r\r\nFor example:\r\r\n\r\r\n\r\r\nGiven nums = [1, 2, 1, 3, 2, 5], return [3, 5].\r\r\n\r\r\n\r\r\nNote:\r\r\n\r\r\nThe order of the result is not important. So in the above example, [5, 3] is also correct.\r\r\nYour algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?\r\r\n\r\r\n\r\r\n\r\r\nCredits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.\" \r\n'''\r\n"} {"blob_id": "90415169c29d34601400a4fc8b18ec3e0713c84d", "repo_name": "kadorek/AlgorithmAnalysis", "path": "/ConvexHull/kaynak.py", "length_bytes": 1393, "score": 3.53125, "int_score": 4, "content": "from random import randint\n\n\n\n\n#Noktlar\ufffd tan\ufffdmlamak \ufffdzere kullan\ufffdlan s\ufffdn\ufffdf yap\ufffds\ufffd\nclass Point(object):\n \n def __init__(self, x,y):\n self.X=x;\n self.Y=y\n\n def IsTheSame(self,p):\n return self.X==p.X and self.Y==p.Y\n\n def Yazdir(self):\n return \"P(%s,%s)\"%(self.X,self.Y)\n\nxMax=200;\nyMax=200;\nn=10;\npoints =[];\n\n# Graham Scan - Tom Switzer \n\nTURN_LEFT, TURN_RIGHT, TURN_NONE = (1, -1, 0)\n\ndef turn(p, q, r):\n return cmp((q[0] - p[0])*(r[1] - p[1]) - (r[0] - p[0])*(q[1] - p[1]), 0)\n\ndef _keep_left(hull, r):\n while len(hull) > 1 and turn(hull[-2], hull[-1], r) != TURN_LEFT:\n hull.pop()\n if not len(hull) or hull[-1] != r:\n hull.append(r)\n return hull\n\ndef convex_hull(points):\n \"\"\"Returns points on convex hull of an array of points in CCW order.\"\"\"\n points = sorted(points)\n l = reduce(_keep_left, points, [])\n u = reduce(_keep_left, reversed(points), [])\n return l.extend(u[i] for i in xrange(1, len(u) - 1)) or l\n\n\n# 3 noktan\ufffdn CCW de\ufffderinin hesaplanmas\ufffd\ndef CCW(p1, p2, p3):\n return (p2.X - p1.X)*(p3.Y - p1.Y) - (p2.Y - p1.Y)*(p3.X - p1.X)\n\nwhile(len(points)0:\n continue;\n else:\n points.append(p);\n\n\nsortedPoints=sorted(key=lambda a : a.Y);\n\n"} {"blob_id": "b93fc71159a3d960f0256ad91b661b41b7602f11", "repo_name": "slavojstar/python-scientific-computing-short-course", "path": "/challenge03Solution.py", "length_bytes": 490, "score": 3.703125, "int_score": 4, "content": "def AitkensDelta(sequence):\n\t''' Returns the Aitken acceleration of sequence '''\n\n\tval1 = next(sequence)\n\tval2 = next(sequence)\n\tval3 = next(sequence)\n\n\twhile True:\n\t\tnewVal = val1 - ((val2 - val1) ** 2) / (val3 - 2 * val2 + val1)\n\t\tyield newVal\n\n\t\tval1 = val2\n\t\tval2 = val3\n\t\tval3 = next(sequence)\n\ndef TestSequence(N):\n\ti = 0\n\tsumVal = 0\n\n\twhile i <= N:\n\t\tsumVal += ((-1) ** i) / (2 * i + 1)\n\t\tyield sumVal\n\t\ti += 1\n\ntestSeq = TestSequence(100)\n\nfor x in AitkensDelta(testSeq):\n\tprint(x)\n"} {"blob_id": "db1a32b1ae786bf9cb9cb748664112b81757e3b3", "repo_name": "dhruvilp/cs440-project-1", "path": "/heap.py", "length_bytes": 966, "score": 3.59375, "int_score": 4, "content": "def heap_push(ls, val):\n index = len(ls)\n ls.append(val)\n parent = int((index - 1) / 2)\n while ls[index] < ls[parent]:\n ls[index], ls[parent] = ls[parent], ls[index]\n index = parent\n parent = int((index - 1) / 2)\n\n\ndef heap_pop(ls):\n if len(ls) == 1: return ls.pop()\n item = ls[0]\n ls[0] = ls.pop()\n index = -1\n next_i = 0\n while next_i != index and int(next_i * 2 + 1) < len(ls):\n index = next_i\n next_i = shift(ls, index)\n return item\n\n\ndef heapify(ls):\n if len(ls) < 2: return\n curr = int((len(ls) - 2) / 2)\n while curr >= 0:\n shift(ls, curr)\n curr -= 1\n\n\ndef shift(ls, node):\n left = node * 2 + 1\n right = node * 2 + 2\n has_right = right < len(ls)\n min_index = left\n if has_right and ls[right] < ls[left]: min_index = right\n if ls[min_index] < ls[node]:\n ls[min_index], ls[node] = ls[node], ls[min_index]\n node = min_index\n return node\n"} {"blob_id": "12bf0b1f5ea0b9c9cc84eb2ad982048e97a9cf27", "repo_name": "nguyenngochuy91/companyQuestions", "path": "/google/3Sum.py", "length_bytes": 744, "score": 3.703125, "int_score": 4, "content": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Oct 20 04:19:16 2019\n\n@author: huyn\n\"\"\"\n#3Sum\nfrom typing import List\ndef threeSum(nums: List[int]) -> List[List[int]]:\n nums.sort()\n res =set()\n check = set()\n for index,num in enumerate(nums):\n if num not in check:\n check.add(num)\n start,stop = index+1,len(nums)-1\n s = -num\n while start int:\r\n # \u5229\u7528\u52a8\u6001\u89c4\u5212\r\n # \u8981\u5230\u8fbe\u7d22\u5f15\u4e3a[r,l]\u7684\u7f51\u683c\uff0c\u6709\u4e24\u79cd\u65b9\u5f0f\r\n # \u4e00\u662f\u4ece[r,l-1]\u7684\u7f51\u683c\u5411\u53f3\u8d70\u8fc7\u6765\u7684\r\n # \u4e8c\u662f\u4ece[r-1,l]\u7684\u7f51\u683c\u5411\u4e0b\u8fc7\u6765\u7684\r\n # \u4ee4S[r,l]\u8868\u793a\u5230\u8fbe\u7d22\u5f15\u4e3a[r,l]\u7684\u7f51\u683c\u7684\u4e0d\u540c\u8def\u5f84\u7684\u4e2a\u6570\r\n # \u5219\u52a8\u6001\u89c4\u5212\u7684\u65b9\u7a0b\u4e3aS[r,l] = S[r-1,l]+S[r,l-1]\r\n\r\n # \u884c\u5217\u7f51\u683c\u6570\u6709\u4e00\u4e2a\u4e3a0\uff0c\u5c31\u8fd4\u56de0\r\n if not m or not n:\r\n return 0\r\n # \u884c\u5217\u7f51\u683c\u6570\u6709\u4e00\u4e2a\u4e3a1\uff0c\u5c31\u8fd4\u56de1\r\n elif m == 1 or n == 1:\r\n return 1\r\n\r\n # \u5b9a\u4e49\u4e8c\u7ef4\u6570\u7ec4\uff0c\u9632\u6b62\u6ea2\u51fa\u8fb9\u754c\uff0c\u6570\u7ec4\u884c \u5217\u5747\u52a01\r\n s = [[0 for i in range(m + 1)] for j in range(n + 1)]\r\n\r\n # \u52a8\u6001\u89c4\u5212\u7684\u521d\u59cb\u72b6\u6001\r\n s[0][1] = 1\r\n\r\n # \u5f00\u59cb\u904d\u5386\r\n for r in range(1, n + 1):\r\n for l in range(1, m + 1):\r\n s[r][l] = s[r - 1][l] + s[r][l - 1]\r\n\r\n return s[-1][-1]\r\n\r\n\r\n\r\n\r\n\r\n\r\n"} {"blob_id": "322d8c7d18a42fdeed08b842f1549b37353a4169", "repo_name": "evank28/ContestCoding", "path": "/G_Kickstart/2020/2020_c_2_stablewall.py", "length_bytes": 2570, "score": 3.609375, "int_score": 4, "content": "# Google Kickstart 2020 Round C\n# Code By Evan Kanter\n# Solved 2020-05-17, live\n\n\ndef insert_before_a(base: str, a: str, to_insert: str) -> str:\n ind = base.find(a)\n return base[:ind] + to_insert + base[ind:]\n\n\ndef swap(base: str, i1: int, i2: int) -> str:\n \"\"\"precondition: i1 > i2\"\"\"\n assert i1 > i2\n return base[:i2] + base[i1] + base[i2+1:i1] + base[i2] + base[i1+1:]\n\n\nif __name__ == \"__main__\":\n T = int(input())\n for t in range(1,T+1):\n R, C = list(map(int, input().split(\" \")))\n rows = [input() for _ in range(R)]\n order = \"\"\n conditions = set()\n stable = True\n last = []\n shapes = set()\n first_row = set()\n for r, row in enumerate(reversed(rows)):\n if r > 0:\n for j, a in enumerate(row):\n below = last[j]\n if a != 'X':\n if below == 'X':\n stable = False\n break\n elif below != a:\n condition = (below, a)\n if condition not in conditions:\n conditions.add(condition)\n if a not in shapes:\n shapes.add(a)\n if not stable:\n break\n else:\n # top row\n for a in row:\n if a != 'X':\n shapes.add(a)\n first_row.add(a)\n last = row\n if stable:\n order = order.join(shapes)\n # Sort the conditions\n afters = set([x[1] for x in conditions])\n firsts = [shape for shape in first_row if shape not in afters]\n i = 0\n for first in enumerate(firsts):\n ind = order.index(first)\n if ind > i:\n order = swap(order, ind, i)\n i += 1\n # for first in firsts:\n\n # Use the conditions to sort the ordered shapes\n swaps = float('inf')\n while swaps:\n swaps = 0\n for before, after in conditions:\n index_before = order.index(before)\n index_after = order.index(after)\n if index_before > index_after:\n order = swap(order, index_before, index_after)\n swaps += 1\n out = order\n else:\n out = -1\n print(\"Case #{}: {}\".format(t,out))\n"} {"blob_id": "1535464dc12cefe53c167bb7743911d6ea552429", "repo_name": "M-Pestka/pszt", "path": "/proj1/podejscie1.py", "length_bytes": 4185, "score": 3.890625, "int_score": 4, "content": "import sys\nimport copy\nimport json\nimport os\n\ndef read_data():\n '''\n loads a json from standard input.\n JSON should contain:\n * N - number of semesters\n * m - number of days devoted to learning\n * k - number of points needed.\n * courses - dictionary of all courses where key is the\n courses name and value is a tuple(number of days needed, number of points)\n '''\n return json.load(os.stdin)\n\n\n\ndef get_k(semesters):\n '''\n calculate number of points gained in the semester\n :param semesters: list of semesters or semester where semester is a list of courses\n :returns: number of points gained\n '''\n if(len(semesters) == 0):\n return 0\n \n if(isinstance(semesters[0], list)):\n return sum([sum([c[2] for c in s]) for s in semesters])\n return sum([c[2] for c in semesters])\n\n\ndef get_m(semesters):\n '''\n returns number of days needed for studying during the semester\n :param semesters: list of semesters or semester where semester is a list of courses\n :returns: sum of days needed for studying\n '''\n if(len(semesters) == 0):\n return 0\n \n if(isinstance(semesters[0], list)):\n return sum([sum([c[1] for c in s]) for s in semesters])\n return sum([s[1] for s in semesters])\n\n\nclass Solver:\n '''\n Solver for the problem of multiple bin packing.\n '''\n def __init__(self, N, m, k, courses):\n '''\n constructor.\n :param N: number of semesters\n :param m: number of days of studying per semester\n :param k: number of points needed\n :param courses: list off all available courses (, num_days, num_points)\n :returns: None\n '''\n self.N = N\n\n # days \n self.m = m * N\n self.days_per_sem = m\n\n # points\n self.k = k\n\n # best sum of days\n self.best_m = None\n self.courses = courses\n self.best_semesters = [[] for i in range(N)]\n\n def _solve(self, current_semesters, courses):\n if(get_m(current_semesters) >= self.best_m):\n # if we already have worse solution\n return\n\n if(get_k(current_semesters) >= self.k):\n # found a better solution\n self.best_m = get_m(current_semesters)\n # tutaj musi by\u0107 deep copy poniewa\u017c\n # p\u0142ytka kopia kpiuje tylko liste semest\u00f3w\n # a nie ka\u017cdy semestr z osobna\n self.best_semesters = copy.deepcopy(current_semesters)\n return \n\n if(len(courses) == 0): \n # no more courses\n return \n\n # iterate over courses\n for i in range(len(courses)):\n copy_courses = copy.deepcopy(courses)\n current_course = courses[i]\n current_semesters_copy = copy.deepcopy(current_semesters)\n # remebmer to add course to semester\n if(not self._add_course(semesters = current_semesters_copy, course = current_course)):\n # course was too large for any of the semesters\n continue\n\n del copy_courses[i]\n # solve for one course less\n self._solve(current_semesters_copy, copy_courses)\n\n def solve(self):\n\n if(self.best_m is None):\n self.best_m = sys.maxsize\n\n # solve for all semesters anf courses\n self._solve(copy.deepcopy(self.best_semesters), copy.deepcopy(self.courses))\n\n # if the solutions has not improved\n if(self.best_m is sys.maxsize):\n raise ValueError('Cannot solve ;_;')\n\n def _add_course(self, semesters, course):\n '''\n adds course the the semesters\n :param semesters: list of semesters, list(list)\n :param course: single course (name, num_days, num_points)\n '''\n # iterate over semesters\n for s in semesters:\n # if a course fits, it sits\n if(get_m(s) + course[1] <= self.days_per_sem):\n s.append(course)\n return True\n return False\n\n def get_best_semesters(self):\n return self.best_semesters\n\n def get_min_num_days(self):\n return self.best_m\n\n\n\n\n \n\n"} {"blob_id": "47905ac969edfdac77838f90fdc5472f6e84be57", "repo_name": "uma-c/CodingProblemSolving", "path": "/2-pointer/sliding_window/fixed_window_size/substr_concat_of_words.py", "length_bytes": 1977, "score": 3.828125, "int_score": 4, "content": "'''\nYou are given a string s and an array of strings words of the same length. Return all starting indices of substring(s) in s that is a concatenation of each word in words exactly once, in any order, and without any intervening characters.\n\nYou can return the answer in any order.\n\n \n\nExample 1:\n\nInput: s = \"barfoothefoobarman\", words = [\"foo\",\"bar\"]\nOutput: [0,9]\nExplanation: Substrings starting at index 0 and 9 are \"barfoo\" and \"foobar\" respectively.\nThe output order does not matter, returning [9,0] is fine too.\nExample 2:\n\nInput: s = \"wordgoodgoodgoodbestword\", words = [\"word\",\"good\",\"best\",\"word\"]\nOutput: []\nExample 3:\n\nInput: s = \"barfoofoobarthefoobarman\", words = [\"bar\",\"foo\",\"the\"]\nOutput: [6,9,12]\n \n\nConstraints:\n\n1 <= s.length <= 104\ns consists of lower-case English letters.\n1 <= words.length <= 5000\n1 <= words[i].length <= 30\nwords[i] consists of lower-case English letters.\n'''\nfrom typing import List\nimport unittest\nfrom collections import Counter\n\n# Time Complexity: O(n), Space Complexity: O(n)\ndef find_substr_with_concat_of_words(s:str, words:List[str])->List[int]:\n if s is None or len(words) < 1 or len(s) < len(words[0]) * len(words):\n return []\n wl = len(words[0])\n cwl = wl * len(words) \n wt = Counter(words)\n required = len(wt) \n finds = []\n i = 0 \n for j in range(cwl - 1, len(s)):\n subseq = s[i:j+1]\n state = Counter()\n formed = 0\n for k in range(0, len(subseq), wl):\n w = subseq[k:k+wl]\n state[w] += 1\n if state[w] == wt[w]:\n formed += 1\n if formed == required:\n finds.append(i) \n i += 1\n\n return finds\n\nclass Tests(unittest.TestCase):\n def test_ex1(self):\n s = \"barfoothefoobarman\"\n words = [\"foo\",\"bar\"]\n result = find_substr_with_concat_of_words(s, words)\n self.assertEqual([0, 9], result)\n\nif __name__ == \"__main__\":\n unittest.main(verbosity = 2)"} {"blob_id": "7c2f026f2fa651c1203c38ec109c737f9c1b5046", "repo_name": "CompPhysics/ComputationalPhysics2", "path": "/doc/LectureNotes/_build/jupyter_execute/resamplingmethods.py", "length_bytes": 27298, "score": 3.625, "int_score": 4, "content": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Resampling Techniques, Bootstrap and Blocking\n# \n# \n# \n# ## Why resampling methods ?\n# **Statistical analysis.**\n# \n# * Our simulations can be treated as *computer experiments*. This is particularly the case for Monte Carlo methods\n# \n# * The results can be analysed with the same statistical tools as we would use analysing experimental data.\n# \n# * As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.\n# \n# \n# \n# \n# ## Statistical analysis\n# * As in other experiments, many numerical experiments have two classes of errors:\n# \n# * Statistical errors\n# \n# * Systematical errors\n# \n# \n# * Statistical errors can be estimated using standard tools from statistics\n# \n# * Systematical errors are method specific and must be treated differently from case to case.\n# \n# \n# \n# \n# \n# \n# \n# ## Statistics, wrapping up from last week\n# Let us analyze the problem by splitting up the correlation term into\n# partial sums of the form:\n\n# $$\n# f_d = \\frac{1}{n-d}\\sum_{k=1}^{n-d}(x_k - \\bar x_n)(x_{k+d} - \\bar x_n)\n# $$\n\n# The correlation term of the error can now be rewritten in terms of\n# $f_d$\n\n# $$\n# \\frac{2}{n}\\sum_{k\n#
\n# \n# $$\n# \\begin{equation} \n# =\\frac{\\tau}{n}\\cdot\\mathrm{var}(x)\n# \\label{_auto1} \\tag{1}\n# \\end{equation}\n# $$\n\n# and we see that $\\mathrm{err}_X$ can be expressed in terms the\n# uncorrelated sample variance times a correction factor $\\tau$ which\n# accounts for the correlation between measurements. We call this\n# correction factor the *autocorrelation time*:\n\n# \n#
\n# \n# $$\n# \\begin{equation}\n# \\tau = 1+2\\sum_{d=1}^{n-1}\\kappa_d\n# \\label{eq:autocorrelation_time} \\tag{2}\n# \\end{equation}\n# $$\n\n# ## Statistics, effective number of correlations\n# For a correlation free experiment, $\\tau$\n# equals 1.\n# \n# We can interpret a sequential\n# correlation as an effective reduction of the number of measurements by\n# a factor $\\tau$. The effective number of measurements becomes:\n\n# $$\n# n_\\mathrm{eff} = \\frac{n}{\\tau}\n# $$\n\n# To neglect the autocorrelation time $\\tau$ will always cause our\n# simple uncorrelated estimate of $\\mathrm{err}_X^2\\approx \\mathrm{var}(x)/n$ to\n# be less than the true sample error. The estimate of the error will be\n# too *good*. On the other hand, the calculation of the full\n# autocorrelation time poses an efficiency problem if the set of\n# measurements is very large.\n# \n# \n# \n# \n# \n# \n# \n# \n# \n# ## Can we understand this? Time Auto-correlation Function\n# \n# The so-called time-displacement autocorrelation $\\phi(t)$ for a quantity $\\mathbf{M}$ is given by\n\n# $$\n# \\phi(t) = \\int dt' \\left[\\mathbf{M}(t')-\\langle \\mathbf{M} \\rangle\\right]\\left[\\mathbf{M}(t'+t)-\\langle \\mathbf{M} \\rangle\\right],\n# $$\n\n# which can be rewritten as\n\n# $$\n# \\phi(t) = \\int dt' \\left[\\mathbf{M}(t')\\mathbf{M}(t'+t)-\\langle \\mathbf{M} \\rangle^2\\right],\n# $$\n\n# where $\\langle \\mathbf{M} \\rangle$ is the average value and\n# $\\mathbf{M}(t)$ its instantaneous value. We can discretize this function as follows, where we used our\n# set of computed values $\\mathbf{M}(t)$ for a set of discretized times (our Monte Carlo cycles corresponding to moving all electrons?)\n\n# \n#
\n# \n# $$\n# \\phi(t) = \\frac{1}{t_{\\mathrm{max}}-t}\\sum_{t'=0}^{t_{\\mathrm{max}}-t}\\mathbf{M}(t')\\mathbf{M}(t'+t)\n# -\\frac{1}{t_{\\mathrm{max}}-t}\\sum_{t'=0}^{t_{\\mathrm{max}}-t}\\mathbf{M}(t')\\times\n# \\frac{1}{t_{\\mathrm{max}}-t}\\sum_{t'=0}^{t_{\\mathrm{max}}-t}\\mathbf{M}(t'+t).\n# \\label{eq:phitf} \\tag{3}\n# $$\n\n# ## Time Auto-correlation Function\n# \n# One should be careful with times close to $t_{\\mathrm{max}}$, the upper limit of the sums \n# becomes small and we end up integrating over a rather small time interval. This means that the statistical\n# error in $\\phi(t)$ due to the random nature of the fluctuations in $\\mathbf{M}(t)$ can become large.\n# \n# One should therefore choose $t \\ll t_{\\mathrm{max}}$.\n# \n# Note that the variable $\\mathbf{M}$ can be any expectation values of interest.\n# \n# \n# \n# The time-correlation function gives a measure of the correlation between the various values of the variable \n# at a time $t'$ and a time $t'+t$. If we multiply the values of $\\mathbf{M}$ at these two different times,\n# we will get a positive contribution if they are fluctuating in the same direction, or a negative value\n# if they fluctuate in the opposite direction. If we then integrate over time, or use the discretized version of, the time correlation function $\\phi(t)$ should take a non-zero value if the fluctuations are \n# correlated, else it should gradually go to zero. For times a long way apart \n# the different values of $\\mathbf{M}$ are most likely \n# uncorrelated and $\\phi(t)$ should be zero.\n# \n# \n# \n# \n# \n# \n# \n# ## Time Auto-correlation Function\n# We can derive the correlation time by observing that our Metropolis algorithm is based on a random\n# walk in the space of all possible spin configurations. \n# Our probability \n# distribution function $\\mathbf{\\hat{w}}(t)$ after a given number of time steps $t$ could be written as\n\n# $$\n# \\mathbf{\\hat{w}}(t) = \\mathbf{\\hat{W}^t\\hat{w}}(0),\n# $$\n\n# with $\\mathbf{\\hat{w}}(0)$ the distribution at $t=0$ and $\\mathbf{\\hat{W}}$ representing the \n# transition probability matrix. \n# We can always expand $\\mathbf{\\hat{w}}(0)$ in terms of the right eigenvectors of \n# $\\mathbf{\\hat{v}}$ of $\\mathbf{\\hat{W}}$ as\n\n# $$\n# \\mathbf{\\hat{w}}(0) = \\sum_i\\alpha_i\\mathbf{\\hat{v}}_i,\n# $$\n\n# resulting in\n\n# $$\n# \\mathbf{\\hat{w}}(t) = \\mathbf{\\hat{W}}^t\\mathbf{\\hat{w}}(0)=\\mathbf{\\hat{W}}^t\\sum_i\\alpha_i\\mathbf{\\hat{v}}_i=\n# \\sum_i\\lambda_i^t\\alpha_i\\mathbf{\\hat{v}}_i,\n# $$\n\n# with $\\lambda_i$ the $i^{\\mathrm{th}}$ eigenvalue corresponding to \n# the eigenvector $\\mathbf{\\hat{v}}_i$.\n# \n# \n# \n# \n# \n# \n# \n# ## Time Auto-correlation Function\n# If we assume that $\\lambda_0$ is the largest eigenvector we see that in the limit $t\\rightarrow \\infty$,\n# $\\mathbf{\\hat{w}}(t)$ becomes proportional to the corresponding eigenvector \n# $\\mathbf{\\hat{v}}_0$. This is our steady state or final distribution. \n# \n# We can relate this property to an observable like the mean energy.\n# With the probabilty $\\mathbf{\\hat{w}}(t)$ (which in our case is the squared trial wave function) we\n# can write the expectation values as\n\n# $$\n# \\langle \\mathbf{M}(t) \\rangle = \\sum_{\\mu} \\mathbf{\\hat{w}}(t)_{\\mu}\\mathbf{M}_{\\mu},\n# $$\n\n# or as the scalar of a vector product\n\n# $$\n# \\langle \\mathbf{M}(t) \\rangle = \\mathbf{\\hat{w}}(t)\\mathbf{m},\n# $$\n\n# with $\\mathbf{m}$ being the vector whose elements are the values of $\\mathbf{M}_{\\mu}$ in its \n# various microstates $\\mu$.\n# \n# \n# \n# \n# \n# ## Time Auto-correlation Function\n# \n# \n# We rewrite this relation as\n\n# $$\n# \\langle \\mathbf{M}(t) \\rangle = \\mathbf{\\hat{w}}(t)\\mathbf{m}=\\sum_i\\lambda_i^t\\alpha_i\\mathbf{\\hat{v}}_i\\mathbf{m}_i.\n# $$\n\n# If we define $m_i=\\mathbf{\\hat{v}}_i\\mathbf{m}_i$ as the expectation value of\n# $\\mathbf{M}$ in the $i^{\\mathrm{th}}$ eigenstate we can rewrite the last equation as\n\n# $$\n# \\langle \\mathbf{M}(t) \\rangle = \\sum_i\\lambda_i^t\\alpha_im_i.\n# $$\n\n# Since we have that in the limit $t\\rightarrow \\infty$ the mean value is dominated by the \n# the largest eigenvalue $\\lambda_0$, we can rewrite the last equation as\n\n# $$\n# \\langle \\mathbf{M}(t) \\rangle = \\langle \\mathbf{M}(\\infty) \\rangle+\\sum_{i\\ne 0}\\lambda_i^t\\alpha_im_i.\n# $$\n\n# We define the quantity\n\n# $$\n# \\tau_i=-\\frac{1}{log\\lambda_i},\n# $$\n\n# and rewrite the last expectation value as\n\n# \n#
\n# \n# $$\n# \\langle \\mathbf{M}(t) \\rangle = \\langle \\mathbf{M}(\\infty) \\rangle+\\sum_{i\\ne 0}\\alpha_im_ie^{-t/\\tau_i}.\n# \\label{eq:finalmeanm} \\tag{4}\n# $$\n\n# ## Time Auto-correlation Function\n# \n# The quantities $\\tau_i$ are the correlation times for the system. They control also the auto-correlation function \n# discussed above. The longest correlation time is obviously given by the second largest\n# eigenvalue $\\tau_1$, which normally defines the correlation time discussed above. For large times, this is the \n# only correlation time that survives. If higher eigenvalues of the transition matrix are well separated from \n# $\\lambda_1$ and we simulate long enough, $\\tau_1$ may well define the correlation time. \n# In other cases we may not be able to extract a reliable result for $\\tau_1$. \n# Coming back to the time correlation function $\\phi(t)$ we can present a more general definition in terms\n# of the mean magnetizations $ \\langle \\mathbf{M}(t) \\rangle$. Recalling that the mean value is equal \n# to $ \\langle \\mathbf{M}(\\infty) \\rangle$ we arrive at the expectation values\n\n# $$\n# \\phi(t) =\\langle \\mathbf{M}(0)-\\mathbf{M}(\\infty)\\rangle \\langle \\mathbf{M}(t)-\\mathbf{M}(\\infty)\\rangle,\n# $$\n\n# resulting in\n\n# $$\n# \\phi(t) =\\sum_{i,j\\ne 0}m_i\\alpha_im_j\\alpha_je^{-t/\\tau_i},\n# $$\n\n# which is appropriate for all times.\n# \n# \n# \n# \n# \n# \n# ## Correlation Time\n# \n# If the correlation function decays exponentially\n\n# $$\n# \\phi (t) \\sim \\exp{(-t/\\tau)}\n# $$\n\n# then the exponential correlation time can be computed as the average\n\n# $$\n# \\tau_{\\mathrm{exp}} = -\\langle \\frac{t}{log|\\frac{\\phi(t)}{\\phi(0)}|} \\rangle.\n# $$\n\n# If the decay is exponential, then\n\n# $$\n# \\int_0^{\\infty} dt \\phi(t) = \\int_0^{\\infty} dt \\phi(0)\\exp{(-t/\\tau)} = \\tau \\phi(0),\n# $$\n\n# which suggests another measure of correlation\n\n# $$\n# \\tau_{\\mathrm{int}} = \\sum_k \\frac{\\phi(k)}{\\phi(0)},\n# $$\n\n# called the integrated correlation time.\n# \n# \n# \n# \n# \n# \n# \n# \n# \n# ## Resampling methods: Jackknife and Bootstrap\n# \n# Two famous\n# resampling methods are the **independent bootstrap** and **the jackknife**. \n# \n# The jackknife is a special case of the independent bootstrap. Still, the jackknife was made\n# popular prior to the independent bootstrap. And as the popularity of\n# the independent bootstrap soared, new variants, such as **the dependent bootstrap**.\n# \n# The Jackknife and independent bootstrap work for\n# independent, identically distributed random variables.\n# If these conditions are not\n# satisfied, the methods will fail. Yet, it should be said that if the data are\n# independent, identically distributed, and we only want to estimate the\n# variance of $\\overline{X}$ (which often is the case), then there is no\n# need for bootstrapping. \n# \n# \n# ## Resampling methods: Jackknife\n# \n# The Jackknife works by making many replicas of the estimator $\\widehat{\\theta}$. \n# The jackknife is a resampling method, we explained that this happens by scrambling the data in some way. When using the jackknife, this is done by systematically leaving out one observation from the vector of observed values $\\hat{x} = (x_1,x_2,\\cdots,X_n)$. \n# Let $\\hat{x}_i$ denote the vector\n\n# $$\n# \\hat{x}_i = (x_1,x_2,\\cdots,x_{i-1},x_{i+1},\\cdots,x_n),\n# $$\n\n# which equals the vector $\\hat{x}$ with the exception that observation\n# number $i$ is left out. Using this notation, define\n# $\\widehat{\\theta}_i$ to be the estimator\n# $\\widehat{\\theta}$ computed using $\\vec{X}_i$. \n# \n# \n# ## Resampling methods: Jackknife estimator\n# \n# To get an estimate for the bias and\n# standard error of $\\widehat{\\theta}$, use the following\n# estimators for each component of $\\widehat{\\theta}$\n\n# $$\n# \\widehat{\\mathrm{Bias}}(\\widehat \\theta,\\theta) = (n-1)\\left( - \\widehat{\\theta} + \\frac{1}{n}\\sum_{i=1}^{n} \\widehat \\theta_i \\right) \\qquad \\text{and} \\qquad \\widehat{\\sigma}^2_{\\widehat{\\theta} } = \\frac{n-1}{n}\\sum_{i=1}^{n}( \\widehat{\\theta}_i - \\frac{1}{n}\\sum_{j=1}^{n}\\widehat \\theta_j )^2.\n# $$\n\n# ## Jackknife code example\n\n# In[1]:\n\n\nfrom numpy import *\nfrom numpy.random import randint, randn\nfrom time import time\n\ndef jackknife(data, stat):\n n = len(data);t = zeros(n); inds = arange(n); t0 = time()\n ## 'jackknifing' by leaving out an observation for each i \n for i in range(n):\n t[i] = stat(delete(data,i) )\n\n # analysis \n print(\"Runtime: %g sec\" % (time()-t0)); print(\"Jackknife Statistics :\")\n print(\"original bias std. error\")\n print(\"%8g %14g %15g\" % (stat(data),(n-1)*mean(t)/n, (n*var(t))**.5))\n\n return t\n\n\n# Returns mean of data samples \ndef stat(data):\n return mean(data)\n\n\nmu, sigma = 100, 15\ndatapoints = 10000\nx = mu + sigma*random.randn(datapoints)\n# jackknife returns the data sample \nt = jackknife(x, stat)\n\n\n# ## Resampling methods: Bootstrap\n# Bootstrapping is a nonparametric approach to statistical inference\n# that substitutes computation for more traditional distributional\n# assumptions and asymptotic results. Bootstrapping offers a number of\n# advantages: \n# 1. The bootstrap is quite general, although there are some cases in which it fails. \n# \n# 2. Because it does not require distributional assumptions (such as normally distributed errors), the bootstrap can provide more accurate inferences when the data are not well behaved or when the sample size is small. \n# \n# 3. It is possible to apply the bootstrap to statistics with sampling distributions that are difficult to derive, even asymptotically. \n# \n# 4. It is relatively simple to apply the bootstrap to complex data-collection plans (such as stratified and clustered samples).\n# \n# \n# \n# \n# \n# ## Resampling methods: Bootstrap background\n# \n# Since $\\widehat{\\theta} = \\widehat{\\theta}(\\hat{X})$ is a function of random variables,\n# $\\widehat{\\theta}$ itself must be a random variable. Thus it has\n# a pdf, call this function $p(\\hat{t})$. The aim of the bootstrap is to\n# estimate $p(\\hat{t})$ by the relative frequency of\n# $\\widehat{\\theta}$. You can think of this as using a histogram\n# in the place of $p(\\hat{t})$. If the relative frequency closely\n# resembles $p(\\vec{t})$, then using numerics, it is straight forward to\n# estimate all the interesting parameters of $p(\\hat{t})$ using point\n# estimators. \n# \n# \n# \n# ## Resampling methods: More Bootstrap background\n# \n# In the case that $\\widehat{\\theta}$ has\n# more than one component, and the components are independent, we use the\n# same estimator on each component separately. If the probability\n# density function of $X_i$, $p(x)$, had been known, then it would have\n# been straight forward to do this by: \n# 1. Drawing lots of numbers from $p(x)$, suppose we call one such set of numbers $(X_1^*, X_2^*, \\cdots, X_n^*)$. \n# \n# 2. Then using these numbers, we could compute a replica of $\\widehat{\\theta}$ called $\\widehat{\\theta}^*$. \n# \n# By repeated use of (1) and (2), many\n# estimates of $\\widehat{\\theta}$ could have been obtained. The\n# idea is to use the relative frequency of $\\widehat{\\theta}^*$\n# (think of a histogram) as an estimate of $p(\\hat{t})$.\n# \n# \n# ## Resampling methods: Bootstrap approach\n# \n# But\n# unless there is enough information available about the process that\n# generated $X_1,X_2,\\cdots,X_n$, $p(x)$ is in general\n# unknown. Therefore, [Efron in 1979](https://projecteuclid.org/euclid.aos/1176344552) asked the\n# question: What if we replace $p(x)$ by the relative frequency\n# of the observation $X_i$; if we draw observations in accordance with\n# the relative frequency of the observations, will we obtain the same\n# result in some asymptotic sense? The answer is yes.\n# \n# \n# Instead of generating the histogram for the relative\n# frequency of the observation $X_i$, just draw the values\n# $(X_1^*,X_2^*,\\cdots,X_n^*)$ with replacement from the vector\n# $\\hat{X}$. \n# \n# \n# ## Resampling methods: Bootstrap steps\n# \n# The independent bootstrap works like this: \n# \n# 1. Draw with replacement $n$ numbers for the observed variables $\\hat{x} = (x_1,x_2,\\cdots,x_n)$. \n# \n# 2. Define a vector $\\hat{x}^*$ containing the values which were drawn from $\\hat{x}$. \n# \n# 3. Using the vector $\\hat{x}^*$ compute $\\widehat{\\theta}^*$ by evaluating $\\widehat \\theta$ under the observations $\\hat{x}^*$. \n# \n# 4. Repeat this process $k$ times. \n# \n# When you are done, you can draw a histogram of the relative frequency of $\\widehat \\theta^*$. This is your estimate of the probability distribution $p(t)$. Using this probability distribution you can estimate any statistics thereof. In principle you never draw the histogram of the relative frequency of $\\widehat{\\theta}^*$. Instead you use the estimators corresponding to the statistic of interest. For example, if you are interested in estimating the variance of $\\widehat \\theta$, apply the etsimator $\\widehat \\sigma^2$ to the values $\\widehat \\theta ^*$.\n# \n# \n# \n# ## Code example for the Bootstrap method\n# \n# The following code starts with a Gaussian distribution with mean value $\\mu =100$ and variance $\\sigma=15$. We use this to generate the data used in the bootstrap analysis. The bootstrap analysis returns a data set after a given number of bootstrap operations (as many as we have data points). This data set consists of estimated mean values for each bootstrap operation. The histogram generated by the bootstrap method shows that the distribution for these mean values is also a Gaussian, centered around the mean value $\\mu=100$ but with standard deviation $\\sigma/\\sqrt{n}$, where $n$ is the number of bootstrap samples (in this case the same as the number of original data points). The value of the standard deviation is what we expect from the central limit theorem.\n\n# In[2]:\n\n\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\nget_ipython().run_line_magic('matplotlib', 'inline')\n\nfrom numpy import *\nfrom numpy.random import randint, randn\nfrom time import time\nfrom scipy.stats import norm\nimport matplotlib.pyplot as plt\n\n# Returns mean of bootstrap samples \ndef stat(data):\n return mean(data)\n\n# Bootstrap algorithm \ndef bootstrap(data, statistic, R):\n t = zeros(R); n = len(data); inds = arange(n); t0 = time()\n\n # non-parametric bootstrap \n for i in range(R):\n t[i] = statistic(data[randint(0,n,n)])\n\n # analysis \n print(\"Runtime: %g sec\" % (time()-t0)); print(\"Bootstrap Statistics :\")\n print(\"original bias std. error\")\n print(\"%8g %8g %14g %15g\" % (statistic(data), std(data), mean(t), std(t)))\n return t\n\n\nmu, sigma = 100, 15\ndatapoints = 10000\nx = mu + sigma*random.randn(datapoints)\n# bootstrap returns the data sample t = bootstrap(x, stat, datapoints)\n# the histogram of the bootstrapped data \nt = bootstrap(x, stat, datapoints)\n# the histogram of the bootstrapped data \nn, binsboot, patches = plt.hist(t, bins=50, density='true',histtype='bar', color='red', alpha=0.75)\n\n# add a 'best fit' line \ny = norm.pdf( binsboot, mean(t), std(t))\nlt = plt.plot(binsboot, y, 'r--', linewidth=1)\nplt.xlabel('Smarts')\nplt.ylabel('Probability')\nplt.axis([99.5, 100.6, 0, 3.0])\nplt.grid(True)\n\nplt.show()\n\n\n# ## Resampling methods: Blocking\n# \n# The blocking method was made popular by [Flyvbjerg and Pedersen (1989)](https://aip.scitation.org/doi/10.1063/1.457480)\n# and has become one of the standard ways to estimate\n# $V(\\widehat{\\theta})$ for exactly one $\\widehat{\\theta}$, namely\n# $\\widehat{\\theta} = \\overline{X}$. \n# \n# Assume $n = 2^d$ for some integer $d>1$ and $X_1,X_2,\\cdots, X_n$ is a stationary time series to begin with. \n# Moreover, assume that the time series is asymptotically uncorrelated. We switch to vector notation by arranging $X_1,X_2,\\cdots,X_n$ in an $n$-tuple. Define:\n\n# $$\n# \\begin{align*}\n# \\hat{X} = (X_1,X_2,\\cdots,X_n).\n# \\end{align*}\n# $$\n\n# The strength of the blocking method is when the number of\n# observations, $n$ is large. For large $n$, the complexity of dependent\n# bootstrapping scales poorly, but the blocking method does not,\n# moreover, it becomes more accurate the larger $n$ is.\n# \n# \n# ## Blocking Transformations\n# We now define\n# blocking transformations. The idea is to take the mean of subsequent\n# pair of elements from $\\vec{X}$ and form a new vector\n# $\\vec{X}_1$. Continuing in the same way by taking the mean of\n# subsequent pairs of elements of $\\vec{X}_1$ we obtain $\\vec{X}_2$, and\n# so on. \n# Define $\\vec{X}_i$ recursively by:\n\n# $$\n# (\\vec{X}_0)_k \\equiv (\\vec{X})_k \\nonumber\n# $$\n\n# \n#
\n# \n# $$\n# \\begin{equation} \n# (\\vec{X}_{i+1})_k \\equiv \\frac{1}{2}\\Big( (\\vec{X}_i)_{2k-1} +\n# (\\vec{X}_i)_{2k} \\Big) \\qquad \\text{for all} \\qquad 1 \\leq i \\leq d-1\n# \\label{_auto2} \\tag{5}\n# \\end{equation}\n# $$\n\n# The quantity $\\vec{X}_k$ is\n# subject to $k$ **blocking transformations**. We now have $d$ vectors\n# $\\vec{X}_0, \\vec{X}_1,\\cdots,\\vec X_{d-1}$ containing the subsequent\n# averages of observations. It turns out that if the components of\n# $\\vec{X}$ is a stationary time series, then the components of\n# $\\vec{X}_i$ is a stationary time series for all $0 \\leq i \\leq d-1$\n# \n# We can then compute the autocovariance, the variance, sample mean, and\n# number of observations for each $i$. \n# Let $\\gamma_i, \\sigma_i^2,\n# \\overline{X}_i$ denote the autocovariance, variance and average of the\n# elements of $\\vec{X}_i$ and let $n_i$ be the number of elements of\n# $\\vec{X}_i$. It follows by induction that $n_i = n/2^i$. \n# \n# \n# ## Blocking Transformations\n# \n# Using the\n# definition of the blocking transformation and the distributive\n# property of the covariance, it is clear that since $h =|i-j|$\n# we can define\n\n# $$\n# \\gamma_{k+1}(h) = cov\\left( ({X}_{k+1})_{i}, ({X}_{k+1})_{j} \\right) \\nonumber\n# $$\n\n# $$\n# = \\frac{1}{4}cov\\left( ({X}_{k})_{2i-1} + ({X}_{k})_{2i}, ({X}_{k})_{2j-1} + ({X}_{k})_{2j} \\right) \\nonumber\n# $$\n\n# \n#
\n# \n# $$\n# \\begin{equation} \n# = \\frac{1}{2}\\gamma_{k}(2h) + \\frac{1}{2}\\gamma_k(2h+1) \\hspace{0.1cm} \\mathrm{h = 0} \n# \\label{_auto3} \\tag{6}\n# \\end{equation}\n# $$\n\n# \n#
\n# \n# $$\n# \\begin{equation} \n# =\\frac{1}{4}\\gamma_k(2h-1) + \\frac{1}{2}\\gamma_k(2h) + \\frac{1}{4}\\gamma_k(2h+1) \\quad \\mathrm{else}\n# \\label{_auto4} \\tag{7}\n# \\end{equation}\n# $$\n\n# The quantity $\\hat{X}$ is asymptotic uncorrelated by assumption, $\\hat{X}_k$ is also asymptotic uncorrelated. Let's turn our attention to the variance of the sample mean $V(\\overline{X})$. \n# \n# \n# ## Blocking Transformations, getting there\n# We have\n\n# \n#
\n# \n# $$\n# \\begin{equation}\n# V(\\overline{X}_k) = \\frac{\\sigma_k^2}{n_k} + \\underbrace{\\frac{2}{n_k} \\sum_{h=1}^{n_k-1}\\left( 1 - \\frac{h}{n_k} \\right)\\gamma_k(h)}_{\\equiv e_k} = \\frac{\\sigma^2_k}{n_k} + e_k \\quad \\text{if} \\quad \\gamma_k(0) = \\sigma_k^2. \n# \\label{_auto5} \\tag{8}\n# \\end{equation}\n# $$\n\n# The term $e_k$ is called the **truncation error**:\n\n# \n#
\n# \n# $$\n# \\begin{equation}\n# e_k = \\frac{2}{n_k} \\sum_{h=1}^{n_k-1}\\left( 1 - \\frac{h}{n_k} \\right)\\gamma_k(h). \n# \\label{_auto6} \\tag{9}\n# \\end{equation}\n# $$\n\n# We can show that $V(\\overline{X}_i) = V(\\overline{X}_j)$ for all $0 \\leq i \\leq d-1$ and $0 \\leq j \\leq d-1$. \n# \n# \n# ## Blocking Transformations, final expressions\n# \n# We can then wrap up\n\n# $$\n# n_{j+1} \\overline{X}_{j+1} = \\sum_{i=1}^{n_{j+1}} (\\hat{X}_{j+1})_i = \\frac{1}{2}\\sum_{i=1}^{n_{j}/2} (\\hat{X}_{j})_{2i-1} + (\\hat{X}_{j})_{2i} \\nonumber\n# $$\n\n# \n#
\n# \n# $$\n# \\begin{equation} \n# = \\frac{1}{2}\\left[ (\\hat{X}_j)_1 + (\\hat{X}_j)_2 + \\cdots + (\\hat{X}_j)_{n_j} \\right] = \\underbrace{\\frac{n_j}{2}}_{=n_{j+1}} \\overline{X}_j = n_{j+1}\\overline{X}_j. \n# \\label{_auto7} \\tag{10}\n# \\end{equation}\n# $$\n\n# By repeated use of this equation we get $V(\\overline{X}_i) = V(\\overline{X}_0) = V(\\overline{X})$ for all $0 \\leq i \\leq d-1$. This has the consequence that\n\n# \n#
\n# \n# $$\n# \\begin{equation}\n# V(\\overline{X}) = \\frac{\\sigma_k^2}{n_k} + e_k \\qquad \\text{for all} \\qquad 0 \\leq k \\leq d-1. \\label{eq:convergence} \\tag{11}\n# \\end{equation}\n# $$\n\n# Flyvbjerg and Petersen demonstrated that the sequence\n# $\\{e_k\\}_{k=0}^{d-1}$ is decreasing, and conjecture that the term\n# $e_k$ can be made as small as we would like by making $k$ (and hence\n# $d$) sufficiently large. The sequence is decreasing (Master of Science thesis by Marius Jonsson, UiO 2018).\n# It means we can apply blocking transformations until\n# $e_k$ is sufficiently small, and then estimate $V(\\overline{X})$ by\n# $\\widehat{\\sigma}^2_k/n_k$. \n# \n# \n# For an elegant solution and proof of the blocking method, see the recent article of [Marius Jonsson (former MSc student of the Computational Physics group)](https://journals.aps.org/pre/abstract/10.1103/PhysRevE.98.043304).\n"} {"blob_id": "da2570dffd5a76c607fa46af46d5b6e1482d1528", "repo_name": "dpazel/music_rep", "path": "/tests/function_tests/test_permutation.py", "length_bytes": 2242, "score": 3.546875, "int_score": 4, "content": "import unittest\n\nfrom function.permutation import Permutation\n\nimport logging\nimport sys\n\n\nclass TestPermutation(unittest.TestCase):\n logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)\n\n def setUp(self):\n pass\n\n def tearDown(self):\n pass\n\n def test_permutation_function(self):\n domain = {1, 2, 3}\n cycles = [[1, 3, 2]]\n p = Permutation(domain, cycles)\n print(p)\n\n assert 3 == p[1]\n assert 2 == p[3]\n assert 1 == p[2]\n\n cycles = [[1, 3, 2], [1, 2]]\n p = Permutation(domain, cycles)\n print(p)\n\n assert 1 == p[1]\n assert 2 == p[3]\n assert 3 == p[2]\n\n def test_permutation_multiplication(self):\n domain = {1, 2, 3, 4}\n cycles_1 = [[1, 3, 2]]\n cycles_2 = [[1, 3], [2, 4]]\n\n p1 = Permutation(domain, cycles_1)\n print('p1={0}'.format(p1))\n p2 = Permutation(domain, cycles_2)\n print('p2={0}'.format(p2))\n\n p3 = p1 * p2\n print('p1 * p2 = {0}'.format(p3))\n\n p3 = p2 * p1\n print('p2 * p1 = {0}'.format(p3))\n\n def test_inversion(self):\n domain = {1, 2, 3, 4}\n cycles = [[1, 3, 4, 2]]\n p = Permutation(domain, cycles)\n\n inverse = p.inverse()\n\n assert 2 == inverse[1]\n assert 4 == inverse[2]\n assert 1 == inverse[3]\n assert 3 == inverse[4]\n\n id_array = p * inverse\n\n assert 1 == id_array[1]\n assert 2 == id_array[2]\n assert 3 == id_array[3]\n assert 4 == id_array[4]\n\n id_array = inverse * p\n\n assert 1 == id_array[1]\n assert 2 == id_array[2]\n assert 3 == id_array[3]\n assert 4 == id_array[4]\n\n def test_book_example(self):\n domain = {1, 2, 3, 4, 5, 6, 7}\n p_cycles = [[1, 3, 4, 2], [6, 5, 7]]\n p = Permutation(domain, p_cycles)\n print(p)\n\n q_cycles = [[1, 3], [2, 4], [5, 7]]\n q = Permutation(domain, q_cycles)\n print(q)\n\n p3 = p * q\n print('p * q = {0}'.format(p3))\n\n p3 = q * p\n print('q * p = {0}'.format(p3))\n\n i = p.inverse()\n print(i)\n print('p * i = {0}'.format(p * i))\n print('i * p = {0}'.format(i * p))\n"} {"blob_id": "f0cac6d58df6db2b53e62eec3caa841b34568059", "repo_name": "1339475125/algorithms", "path": "/\u5728LR\u5b57\u7b26\u4e32\u4e2d\u4ea4\u6362\u76f8\u90bb\u5b57\u7b26.py", "length_bytes": 1220, "score": 3.515625, "int_score": 4, "content": "\"\"\"\n\u7531\u65b9\u6cd5\u4e00\u53ef\u77e5\uff0c\u5982\u679c\u53ef\u4ee5\u5230\u8fbe\u76ee\u6807\u5b57\u7b26\u4e32\uff0c\u90a3\u4e48\u4e00\u5b9a\u6ee1\u8db3 \u8f6c\u6362\u4e0d\u53d8\u6027 \u548c \u53ef\u5230\u8fbe\u6027\u3002\n\n\u53ef\u4ee5\u7528\u53cc\u6307\u9488\u6765\u89e3\u51b3\u8fd9\u4e2a\u95ee\u9898\uff0c\u5bf9\u4e8e i\uff0c j \u4e24\u4e2a\u6307\u9488\uff0c\u5206\u522b\u8ba9\u4ed6\u4eec\u6307\u5411 start \u548c end\uff0c\n\u4e14\u4fdd\u8bc1 start[i] != 'X'\uff0cend[j] != 'X'\u3002\u63a5\u4e0b\u6765\u5f00\u59cb\u79fb\u52a8\u6307\u9488\uff0c\u5982\u679c start[i] != end[j]\uff0c\n\u5219\u4e0d\u6ee1\u8db3 \u8f6c\u6362\u4e0d\u53d8\u6027\uff0c\u5982\u679c start[i] == 'L' \u4e14 i < j\uff0c\u5219\u4e0d\u6ee1\u8db3 \u53ef\u5230\u8fbe\u6027\u3002\n\"\"\"\nclass Solution:\n def canTransform(self, start: str, end: str) -> bool:\n i, j = 0, 0\n m, n = len(start), len(end)\n start = start + '#'\n end = end + '#'\n while i < m or j < n:\n while i < m and start[i] == 'X': i += 1\n print(i)\n while j < n and end[j] == 'X': j += 1\n print(j)\n if start[i] != end[j]:\n return False\n if i < m:\n if start[i] == 'L' and i < j:\n return False\n if start[i] == 'R' and i > j:\n return False\n if i < m:\n i += 1\n if j < n:\n j += 1\n return True\n\n\ns = Solution()\nstart = \"RXXLRXRXL\"\nend = \"XRLXXRRLX\"\ns.canTransform(start, end)"} {"blob_id": "4b998e3fd5cd180e0a5fbd2081f718d7c63ef141", "repo_name": "ZeK1ng/machineVision", "path": "/hw1/hw1_release/filters.py", "length_bytes": 9824, "score": 3.875, "int_score": 4, "content": "\"\"\"\nCS131 - Computer Vision: Foundations and Applications\nAssignment 1\nAuthor: Donsuk Lee (donlee90@stanford.edu)\nDate created: 07/2017\nLast modified: 10/16/2017\nPython Version: 3.5+\n\"\"\"\nfrom skimage import io\nfrom time import time\nimport matplotlib.pyplot as plt\n\nimport numpy as np\n\n\ndef show_image(image):\n imgplot = plt.imshow(image)\n plt.show()\n\n\ndef conv_nested(image, kernel):\n \"\"\"A naive implementation of convolution filter.\n\n This is a naive implementation of convolution using 4 nested for-loops.\n This function computes convolution of an image with a kernel and outputs\n the result that has the same shape as the input image.\n\n Args:\n image: numpy array of shape (Hi, Wi).\n kernel: numpy array of shape (Hk, Wk).\n\n Returns:\n out: numpy array of shape (Hi, Wi).\n \"\"\"\n Hi, Wi = image.shape\n Hk, Wk = kernel.shape\n out = np.zeros((Hi, Wi))\n\n ### YOUR CODE HERE\n for i in range(0, Hi):\n for j in range(0, Wi):\n s = 0\n for ki in range(0, Hk):\n for kj in range(0, Wk):\n curr_i = i - ki + 1\n curr_j = j - kj + 1\n if 0 <= curr_i < Hi and 0 <= curr_j < Wi:\n s = s + image[curr_i][curr_j] * kernel[ki][kj]\n out[i][j] = s\n\n return out\n\n\ndef zero_pad(image, pad_height, pad_width):\n \"\"\" Zero-pad an image.\n\n Ex: a 1x1 image [[1]] with pad_height = 1, pad_width = 2 becomes:\n\n [[0, 0, 0, 0, 0],\n [0, 0, 1, 0, 0],\n [0, 0, 0, 0, 0]] of shape (3, 5)\n\n Args:\n image: numpy array of shape (H, W).\n pad_width: width of the zero padding (left and right padding).\n pad_height: height of the zero padding (bottom and top padding).\n\n Returns:\n out: numpy array of shape (H+2*pad_height, W+2*pad_width).\n \"\"\"\n\n H, W = image.shape\n out = None\n\n ### YOUR CODE HERE\n img_h = H + pad_height\n img_w = W + pad_width\n H += 2 * pad_height\n W += 2 * pad_width\n out = np.zeros((H, W))\n out[pad_height:img_h, pad_width:img_w] = image\n return out\n\n\ndef conv_fast(image, kernel):\n \"\"\" An efficient implementation of convolution filter.\n\n This function uses element-wise multiplication and np.sum()\n to efficiently compute weighted sum of neighborhood at each\n pixel.\n\n Hints:\n - Use the zero_pad function you implemented above\n - There should be two nested for-loops\n - You may find np.flip() and np.sum() useful\n\n Args:\n image: numpy array of shape (Hi, Wi).\n kernel: numpy array of shape (Hk, Wk).\n\n Returns:\n out: numpy array of shape (Hi, Wi).\n \"\"\"\n Hi, Wi = image.shape\n Hk, Wk = kernel.shape\n out = np.zeros((Hi, Wi))\n\n ### YOUR CODE HERE\n kernel = np.flip(np.flip(kernel, 0), 1)\n zr_pd_img = zero_pad(image, Hk // 2, Wk // 2)\n for h in range(0, Hi):\n for w in range(0, Wi):\n k = np.sum(zr_pd_img[h:h + Hk, w:w + Wk] * kernel)\n out[h][w] = k\n ### END YOUR CODE\n kernel = np.flip(np.flip(kernel, 0), 1)\n return out\n\n\ndef conv_faster(image, kernel):\n \"\"\"\n Args:\n image: numpy array of shape (Hi, Wi).\n kernel: numpy array of shape (Hk, Wk).\n\n Returns:\n out: numpy array of shape (Hi, Wi).\n \"\"\"\n Hi, Wi = image.shape\n Hk, Wk = kernel.shape\n out = np.zeros((Hi, Wi))\n\n ### YOUR CODE HERE\n pass\n ### END YOUR CODE\n\n return out\n\n\ndef cross_correlation(f, g):\n \"\"\" Cross-correlation of f and g.\n\n Hint: use the conv_fast function defined above.\n\n Args:\n f: numpy array of shape (Hf, Wf).\n g: numpy array of shape (Hg, Wg).\n\n Returns:\n out: numpy array of shape (Hf, Wf).\n \"\"\"\n ### YOUR CODE HERE\n return conv_fast(f, np.flip(np.flip(g, axis=0), axis=1))\n\n\ndef zero_mean_cross_correlation(f, g):\n \"\"\" Zero-mean cross-correlation of f and g.\n\n Subtract the mean of g from g so that its mean becomes zero.\n\n Hint: you should look up useful numpy functions online for calculating the mean.\n\n Args:\n f: numpy array of shape (Hf, Wf).\n g: numpy array of shape (Hg, Wg).\n\n Returns:\n out: numpy array of shape (Hf, Wf).\n \"\"\"\n\n return conv_fast(f, np.flip(np.flip(g - np.mean(g), axis=0), axis=1))\n\n\ndef normalized_cross_correlation(f, g):\n \"\"\" Normalized cross-correlation of f and g.\n\n Normalize the subimage of f and the template g at each step\n before computing the weighted sum of the two.\n\n Hint: you should look up useful numpy functions online for calculating \n the mean and standard deviation.\n\n Args:\n f: numpy array of shape (Hf, Wf).\n g: numpy array of shape (Hg, Wg).\n\n Returns:\n out: numpy array of shape (Hf, Wf).\n \"\"\"\n\n ### YOUR CODE HERE\n\n Hf, Wf = f.shape\n Hg, Wg = g.shape\n out = np.zeros((Hf, Wf))\n g_normalized = (g - np.mean(g)) / np.std(g)\n zero_pad_f = zero_pad(f, Hg // 2, Wg // 2)\n for h in range(0, Hf):\n for w in range(0, Wf):\n sub_image = zero_pad_f[h:h + Hg, w:w + Wg]\n out[h, w] = (((sub_image - np.mean(sub_image)) / np.std(sub_image)) * g_normalized).sum()\n return out\n\n\ndef test1():\n print(\"-------------Testing conv_nested--------------\")\n kernel = np.array(\n [\n [1, 0, 1],\n [0, 0, 0],\n [1, 0, 0]\n ])\n\n # Create a test image: a white square in the middle\n test_img = np.zeros((9, 9))\n test_img[3:6, 3:6] = 1\n\n # Run your conv_nested function on the test image\n test_output = conv_nested(test_img, kernel)\n\n # Build the expected output\n expected_output = np.zeros((9, 9))\n expected_output[2:7, 2:7] = 1\n expected_output[5:, 5:] = 0\n expected_output[4, 2:5] = 2\n expected_output[2:5, 4] = 2\n expected_output[4, 4] = 3\n # print(expected_output)\n # print(\"----------------------------------------\")\n # print(test_output)\n # Test if the output matches expected output\n assert np.max(test_output - expected_output) < 1e-10, \"Your solution is not correct.\"\n print(\"-------------Conv_nested test passed--------------\")\n\n\ndef test2():\n print(\"-------------Testing conv_faster--------------\")\n kernel = np.array(\n [\n [1, 0, 1],\n [0, 0, 0],\n [1, 0, 0]\n ])\n\n # Create a test image: a white square in the middle\n img = np.zeros((9, 9))\n img[3:6, 3:6] = 1\n t0 = time()\n out_fast = conv_fast(img, kernel)\n t1 = time()\n out_nested = conv_nested(img, kernel)\n t2 = time()\n\n # Compare the running time of the two implementations\n conv_nested_time = t2 - t1\n conv_fast_time = t1 - t0\n print(\"conv_nested: took %f seconds.\" % conv_nested_time)\n print(\"conv_fast: took %f seconds.\" % conv_fast_time)\n # Make sure that the two outputs are the same\n if not (np.max(out_fast - out_nested) < 1e-10):\n print(\"Different outputs! Check your implementation.\")\n print(\"-------------Conv_faster test passed--------------\")\n\n\ndef test3():\n print(\"-------Cross-Correlation in progress--------\")\n img = io.imread('shelf.jpg')\n img_grey = io.imread('shelf.jpg', as_gray=True)\n temp = io.imread('template.jpg')\n temp_grey = io.imread('template.jpg', as_gray=True)\n out = cross_correlation(img_grey, temp_grey)\n y, x = (np.unravel_index(out.argmax(), out.shape))\n print(\"Location With Maximum similarity: \" + str(y) + \",\" + str(x))\n show_image(img_grey)\n show_image(temp_grey)\n show_image(out)\n print(\"-------Cross-Correlation Done--------\")\n\n\ndef test4():\n print(\"-------Zero-Cross-Correlation in progress--------\")\n img = io.imread('shelf.jpg')\n img_grey = io.imread('shelf.jpg', as_gray=True)\n temp = io.imread('template.jpg')\n temp_grey = io.imread('template.jpg', as_gray=True)\n out = zero_mean_cross_correlation(img_grey, temp_grey)\n y, x = (np.unravel_index(out.argmax(), out.shape))\n print(\"Location With Maximum similarity: \" + str(y) + \",\" + str(x))\n show_image(img_grey)\n show_image(temp_grey)\n show_image(out)\n print(\"-------Zero-Cross-Correlation Done--------\")\n\n\ndef check_product_on_shelf(shelf, product):\n out = zero_mean_cross_correlation(shelf, product)\n\n # Scale output by the size of the template\n out = out / float(product.shape[0] * product.shape[1])\n\n # Threshold output (this is arbitrary, you would need to tune the threshold for a real application)\n out = out > 0.025\n\n if np.sum(out) > 0:\n print('The product is on the shelf')\n else:\n print('The product is not on the shelf')\n\n\ndef test5():\n print(\"-------Testing nonexsiting product on shelf--------\")\n # Load image of the shelf without the product\n img2 = io.imread('shelf_soldout.jpg')\n img2_grey = io.imread('shelf_soldout.jpg', as_gray=True)\n temp_grey = io.imread('template.jpg', as_gray=True)\n check_product_on_shelf(img2_grey, temp_grey)\n print(\"-------Testing nonexsiting product on shelf:Done--------\")\n\n\ndef test6():\n print(\"-------Normalized-Cross-Correlation Done--------\")\n img = io.imread('shelf_dark.jpg')\n img_grey = io.imread('shelf_dark.jpg', as_gray=True)\n temp = io.imread('template.jpg')\n temp_grey = io.imread('template.jpg', as_gray=True)\n # Perform cross-correlation between the image and the template\n out = zero_mean_cross_correlation(img_grey, temp_grey)\n # Find the location with maximum similarity\n y, x = (np.unravel_index(out.argmax(), out.shape))\n print(\"Location With Maximum similarity: \" + str(y) + \",\" + str(x))\n show_image(out)\n print(\"-------Normalized-Cross-Correlation Done--------\")\n\n\ndef main():\n test1()\n test2()\n test3()\n test4()\n test5()\n test6()\n\n\nif __name__ == \"__main__\":\n main()\n"} {"blob_id": "e10c73a4cbb5c9e127021a2e0b91db24bfdedb2f", "repo_name": "way2arun/datastructures_algorithms", "path": "/src/arrays/maxScore.py", "length_bytes": 2447, "score": 4.5625, "int_score": 5, "content": "\"\"\"\nMaximum Points You Can Obtain from Cards\nThere are several cards arranged in a row, and each card has an associated number of points The points are given in the integer array cardPoints.\n\nIn one step, you can take one card from the beginning or from the end of the row. You have to take exactly k cards.\n\nYour score is the sum of the points of the cards you have taken.\n\nGiven the integer array cardPoints and the integer k, return the maximum score you can obtain.\n\n\n\nExample 1:\n\nInput: cardPoints = [1,2,3,4,5,6,1], k = 3\nOutput: 12\nExplanation: After the first step, your score will always be 1. However, choosing the rightmost card first will maximize your total score. The optimal strategy is to take the three cards on the right, giving a final score of 1 + 6 + 5 = 12.\nExample 2:\n\nInput: cardPoints = [2,2,2], k = 2\nOutput: 4\nExplanation: Regardless of which two cards you take, your score will always be 4.\nExample 3:\n\nInput: cardPoints = [9,7,7,9,7,7,9], k = 7\nOutput: 55\nExplanation: You have to take all the cards. Your score is the sum of points of all cards.\nExample 4:\n\nInput: cardPoints = [1,1000,1], k = 1\nOutput: 1\nExplanation: You cannot take the card in the middle. Your best score is 1.\nExample 5:\n\nInput: cardPoints = [1,79,80,1,1,1,200,1], k = 3\nOutput: 202\n\n\nConstraints:\n\n1 <= cardPoints.length <= 10^5\n1 <= cardPoints[i] <= 10^4\n1 <= k <= cardPoints.length\n Hide Hint #1\nLet the sum of all points be total_pts. You need to remove a sub-array from cardPoints with length n - k.\n Hide Hint #2\nKeep a window of size n - k over the array. The answer is max(answer, total_pts - sumOfCurrentWindow)\n\n\"\"\"\nfrom typing import List\n\n\nclass Solution:\n def maxScore(self, cardPoints: List[int], k: int) -> int:\n # Solution 1 - 408 ms\n \"\"\"\n best = total = sum(cardPoints[:k])\n for i in range(k - 1, -1, -1):\n total += cardPoints[i + len(cardPoints) - k] - cardPoints[i]\n best = max(best, total)\n return best\n \"\"\"\n # Solution 2 - 364 ms\n size = len(cardPoints) - k\n minSubArraySum = curr = sum(cardPoints[:size])\n\n for i in range(len(cardPoints) - size):\n curr += cardPoints[size + i] - cardPoints[i]\n minSubArraySum = min(minSubArraySum, curr)\n\n return sum(cardPoints) - minSubArraySum\n\n\n# Main Call\ncardPoints = [1, 2, 3, 4, 5, 6, 1]\nk = 3\n\nsolution = Solution()\nprint(solution.maxScore(cardPoints, k))"} {"blob_id": "3340e9f026390684342a50b7eba395a88cd61d93", "repo_name": "f-fathurrahman/ffr-MetodeNumerik", "path": "/chapra_7th/ch21/chapra_example_21_1.py", "length_bytes": 706, "score": 3.609375, "int_score": 4, "content": "def my_func(x):\n return 0.2 + 25*x - 200*x**2 + 675*x**3 - 900*x**4 + 400*x**5\n\na = 0.0\nb = 0.8\nf_a = my_func(a)\nf_b = my_func(b)\n\nI_exact = 1.640533 # from the book\nI = (b - a)*(f_a + f_b)/2\nE_t = I_exact - I\n\u03b5_t = E_t/I_exact * 100\nprint(\"Integral result = %.6f\" % I)\nprint(\"True integral = %.6f\" % I_exact)\nprint(\"True error = %.6f\" % E_t)\nprint(\"\u03b5_t = %.1f%%\" % \u03b5_t)\n\nimport sympy\nx = sympy.symbols(\"x\")\nf = 0.2 + 25*x - 200*x**2 + 675*x**3 - 900*x**4 + 400*x**5\nd2f = f.diff(x,2)\n#sympy.pprint(d2f)\navg_d2f_xi = sympy.integrate( d2f, (x,a,b) )/(b - a)\n#print(\"avg_d2f_xi = \", avg_d2f_xi)\nE_a = -1/12*avg_d2f_xi*(b - a)**3 # Persamaan 21.6\nprint(\"Approx error = %.6f\" % E_a)"} {"blob_id": "3881b676134a24fd54b11efe7113c5ecc83b3eba", "repo_name": "vmontielmg/data-structures-and-algorithms", "path": "/Python/chapter03/p01_three_in_one/miguelHx.py", "length_bytes": 8256, "score": 3.859375, "int_score": 4, "content": "\"\"\"Python version 3.7.0\n3.1 - Three in one\nDescribe how you could use a single array to implement three stacks\n\"\"\"\n\nimport copy\nimport unittest\n\nfrom dataclasses import dataclass\nfrom typing import Generic, TypeVar\nfrom typing import List, Optional, Iterator\n\nT = TypeVar('T')\n\n@dataclass\nclass StackNode(Generic[T]):\n data: T\n next: 'Optional[StackNode[T]]'\n\n@dataclass\nclass StackInfo:\n id: int\n start: int\n end: int\n size: int\n top_index: int\n top_index_next: int\n\n def __init__(self, **kwargs):\n self.__dict__.update(kwargs)\n\n\nclass StackTrio:\n def __init__(self, stack_capacity = 7):\n self.num_stacks = 3\n self.stack_capacity = stack_capacity\n first_stack_info = StackInfo(\n id=1,\n start=0,\n end=stack_capacity - 1,\n size=0,\n top_index=0,\n top_index_next=-1\n )\n second_stack_info = StackInfo(\n id=2,\n start=stack_capacity,\n end=stack_capacity * 2 - 1,\n size=0,\n top_index=stack_capacity,\n top_index_next=-1\n )\n third_stack_info = StackInfo(\n id=3,\n start=stack_capacity * 2,\n end=stack_capacity * 3 - 1,\n size=0,\n top_index=stack_capacity * 2,\n top_index_next=-1\n )\n self.stack_info = {\n 1: first_stack_info,\n 2: second_stack_info,\n 3: third_stack_info\n }\n self.values = [0] * (stack_capacity * self.num_stacks)\n \n def _validate_stack_id(self, stack_id: int):\n \"\"\"Helper method to make sure stack_id\n doesn't go out of range.\n\n Args:\n stack_id (int): id used to refer to correct stack valid ids: 1-3\n \"\"\"\n if stack_id < 1 or stack_id > 3:\n raise IndexError(f'Stack Id out of range. Valid ranges: 1-3, input: {stack_id}')\n\n def is_empty(self, stack_id: int):\n self._validate_stack_id(stack_id)\n return self.stack_info[stack_id].size <= 0\n \n def peek(self, stack_id):\n # this method returns the value at the top index\n self._validate_stack_id(stack_id)\n if self.is_empty(stack_id):\n raise IndexError('Stack is empty. Stack ID: {}'.format(stack_id))\n return self.values[self.stack_info[stack_id].top_index]\n\n def push(self, stack_id, value):\n self._validate_stack_id(stack_id)\n # then, check if stack of interest is full\n if self.stack_info[stack_id].size >= self.stack_capacity:\n raise IndexError('Stack is full. Stack ID: {}'.format(stack_id))\n stack_top_index = self.stack_info[stack_id].top_index\n new_stack_top_index = stack_top_index + 1\n # if empty, then top index and next index stay the same.\n if self.is_empty(stack_id):\n self.values[stack_top_index] = value\n # update stack size.\n self.stack_info[stack_id].size += 1\n return\n\n # otherwise, stack is not empty, and so we\n # first need to update the next and top indices, then update\n # the values accordingly.\n self.stack_info[stack_id].top_index_next = stack_top_index\n self.stack_info[stack_id].top_index = new_stack_top_index\n self.values[new_stack_top_index] = value\n self.stack_info[stack_id].size += 1\n \n \n \n def pop(self, stack_id):\n self._validate_stack_id(stack_id)\n # then, make sure we are not at an empty stack\n if self.is_empty(stack_id):\n raise IndexError('Stack is empty. Stack ID: {}'.format(stack_id))\n # basically, the next index will be one less than top index.\n # when we pop, each top index will get decremented by 1\n original_stack_top_index = self.stack_info[stack_id].top_index\n val_before_pop = self.peek(stack_id)\n self.stack_info[stack_id].top_index -= 1\n self.stack_info[stack_id].top_index_next -= 1\n # clear value\n self.values[original_stack_top_index] = 0\n # decrement size\n self.stack_info[stack_id].size -= 1\n return val_before_pop\n \n def get_size(self, stack_id):\n self._validate_stack_id(stack_id)\n return self.stack_info[stack_id].size\n \n def __str__(self):\n \"\"\"\n We will print out the values\n as well as the stack info for each stack\n \"\"\"\n d = copy.deepcopy(self.stack_info)\n d['values'] = str(self.values)\n return str(d)\n\n\nclass TestThreeInOne(unittest.TestCase):\n \n def test_stack_push(self):\n\n s_trio = StackTrio()\n\n self.assertEqual(s_trio.get_size(1), 0)\n self.assertEqual(s_trio.get_size(2), 0)\n self.assertEqual(s_trio.get_size(3), 0)\n\n s_trio.push(1, 99)\n\n self.assertEqual(s_trio.get_size(1), 1)\n self.assertEqual(s_trio.get_size(2), 0)\n self.assertEqual(s_trio.get_size(3), 0)\n\n s_trio.push(1, 100)\n self.assertEqual(s_trio.get_size(1), 2)\n self.assertEqual(s_trio.get_size(2), 0)\n self.assertEqual(s_trio.get_size(3), 0)\n\n s_trio.push(2, 101)\n\n self.assertEqual(s_trio.get_size(1), 2)\n self.assertEqual(s_trio.get_size(2), 1)\n self.assertEqual(s_trio.get_size(3), 0)\n\n s_trio.push(2, 102)\n self.assertEqual(s_trio.get_size(1), 2)\n self.assertEqual(s_trio.get_size(2), 2)\n self.assertEqual(s_trio.get_size(3), 0)\n\n s_trio.push(3, 103)\n\n self.assertEqual(s_trio.get_size(1), 2)\n self.assertEqual(s_trio.get_size(2), 2)\n self.assertEqual(s_trio.get_size(3), 1)\n\n s_trio.push(3, 104)\n self.assertEqual(s_trio.get_size(1), 2)\n self.assertEqual(s_trio.get_size(2), 2)\n self.assertEqual(s_trio.get_size(3), 2)\n\n \n def test_stack_peek(self):\n s_trio = StackTrio()\n\n self.assertRaises(IndexError, lambda: s_trio.peek(1))\n self.assertRaises(IndexError, lambda: s_trio.peek(2))\n self.assertRaises(IndexError, lambda: s_trio.peek(3))\n\n s_trio.push(1, 99)\n self.assertEqual(s_trio.peek(1), 99)\n s_trio.push(1, 100)\n self.assertEqual(s_trio.peek(1), 100)\n s_trio.push(1, 101)\n self.assertEqual(s_trio.peek(1), 101)\n \n # test that peek still works after popping\n val = s_trio.pop(1)\n self.assertEqual(val, 101)\n self.assertEqual(s_trio.peek(1), 100)\n return\n \n def test_stack_pop(self):\n # first case, attempt to pop an empty stack\n s_trio = StackTrio()\n self.assertRaises(IndexError, lambda: s_trio.pop(1))\n self.assertRaises(IndexError, lambda: s_trio.pop(2))\n self.assertRaises(IndexError, lambda: s_trio.pop(3))\n\n # next, test out pop for each stack\n s_trio.push(1, 199)\n s_trio.push(2, 299)\n s_trio.push(3, 399)\n\n self.assertEqual(s_trio.get_size(1), 1)\n self.assertEqual(s_trio.get_size(2), 1)\n self.assertEqual(s_trio.get_size(3), 1)\n\n val = s_trio.pop(1)\n self.assertEqual(val, 199)\n self.assertEqual(s_trio.get_size(1), 0)\n \n s_trio.push(1, 199)\n s_trio.push(1, 200)\n\n val = s_trio.pop(1)\n self.assertEqual(val, 200)\n self.assertEqual(s_trio.get_size(1), 1)\n\n val = s_trio.pop(2)\n self.assertEqual(val, 299)\n self.assertEqual(s_trio.get_size(2), 0)\n\n s_trio.push(2, 299)\n s_trio.push(2, 300)\n\n val = s_trio.pop(2)\n\n self.assertEqual(val, 300)\n self.assertEqual(s_trio.get_size(2), 1)\n\n val = s_trio.pop(3)\n\n self.assertEqual(val, 399)\n self.assertEqual(s_trio.get_size(3), 0)\n\n s_trio.push(3, 399)\n s_trio.push(3, 400)\n\n self.assertEqual(s_trio.get_size(3), 2)\n\n val = s_trio.pop(3)\n\n self.assertEqual(val, 400)\n self.assertEqual(s_trio.get_size(3), 1)\n \n def test_validate_stack_id(self):\n s_trio = StackTrio()\n self.assertRaises(IndexError, lambda: s_trio._validate_stack_id(4))\n self.assertRaises(IndexError, lambda: s_trio._validate_stack_id(0))\n \n\nif __name__ == '__main__':\n unittest.main()\n"} {"blob_id": "d6c21521dd0172d6bd46544e1bc70a89f036d229", "repo_name": "p2sun/ProjectEuler", "path": "/Problem3.py", "length_bytes": 560, "score": 3.734375, "int_score": 4, "content": "#Problem: The prime factors of 13195 are 5, 7, 13 and 29.\n#What is the largest prime factor of the number 600851475143 ?\n\n#The approach I had was to go through starting from 2 and find\n#and if n is divisible by current number(i), reduce it. i is a prime\n#because if it were composite, it wouldn't be able to divide n\n#since n has already been reduce by its prime factors less than itself\n\n\ndef largest_prime_factor(n):\n i=2\n \n while (i<=n):\n if (n%i == 0):\n n=n/i\n i+=1\n return i-1\nprint largest_prime_factor(600851475143)\n"} {"blob_id": "35a0e66776f0e7f42cfa6baeacb32312056f81bc", "repo_name": "bksahu/dsa", "path": "/dsa/patterns/two_pointers/triplet_with_smaller_sum.py", "length_bytes": 1146, "score": 4.25, "int_score": 4, "content": "\"\"\"\nGiven an array arr of unsorted numbers and a target sum, count all triplets in it such\nthat arr[i] + arr[j] + arr[k] < target where i, j, and k are three different indices. \nWrite a function to return the count of such triplets.\n\nExample 1:\n\nInput: [-1, 0, 2, 3], target=3 \nOutput: 2\nExplanation: There are two triplets whose sum is less than the target: [-1, 0, 3], [-1, 0, 2]\nExample 2:\n\nInput: [-1, 4, 2, 1, 3], target=5 \nOutput: 4\nExplanation: There are four triplets whose sum is less than the target: \n [-1, 1, 4], [-1, 1, 3], [-1, 1, 2], [-1, 2, 3]\n\n\"\"\"\ndef search_pair(arr, firstIdx, target):\n first = arr[firstIdx]\n left, right = firstIdx+1, len(arr)-1\n curr_count = 0\n while left < right:\n if arr[left] + arr[right] + first < target:\n curr_count = right - left\n left += 1\n else:\n right -= 1\n\n return curr_count\n\n\ndef solution(arr, target):\n arr.sort()\n count = 0\n for i in range(len(arr)):\n count += search_pair(arr, i, target)\n return count\n\n\nif __name__ == \"__main__\":\n print(solution([-1, 0, 2, 3], 3))\n print(solution([-1, 4, 2, 1, 3], 5))"} {"blob_id": "fa1b3f9ffce5a2baed166e24e341b94b9f851bb1", "repo_name": "Maxxx911/MZI_labs", "path": "/Lab3/rsa.py", "length_bytes": 1584, "score": 3.671875, "int_score": 4, "content": "from number_generate import NumberGenerate\nimport random\n\nclass Rsa:\n \n def gen_rsa_key(self):\n num_generate = NumberGenerate()\n prime = num_generate.generate(1000)\n print(prime[-80:-1])\n while 1:\n prime_str = input(\"\u0412\u044b\u0431\u0435\u0440\u0438\u0442\u0435 \u0434\u0432\u0430 \u0447\u0438\u0441\u043b\u0430 \u0438\u0437 \u043f\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043b\u0435\u043d\u043d\u044b\u0445 \u0432\u044b\u0448\u0435 \").split(\",\")\n p, q = [int(x) for x in prime_str]\n if (p in prime) and (q in prime):\n break\n else:\n print(\"\u041d\u0435\u0432\u0435\u0440\u043d\u043e\u0435 \u0447\u0438\u0441\u043b\u043e, \u0447\u0438\u043b\u043e \u0434\u043e\u043b\u0436\u043d\u043e \u0431\u044b\u0442\u044c \u043f\u0440\u043e\u0441\u0442\u044b\u043c.\")\n\n N = p * q\n r = (p - 1) * (q - 1)\n r_prime = num_generate.generate(r)\n r_len = len(r_prime)\n e = r_prime[int(random.uniform(0, r_len))]\n d = 0\n for n in range(2,r):\n if (e * n) % r == 1:\n d = n\n break\n\n return ((N, e), (N, d))\n\n def encrypt(self, pub_key,origal):\n N, e = pub_key\n return (origal ** e ) % N\n\n def decrypt(self, pri_key,encry):\n N, d = pri_key\n return (encry ** d) % N\n\nif __name__ == '__main__':\n\n rsa = Rsa()\n pub_key, pri_key = rsa.gen_rsa_key()\n print(\"\u0412\u0430\u0448 \u043f\u0443\u0431\u043b\u0438\u0447\u043d\u044b\u0439 \u043a\u043b\u044e\u0447:\",pub_key)\n print(\"\u0412\u0430\u0448 \u0441\u0435\u043a\u0440\u0435\u0442\u043d\u044b\u0439 \u043a\u043b\u044e\u0447\",pri_key)\n\n origal_text = input(\"\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u0441\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u0435: \")\n encrypt_text = [rsa.encrypt(pub_key, ord(x)) for x in origal_text]\n decrypt_text = [chr(rsa.decrypt(pri_key, x)) for x in encrypt_text]\n\n encrypt_show = \"\".join([chr(x) for x in encrypt_text])\n decrypt_show = \"\".join(decrypt_text)\n\n print(\"\u0417\u0430\u0448\u0438\u0444\u043e\u0432\u0430\u043d\u044b\u0439 \u0442\u0435\u043a\u0441\u0442: \", encrypt_show)\n print(\"\u041e\u0440\u0438\u0433\u0438\u043d\u0430\u043b\u044c\u043d\u044b\u0439 \u0442\u0435\u043a\u0441\u0442: \", decrypt_show)\n"} {"blob_id": "ebbfe21c45e3ccca18fcb1f6ae9e8f0a18426c02", "repo_name": "praatibhsurana/Competitive-Coding", "path": "/Strings/SherlockAndTheValidString.py", "length_bytes": 1490, "score": 4.0625, "int_score": 4, "content": "\"\"\"\nSherlock considers a string to be valid if all characters of the string appear the same number of times. \nIt is also valid if he can remove just 1 character at 1 index in the string, and the remaining characters will occur the same number of times. \nGiven a string s, determine if it is valid. If so, return YES, otherwise return NO.\n\nSample Input \n\nabcdefghhgfedecba\n\nSample Output \n\nYES\n\nExplanation \n\nAll characters occur twice except for e which occurs 3 times. We can delete one instance of e to have a valid string.\n\"\"\"\n#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\nfrom collections import Counter \n\n#\n# Complete the 'isValid' function below.\n#\n# The function is expected to return a STRING.\n# The function accepts STRING s as parameter.\n#\n\ndef isValid(s):\n # Write your code here\n c = Counter(Counter(s).values())\n \n if len(c)==1:\n return \"YES\"\n if len(c)>2:\n return \"NO\"\n if 1 in c.values() and (c[min(c.keys())]==1 or (max(c.keys()) - min(c.keys())==1)):\n return \"YES\"\n else:\n return \"NO\"\n \n \nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n s = input()\n\n result = isValid(s)\n\n fptr.write(result + '\\n')\n\n fptr.close()\n\n# Tried using an approach wherein I append the element count of an alphabets array and then proceed with that. However, it is long and time consuming.\n# Making use of the collections library is the easiest way to solve this problem. \n"} {"blob_id": "866eb6fe238e5f2fc9437cc6625424b63e94003d", "repo_name": "824zzy/Leetcode", "path": "/O_Trie/BitwiseTrie/L2_421_Maximum_XOR_of_Two_Numbers_in_an_Array.py", "length_bytes": 1084, "score": 3.640625, "int_score": 4, "content": "\"\"\" https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/\ntrie + bit manipulation\n1. build a bitwise trie based on 32 bits format numbers\n2. greedily find numbers as opposite as possible from trie bit by bit\n\"\"\"\nfrom header import *\n\nclass Trie:\n def __init__(self):\n self.trie = defaultdict(dict)\n \n def insert(self, word: str) -> None:\n node = self.trie\n for c in map(int, word):\n if c not in node: node[c] = {}\n node = node[c]\n node['#'] = int(word, 2)\n \nclass Solution:\n def findMaximumXOR(self, A: List[int]) -> int:\n # insert binary representation of a number on a trie\n T = Trie()\n for x in A: T.insert(bin(x)[2:].zfill(32))\n \n ans = 0\n for x in A:\n # find numbers as opposite as possible from trie bit by bit\n node = T.trie\n for c in map(int, bin(x)[2:].zfill(32)):\n # find opposite bit\n node = node.get(1-c) or node.get(c)\n ans = max(ans, x^node['#'])\n return ans"} {"blob_id": "c46da2f2fe955432b80e9cd7dc210d70a434b790", "repo_name": "SoulH-qqq/Sunhao", "path": "/sort-python/Quick.py", "length_bytes": 508, "score": 3.6875, "int_score": 4, "content": "def sort(low, high, a):\n pass\n if low=k:\n j-=1\n if i